[teiid-commits] teiid SVN: r3394 - in branches/as7: adminshell and 257 other directories.

teiid-commits at lists.jboss.org teiid-commits at lists.jboss.org
Thu Aug 18 12:17:36 EDT 2011


Author: rareddy
Date: 2011-08-18 12:17:24 -0400 (Thu, 18 Aug 2011)
New Revision: 3394

Added:
   branches/as7/api/src/main/java/org/teiid/PolicyDecider.java
   branches/as7/api/src/main/java/org/teiid/language/WindowFunction.java
   branches/as7/api/src/main/java/org/teiid/language/WindowSpecification.java
   branches/as7/build/kits/jboss-container/teiid-docs/licenses/MPL-1.0.html
   branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/
   branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java
   branches/as7/client/src/main/java/org/teiid/gss/
   branches/as7/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java
   branches/as7/client/src/main/java/org/teiid/gss/MakeGSS.java
   branches/as7/connectors/connector-file/src/test/java/org/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java
   branches/as7/connectors/sandbox/coherence_translator/src/META-INF/
   branches/as7/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml
   branches/as7/connectors/sandbox/coherence_translator/src/test/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java
   branches/as7/connectors/sandbox/coherence_translator/src/test/resources/
   branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.vdb
   branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/BaseDB2ExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java
   branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_clauses.xml
   branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/SizeUtility.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRolePolicyDecider.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DefaultAuthorizationValidator.java
   branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/RankingFunction.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BranchingInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/WindowFunctionProjectNode.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BranchingStatement.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowFunction.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowSpecification.java
   branches/as7/engine/src/main/java/org/teiid/query/tempdata/AlterTempTable.java
   branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/DocumentWrapper.java
   branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/NodeWrapper.java
   branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/StreamingUtils.java
   branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/XQueryEvaluator.java
   branches/as7/engine/src/test/java/org/teiid/common/buffer/impl/TestSizeUtility.java
   branches/as7/engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestWindowFunctions.java
   branches/as7/engine/src/test/resources/TestXMLPlanningEnhancements-testThreeWayOrWithNestedSiblings.xml
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/AssosiateCallerIdentityLoginModule.java
   branches/as7/metadata/DATATYPES.INDEX
   branches/as7/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java
   branches/as7/metadata/src/test/resources/other/
   branches/as7/metadata/src/test/resources/other/test.vdb
   branches/as7/runtime/src/main/java/org/teiid/odbc/PGUtil.java
   branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java
   branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testColumnMetadataWithAlias.expected
   branches/as7/test-integration/common/src/test/resources/relate/
   branches/as7/test-integration/common/src/test/resources/relate/VehicleRentalsVDB.vdb
   branches/as7/test-integration/common/src/test/resources/relate/rentals.sql
   branches/as7/test-integration/common/src/test/resources/relate/test.zip
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_crit.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDoc.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected
Removed:
   branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java
   branches/as7/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java
   branches/as7/client/src/main/java/org/teiid/gss/MakeGSS.java
   branches/as7/connectors/connector-file/src/test/java/org/teiid/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/
   branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java
   branches/as7/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/
   branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java
   branches/as7/connectors/sandbox/coherence_translator/src/test/resources/
   branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.vdb
   branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java
   branches/as7/engine/src/main/java/org/teiid/core/id/IntegerID.java
   branches/as7/engine/src/main/java/org/teiid/core/id/IntegerIDFactory.java
   branches/as7/engine/src/main/java/org/teiid/core/id/InvalidIDException.java
   branches/as7/engine/src/main/java/org/teiid/core/id/LongID.java
   branches/as7/engine/src/main/java/org/teiid/core/id/LongIDFactory.java
   branches/as7/engine/src/main/java/org/teiid/core/id/ObjectID.java
   branches/as7/engine/src/main/java/org/teiid/core/id/ObjectIDFactory.java
   branches/as7/engine/src/main/java/org/teiid/core/id/ParsedObjectID.java
   branches/as7/engine/src/main/java/org/teiid/core/id/StringID.java
   branches/as7/engine/src/main/java/org/teiid/core/id/StringIDFactory.java
   branches/as7/engine/src/main/java/org/teiid/core/id/UUIDFactory.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BreakInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ContinueInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BreakStatement.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/ContinueStatement.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllInGroupSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java
   branches/as7/engine/src/test/java/org/teiid/core/id/
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/NodeTestUtil.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestContinueStatement.java
   branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java
   branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java
   branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java
   branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java
   branches/as7/metadata/src/test/resources/other/test.vdb
   branches/as7/test-integration/common/src/test/resources/relate/VehicleRentalsVDB.vdb
   branches/as7/test-integration/common/src/test/resources/relate/rentals.sql
   branches/as7/test-integration/common/src/test/resources/relate/test.zip
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_crit.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected
   branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDoc.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected
   branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected
Modified:
   branches/as7/
   branches/as7/adminshell/pom.xml
   branches/as7/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
   branches/as7/api/pom.xml
   branches/as7/api/src/main/java/org/teiid/CommandContext.java
   branches/as7/api/src/main/java/org/teiid/connector/DataPlugin.java
   branches/as7/api/src/main/java/org/teiid/events/EventDistributor.java
   branches/as7/api/src/main/java/org/teiid/language/AggregateFunction.java
   branches/as7/api/src/main/java/org/teiid/language/Like.java
   branches/as7/api/src/main/java/org/teiid/language/SQLConstants.java
   branches/as7/api/src/main/java/org/teiid/language/visitor/
   branches/as7/api/src/main/java/org/teiid/language/visitor/CollectorVisitor.java
   branches/as7/api/src/main/java/org/teiid/language/visitor/HierarchyVisitor.java
   branches/as7/api/src/main/java/org/teiid/language/visitor/LanguageObjectVisitor.java
   branches/as7/api/src/main/java/org/teiid/language/visitor/SQLStringVisitor.java
   branches/as7/api/src/main/java/org/teiid/logging/AuditMessage.java
   branches/as7/api/src/main/java/org/teiid/logging/JavaLogger.java
   branches/as7/api/src/main/java/org/teiid/logging/LogManager.java
   branches/as7/api/src/main/java/org/teiid/logging/LogMessage.java
   branches/as7/api/src/main/java/org/teiid/metadata/
   branches/as7/api/src/main/java/org/teiid/metadata/AbstractMetadataRecord.java
   branches/as7/api/src/main/java/org/teiid/metadata/Column.java
   branches/as7/api/src/main/java/org/teiid/metadata/ColumnSet.java
   branches/as7/api/src/main/java/org/teiid/metadata/Datatype.java
   branches/as7/api/src/main/java/org/teiid/metadata/ForeignKey.java
   branches/as7/api/src/main/java/org/teiid/metadata/ProcedureParameter.java
   branches/as7/api/src/main/java/org/teiid/metadata/Schema.java
   branches/as7/api/src/main/java/org/teiid/metadata/Table.java
   branches/as7/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java
   branches/as7/api/src/main/java/org/teiid/translator/ExecutionContext.java
   branches/as7/api/src/main/java/org/teiid/translator/ExecutionFactory.java
   branches/as7/api/src/main/java/org/teiid/translator/FileConnection.java
   branches/as7/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java
   branches/as7/api/src/main/java/org/teiid/translator/TranslatorException.java
   branches/as7/api/src/main/resources/org/
   branches/as7/api/src/main/resources/org/teiid/
   branches/as7/api/src/main/resources/org/teiid/connector/
   branches/as7/api/src/test/java/org/
   branches/as7/api/src/test/java/org/teiid/
   branches/as7/api/src/test/java/org/teiid/connector/
   branches/as7/api/src/test/java/org/teiid/logging/TestLogManager.java
   branches/as7/build/kits/jboss-as7/standalone/configuration/standalone-teiid.xml
   branches/as7/build/kits/jboss-container/deploy/teiid/teiid-cache-manager-jboss-beans-rename-me.xml
   branches/as7/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
   branches/as7/build/kits/jboss-container/teiid-examples/jca/file-ds.xml
   branches/as7/build/kits/jboss-container/teiid-examples/jca/readme.txt
   branches/as7/build/kits/jboss-container/teiid-examples/jca/teiid-jdbc-template-ds.xml
   branches/as7/build/kits/jboss-container/teiid-releasenotes.html
   branches/as7/build/pom.xml
   branches/as7/cache-jbosscache/pom.xml
   branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java
   branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/TupleBatchCacheLoader.java
   branches/as7/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java
   branches/as7/client-jdk15/pom.xml
   branches/as7/client/pom.xml
   branches/as7/client/src/main/java/org/teiid/adminapi/DataPolicy.java
   branches/as7/client/src/main/java/org/teiid/adminapi/Session.java
   branches/as7/client/src/main/java/org/teiid/adminapi/impl/MetadataMapper.java
   branches/as7/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java
   branches/as7/client/src/main/java/org/teiid/client/SourceWarning.java
   branches/as7/client/src/main/java/org/teiid/client/security/ILogon.java
   branches/as7/client/src/main/java/org/teiid/client/security/LogonResult.java
   branches/as7/client/src/main/java/org/teiid/jdbc/BaseDataSource.java
   branches/as7/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java
   branches/as7/client/src/main/java/org/teiid/jdbc/DatabaseMetaDataImpl.java
   branches/as7/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java
   branches/as7/client/src/main/java/org/teiid/jdbc/ExecutionProperties.java
   branches/as7/client/src/main/java/org/teiid/jdbc/JDBCURL.java
   branches/as7/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java
   branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetImpl.java
   branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetMetaDataImpl.java
   branches/as7/client/src/main/java/org/teiid/jdbc/SQLStates.java
   branches/as7/client/src/main/java/org/teiid/jdbc/StatementImpl.java
   branches/as7/client/src/main/java/org/teiid/jdbc/TeiidDataSource.java
   branches/as7/client/src/main/java/org/teiid/jdbc/TeiidSQLException.java
   branches/as7/client/src/main/java/org/teiid/net/TeiidURL.java
   branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnection.java
   branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
   branches/as7/client/src/main/java/org/teiid/netty/handler/codec/serialization/
   branches/as7/client/src/main/resources/org/teiid/jdbc/i18n.properties
   branches/as7/client/src/test/java/org/teiid/client/TestRequestMessage.java
   branches/as7/client/src/test/java/org/teiid/jdbc/TestAllResultsImpl.java
   branches/as7/client/src/test/java/org/teiid/jdbc/TestConnection.java
   branches/as7/client/src/test/java/org/teiid/jdbc/TestSQLException.java
   branches/as7/client/src/test/java/org/teiid/jdbc/TestStatement.java
   branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDataSource.java
   branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java
   branches/as7/client/src/test/java/org/teiid/net/socket/TestSocketServerConnection.java
   branches/as7/client/src/test/resources/metamatrix.keystore
   branches/as7/client/src/test/resources/metamatrix.truststore
   branches/as7/client/src/test/resources/vdb-describe.txt
   branches/as7/common-core/pom.xml
   branches/as7/common-core/src/main/java/org/teiid/core/TeiidException.java
   branches/as7/common-core/src/main/java/org/teiid/core/TeiidRuntimeException.java
   branches/as7/common-core/src/main/java/org/teiid/core/util/ApplicationInfo.java
   branches/as7/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java
   branches/as7/common-core/src/main/java/org/teiid/core/util/StringUtil.java
   branches/as7/common-core/src/test/java/org/teiid/core/TestMetaMatrixRuntimeException.java
   branches/as7/common-core/src/test/java/org/teiid/query/unittest/TimestampUtil.java
   branches/as7/connectors/connector-file/pom.xml
   branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java
   branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileManagedConnectionFactory.java
   branches/as7/connectors/connector-file/src/main/rar/META-INF/ra.xml
   branches/as7/connectors/connector-file/src/main/resources/org/teiid/resource/adapter/file/i18n.properties
   branches/as7/connectors/connector-ldap/pom.xml
   branches/as7/connectors/connector-salesforce/pom.xml
   branches/as7/connectors/connector-ws/pom.xml
   branches/as7/connectors/pom.xml
   branches/as7/connectors/salesforce-api/pom.xml
   branches/as7/connectors/sandbox/pom.xml
   branches/as7/connectors/sandbox/translator-yahoo/pom.xml
   branches/as7/connectors/translator-file/pom.xml
   branches/as7/connectors/translator-file/src/main/java/org/teiid/translator/file/FileExecutionFactory.java
   branches/as7/connectors/translator-file/src/main/resources/org/teiid/translator/file/i18n.properties
   branches/as7/connectors/translator-jdbc/pom.xml
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/AliasModifier.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/EscapeSyntaxModifier.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/FunctionModifier.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCBaseExecution.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCMetdataProcessor.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCPlugin.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCProcedureExecution.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCQueryExecution.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCUpdateExecution.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ModFunctionModifier.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SimpleJDBCExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/TranslatedCommand.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2ExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5ExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java
   branches/as7/connectors/translator-jdbc/src/main/resources/META-INF/services/org.teiid.translator.ExecutionFactory
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/FakeConnection.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/access/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2SqlTranslator.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbyCapabilities.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/TestPostgreSQLTranslator.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase/
   branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java
   branches/as7/connectors/translator-ldap/pom.xml
   branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPExecutionFactory.java
   branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPSyncQueryExecution.java
   branches/as7/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java
   branches/as7/connectors/translator-loopback/pom.xml
   branches/as7/connectors/translator-olap/pom.xml
   branches/as7/connectors/translator-olap/src/main/java/org/teiid/translator/olap/OlapQueryExecution.java
   branches/as7/connectors/translator-salesforce/pom.xml
   branches/as7/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java
   branches/as7/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
   branches/as7/connectors/translator-ws/pom.xml
   branches/as7/console/pom.xml
   branches/as7/console/src/main/resources/META-INF/rhq-plugin.xml
   branches/as7/documentation/admin-guide/pom.xml
   branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/admin-console.xml
   branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/performance.xml
   branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/security.xml
   branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/vdb-deployment.xml
   branches/as7/documentation/admin-guide/src/main/docbook/en-US/images/admin_console.png
   branches/as7/documentation/caching-guide/pom.xml
   branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/codetable.xml
   branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/matviews.xml
   branches/as7/documentation/client-developers-guide/pom.xml
   branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml
   branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml
   branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml
   branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml
   branches/as7/documentation/developer-guide/pom.xml
   branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml
   branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/security.xml
   branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/translator-api.xml
   branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml
   branches/as7/documentation/docbook/custom.dtd
   branches/as7/documentation/pom.xml
   branches/as7/documentation/quick-start-example/pom.xml
   branches/as7/documentation/reference/pom.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/Reference.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/architecture.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/dataroles.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/grammar.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/procedures.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_support.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/system_schema.xml
   branches/as7/documentation/reference/src/main/docbook/en-US/content/translators.xml
   branches/as7/engine/pom.xml
   branches/as7/engine/src/main/java/org/teiid/api/exception/query/QueryParserException.java
   branches/as7/engine/src/main/java/org/teiid/common/buffer/BlockedException.java
   branches/as7/engine/src/main/java/org/teiid/common/buffer/BufferManager.java
   branches/as7/engine/src/main/java/org/teiid/common/buffer/STree.java
   branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBatch.java
   branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
   branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java
   branches/as7/engine/src/main/java/org/teiid/core/id/IDGenerator.java
   branches/as7/engine/src/main/java/org/teiid/core/id/UUID.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/CapabilitiesConverter.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/CachedResults.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/LobWorkItem.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/MetaDataProcessor.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/multisource/
   branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
   branches/as7/engine/src/main/java/org/teiid/dqp/service/SessionService.java
   branches/as7/engine/src/main/java/org/teiid/query/analysis/AnalysisRecord.java
   branches/as7/engine/src/main/java/org/teiid/query/eval/Evaluator.java
   branches/as7/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java
   branches/as7/engine/src/main/java/org/teiid/query/function/FunctionMethods.java
   branches/as7/engine/src/main/java/org/teiid/query/function/FunctionTree.java
   branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java
   branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ArrayAgg.java
   branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java
   branches/as7/engine/src/main/java/org/teiid/query/function/source/SystemSource.java
   branches/as7/engine/src/main/java/org/teiid/query/function/source/XMLSystemFunctions.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java
   branches/as7/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java
   branches/as7/engine/src/main/java/org/teiid/query/metadata/TempCapabilitiesFinder.java
   branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java
   branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java
   branches/as7/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/BatchedUpdatePlanner.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/ProcedurePlanner.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/QueryOptimizer.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/FrameUtil.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleAssignOutputElements.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseJoinStrategy.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleConstants.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleDecomposeJoin.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanSorts.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushLimit.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushSelectCriteria.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseNull.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/QueryUtil.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlannerEnvironment.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java
   branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java
   branches/as7/engine/src/main/java/org/teiid/query/parser/ParseInfo.java
   branches/as7/engine/src/main/java/org/teiid/query/parser/QueryParser.java
   branches/as7/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/BatchCollector.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/QueryProcessor.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ExecDynamicSqlInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/LoopInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ProcedurePlan.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/Program.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/RepeatedInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/proc/WhileInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SubqueryAwareEvaluator.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/TextTableNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/relational/XMLTableNode.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecSqlInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecStagingTableInstruction.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/PlanExecutor.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/RelationalPlanExecutor.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLPlan.java
   branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLProcessorEnvironment.java
   branches/as7/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java
   branches/as7/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java
   branches/as7/engine/src/main/java/org/teiid/query/resolver/command/UpdateProcedureResolver.java
   branches/as7/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java
   branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
   branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageObject.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/GroupBy.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/MatchCriteria.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/OrderByItem.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/Select.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Block.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/IfStatement.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/LoopStatement.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Statement.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/TriggerAction.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/proc/WhileStatement.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AliasSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/DerivedColumn.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ElementSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ExpressionSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/MultipleElementSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/QueryString.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/Reference.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SelectSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SingleElementSymbol.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/TextLine.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AbstractSymbolMappingVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AggregateSymbolCollectorVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ElementCollectorVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ExpressionMappingVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/GroupsUsedByElementsVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/tempdata/IndexInfo.java
   branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
   branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableStore.java
   branches/as7/engine/src/main/java/org/teiid/query/util/CommandContext.java
   branches/as7/engine/src/main/java/org/teiid/query/validator/AbstractValidationVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/validator/UpdateValidator.java
   branches/as7/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java
   branches/as7/engine/src/main/java/org/teiid/query/validator/Validator.java
   branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/PathMapFilter.java
   branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/SaxonXQueryExpression.java
   branches/as7/engine/src/main/java/org/teiid/security/Credentials.java
   branches/as7/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
   branches/as7/engine/src/main/resources/org/teiid/query/i18n.properties
   branches/as7/engine/src/test/java/org/teiid/cdk/CommandBuilder.java
   branches/as7/engine/src/test/java/org/teiid/common/buffer/BufferManagerFactory.java
   branches/as7/engine/src/test/java/org/teiid/common/buffer/TestSTree.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/FakeConnector.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorManager.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCoreRequestHandling.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedPlanCache.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java
   branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
   branches/as7/engine/src/test/java/org/teiid/query/function/TestFunction.java
   branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
   branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java
   branches/as7/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java
   branches/as7/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java
   branches/as7/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java
   branches/as7/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java
   branches/as7/engine/src/test/java/org/teiid/query/parser/TestParseAlter.java
   branches/as7/engine/src/test/java/org/teiid/query/parser/TestParser.java
   branches/as7/engine/src/test/java/org/teiid/query/parser/TestSetQueryParsing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcessor.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestTextTable.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestLimitNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectIntoNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSortNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestUnionAllNode.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/xml/FakePlanExecutor.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestProcessorEnvironment.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java
   branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
   branches/as7/engine/src/test/java/org/teiid/query/resolver/TestAlterResolving.java
   branches/as7/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java
   branches/as7/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java
   branches/as7/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
   branches/as7/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java
   branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java
   branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/lang/TestSelect.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestBreakStatement.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/symbol/TestSearchedCaseExpression.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestAggregateSymbolCollectorVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestExpressionMappingVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestStaticSymbolMappingVisitor.java
   branches/as7/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
   branches/as7/engine/src/test/java/org/teiid/query/validator/TestAlterValidation.java
   branches/as7/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java
   branches/as7/engine/src/test/java/org/teiid/query/validator/TestValidator.java
   branches/as7/engine/src/test/resources/text/cdm_dos_win.txt
   branches/as7/hibernate-dialect/pom.xml
   branches/as7/jboss-integration/pom.xml
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Configuration.java
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Element.java
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/JBossLifeCycleListener.java
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineAdd.java
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineDescription.java
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/TeiidSubsystemParser.java
   branches/as7/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
   branches/as7/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties
   branches/as7/jboss-integration/src/main/resources/schema/jboss-teiid.xsd
   branches/as7/jboss-integration/src/test/java/org/teiid/jboss/TestTeiidConfiguration.java
   branches/as7/jboss-integration/src/test/resources/teiid-model-config.txt
   branches/as7/jboss-integration/src/test/resources/teiid-sample-config.xml
   branches/as7/metadata/
   branches/as7/metadata/pom.xml
   branches/as7/metadata/src/main/resources/System.vdb
   branches/as7/metadata/src/main/resources/org/
   branches/as7/metadata/src/main/resources/org/teiid/
   branches/as7/metadata/src/main/resources/org/teiid/metadata/i18n.properties
   branches/as7/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java
   branches/as7/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java
   branches/as7/metadata/src/test/java/org/teiid/metadata/index/VDBMetadataFactory.java
   branches/as7/pom.xml
   branches/as7/runtime/pom.xml
   branches/as7/runtime/src/main/java/org/teiid/deployers/CompositeVDB.java
   branches/as7/runtime/src/main/java/org/teiid/deployers/ContainerLifeCycleListener.java
   branches/as7/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java
   branches/as7/runtime/src/main/java/org/teiid/deployers/VirtualDatabaseException.java
   branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java
   branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemote.java
   branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java
   branches/as7/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java
   branches/as7/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
   branches/as7/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java
   branches/as7/runtime/src/main/java/org/teiid/transport/LogonImpl.java
   branches/as7/runtime/src/main/java/org/teiid/transport/ODBCClientInstance.java
   branches/as7/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
   branches/as7/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java
   branches/as7/runtime/src/main/java/org/teiid/transport/PgFrontendProtocol.java
   branches/as7/runtime/src/main/java/org/teiid/transport/SSLAwareChannelHandler.java
   branches/as7/runtime/src/main/java/org/teiid/transport/SSLConfiguration.java
   branches/as7/runtime/src/main/resources/org/teiid/runtime/i18n.properties
   branches/as7/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java
   branches/as7/runtime/src/test/java/org/teiid/dqp/service/buffer/TestLocalBufferService.java
   branches/as7/runtime/src/test/java/org/teiid/transport/TestLogonImpl.java
   branches/as7/runtime/src/test/java/org/teiid/transport/TestSocketRemoting.java
   branches/as7/runtime/src/test/resources/dqp/config/
   branches/as7/runtime/src/test/resources/groups.properties
   branches/as7/runtime/src/test/resources/permissions.xml
   branches/as7/runtime/src/test/resources/permissions2.xml
   branches/as7/runtime/src/test/resources/users.properties
   branches/as7/test-integration/common/pom.xml
   branches/as7/test-integration/common/src/test/java/org/teiid/connector/language/
   branches/as7/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime/
   branches/as7/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime/TestMetadataObject.java
   branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/
   branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestCollectorVisitor.java
   branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestSQLStringVisitor.java
   branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java
   branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java
   branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractMMQueryTestCase.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractQueryTest.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestDymamicImportedMetaData.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestMMDatabaseMetaData.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestQueryPlans.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestResultsMetadataWithProvider.java
   branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestVDBMerge.java
   branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMatViews.java
   branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMetadataUpdates.java
   branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestSystemVirtualModel.java
   branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestVirtualDocWithVirtualProc.java
   branches/as7/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java
   branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedureColumns.expected
   branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedures.expected
   branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProceduresWithEscape.expected
   branches/as7/test-integration/common/src/test/resources/TestODBCSchema/test_PG_ATTRIBUTE.expected
   branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPk.expected
   branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPkPrepared.expected
   branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedureColumns.expected
   branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedures.expected
   branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedureParams.expected
   branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedures.expected
   branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testVDBResources.expected
   branches/as7/test-integration/db/pom.xml
   branches/as7/test-integration/db/src/test/java/org/teiid/dynamicvdb/TestVDBLessExecution.java
   branches/as7/test-integration/pom.xml
Log:
TEIID-1720: 1) Forward merge -r 3187:3382,   2) Update to JBoss AS 7.0.1 3) All existing unit tests pass


Property changes on: branches/as7
___________________________________________________________________
Added: svn:mergeinfo
   + /trunk:3188-3382

Modified: branches/as7/adminshell/pom.xml
===================================================================
--- branches/as7/adminshell/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/adminshell/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>teiid-adminshell</artifactId>


Property changes on: branches/as7/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.1.x/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java:2901-2940
   + /branches/7.1.x/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java:2901-2940
/trunk/adminshell/src/main/java/org/teiid/adminshell/AdminShell.java:3188-3382

Modified: branches/as7/api/pom.xml
===================================================================
--- branches/as7/api/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,12 +3,12 @@
   <parent>
     <artifactId>teiid-parent</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>teiid-api</artifactId>
-  <name>Teiid Translator API</name>
-  <description>API for creating Translators and other common extenders in Teiid</description>
+  <name>Teiid API</name>
+  <description>API for creating Translators and other extensions to Teiid</description>
   
   <dependencies>
     <dependency>
@@ -19,6 +19,12 @@
     
     <dependency>
       <groupId>org.jboss.teiid</groupId>
+      <artifactId>teiid-client</artifactId>
+      <scope>provided</scope>
+    </dependency>
+    
+    <dependency>
+      <groupId>org.jboss.teiid</groupId>
       <artifactId>teiid-common-core</artifactId>
       <type>test-jar</type>
       <scope>test</scope>

Modified: branches/as7/api/src/main/java/org/teiid/CommandContext.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/CommandContext.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/CommandContext.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,35 +22,115 @@
 
 package org.teiid;
 
+import java.io.Serializable;
+import java.util.Map;
 import java.util.Properties;
 import java.util.TimeZone;
 
 import javax.security.auth.Subject;
 
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.Session;
+import org.teiid.adminapi.VDB;
+
 /**
  * Context information for the currently executing command.
  * Can be used as an argument to UDFs.
  */
 public interface CommandContext {
 	
+	/**
+	 * Get the current user name
+	 * @return
+	 */
 	String getUserName();
 	
+	/**
+	 * Get the current vdb name
+	 * @return
+	 */
 	String getVdbName();
 	
+	/**
+	 * Get the current vdb version
+	 * @return
+	 */
 	int getVdbVersion();
 	
+	/**
+	 * Get the connection id
+	 * @return
+	 */
 	String getConnectionID();
 	
+	/**
+	 * Get the environment properties.  The returned properties are associated only with the currently executing command.
+	 * The only built-in key/value in the properties is the key "sessionid" with the same value as getConnectionID()
+	 * @return
+	 * @deprecated
+	 */
 	Properties getEnvironmentProperties();
 	
+	/**
+	 * Get the next random double value 
+	 * @return
+	 */
 	double getNextRand();
 	
+	/**
+	 * Sets the seed value and returns the next random double value.  
+	 * Additional calls to {@link #getNextRand()} will be based upon the seed value.
+	 * @param seed
+	 * @return
+	 */
 	double getNextRand(long seed);
 	
+	/**
+	 * Get the processor batch size set on the BufferManager
+	 * @return
+	 */
 	int getProcessorBatchSize();
 	
+	/**
+	 * Get the server {@link TimeZone}
+	 * @return
+	 */
 	TimeZone getServerTimeZone();
 	
+	/**
+	 * Get the current subject
+	 * @return
+	 */
 	Subject getSubject();
 
+	/**
+	 * Get the current session
+	 * @return
+	 */
+	Session getSession();
+
+	/**
+	 * Get the current command payload
+	 * @return may be null if the client did not set a payload
+	 */
+	Serializable getCommandPayload();
+
+	/**
+	 * Get the current request id 
+	 * @return
+	 */
+	String getRequestId();
+	
+	/**
+	 * Get the user's data policies, never null
+	 * @return
+	 */
+	Map<String, DataPolicy> getAllowedDataPolicies();
+	
+	/**
+	 * Get the current vdb
+	 * @return
+	 */
+	VDB getVdb();
+
 }

Copied: branches/as7/api/src/main/java/org/teiid/PolicyDecider.java (from rev 3382, trunk/api/src/main/java/org/teiid/PolicyDecider.java)
===================================================================
--- branches/as7/api/src/main/java/org/teiid/PolicyDecider.java	                        (rev 0)
+++ branches/as7/api/src/main/java/org/teiid/PolicyDecider.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,79 @@
+/*
+ * 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 org.teiid;
+
+import java.util.Set;
+
+import org.teiid.adminapi.DataPolicy.Context;
+import org.teiid.adminapi.DataPolicy.PermissionType;
+
+/**
+ * A policy decider that reports authorization decisions for further action.  
+ * A decider may be called many times for a single user command.  Typically there will be 1 call for every
+ * command/subquery/temp table access/function call.
+ */
+public interface PolicyDecider {
+	
+	/**
+	 * Called by the system hasRole function to determine role membership.
+	 * @param roleName
+	 * @param context
+	 * @return true if the user has the given role name, otherwise false
+	 */
+	boolean hasRole(String roleName, CommandContext context);
+
+	/**
+	 * Returns the set of resources not allowed to be accessed by the current user.
+	 * Resource names are given based upon the FQNs (NOTE these are non-SQL names - identifiers are not quoted).
+	 * @param action
+	 * @param resources
+	 * @param context in which the action is performed.  
+	 *   For example you can have a context of {@link Context#UPDATE} for a {@link PermissionType#READ} for columns used in an UPDATE condition.   
+	 * @param commandContext
+	 * @return the set of inaccessible resources, never null
+	 */
+	Set<String> getInaccessibleResources(PermissionType action,
+			Set<String> resources, Context context,
+			CommandContext commandContext);
+
+	/**
+	 * Checks if the given temp table is accessible.  Typically as long as temp tables can be created, all operations are allowed.
+	 * Resource names are given based upon the FQNs (NOTE these are non-SQL names - identifiers are not quoted).
+	 * @param action
+	 * @param resource
+	 * @param context in which the action is performed.  
+	 *   For example you can have a context of {@link Context#UPDATE} for a {@link PermissionType#READ} for columns used in an UPDATE condition.   
+	 * @param commandContext
+	 * @return true if the access is allowed, otherwise false
+	 */
+	boolean isTempAccessable(PermissionType action, String resource,
+			Context context, CommandContext commandContext);
+	
+	/**
+	 * Determines if an authorization check should proceed
+	 * @param commandContext
+	 * @return
+	 */
+	boolean validateCommand(CommandContext commandContext);
+
+}


Property changes on: branches/as7/api/src/main/java/org/teiid/connector/DataPlugin.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/api/src/main/java/org/teiid/events/EventDistributor.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/events/EventDistributor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/events/EventDistributor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -121,4 +121,11 @@
 	 */
 	void setViewDefinition(String vdbName, int vdbVersion, String schema, String viewName, String definition);
 	
+	/**
+	 * 
+	 * @param vdbName
+	 * @param vdbVersion
+	 * @param viewName
+	 */
+	void refreshMatView(String vdbName, int vdbVersion, String tableName);
 }


Property changes on: branches/as7/api/src/main/java/org/teiid/events/EventDistributor.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/api/src/main/java/org/teiid/events/EventDistributor.java:3340-3349
/trunk/api/src/main/java/org/teiid/events/EventDistributor.java:3188-3382

Modified: branches/as7/api/src/main/java/org/teiid/language/AggregateFunction.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/AggregateFunction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/language/AggregateFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,6 +43,7 @@
     private String aggName;
     private boolean isDistinct;
     private Class<?> type;
+    private Expression condition;
     
     public AggregateFunction(String aggName, boolean isDistinct, Expression exp, Class<?> type) {
         this.expression = exp;
@@ -118,5 +119,17 @@
     public void setType(Class<?> type) {
         this.type = type;
     }
+    
+    /**
+     * 
+     * @return the filter clause condition
+     */
+    public Expression getCondition() {
+		return condition;
+	}
+    
+    public void setCondition(Expression condition) {
+		this.condition = condition;
+	}
 
 }

Modified: branches/as7/api/src/main/java/org/teiid/language/Like.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/Like.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/language/Like.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,11 +25,21 @@
 import org.teiid.language.visitor.LanguageObjectVisitor;
 
 public class Like extends Condition implements Predicate {
+	
+	public enum MatchMode {
+		LIKE,
+		SIMILAR,
+		/**
+		 * The escape char is typically not used in regex mode.
+		 */
+		REGEX
+	}
         
     private Expression leftExpression;
     private Expression rightExpression;
     private Character escapeCharacter;
     private boolean isNegated;
+    private MatchMode mode = MatchMode.LIKE;
     
     public Like(Expression left, Expression right, Character escapeCharacter, boolean negated) {
         leftExpression = left;
@@ -74,5 +84,13 @@
     public void setNegated(boolean negated) {
         this.isNegated = negated;
     }
+    
+    public MatchMode getMode() {
+		return mode;
+	}
+    
+    public void setMode(MatchMode mode) {
+		this.mode = mode;
+	}
 
 }

Modified: branches/as7/api/src/main/java/org/teiid/language/SQLConstants.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/SQLConstants.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/language/SQLConstants.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -46,6 +46,7 @@
 		public static final String GE = ">="; //$NON-NLS-1$
 		public static final String LPAREN = "("; //$NON-NLS-1$
 		public static final String RPAREN = ")"; //$NON-NLS-1$
+		public static final String COLON = ":"; //$NON-NLS-1$
 	}
 	
 	public interface NonReserved {
@@ -111,6 +112,8 @@
 		public static final String INSTEAD = "INSTEAD"; //$NON-NLS-1$
 		public static final String ENABLED = "ENABLED"; //$NON-NLS-1$
 		public static final String DISABLED = "DISABLED"; //$NON-NLS-1$
+		
+		public static final String TRIM = "TRIM";
 	}
 	
 	public interface Reserved {
@@ -247,8 +250,10 @@
 	    public static final String LARGE = "LARGE"; //$NON-NLS-1$
 	    public static final String LATERAL = "LATERAL"; //$NON-NLS-1$
 	    public static final String LEADING = "LEADING"; //$NON-NLS-1$
+	    public static final String LEAVE = "LEAVE"; //$NON-NLS-1$
 	    public static final String LEFT = "LEFT"; //$NON-NLS-1$
 	    public static final String LIKE = "LIKE"; //$NON-NLS-1$
+	    public static final String LIKE_REGEX = "LIKE_REGEX"; //$NON-NLS-1$
 	    public static final String LOCAL = "LOCAL"; //$NON-NLS-1$
 	    public static final String LOCALTIME = "LOCALTIME"; //$NON-NLS-1$
 	    public static final String LOCALTIMESTAMP = "LOCALTIMESTAMP"; //$NON-NLS-1$
@@ -273,6 +278,7 @@
 	    public static final String NUMERIC = "NUMERIC"; //$NON-NLS-1$
 	    public static final String OBJECT = "OBJECT"; //$NON-NLS-1$
 		public static final String OF = "OF"; //$NON-NLS-1$
+		public static final String OFFSET = "OFFSET"; //$NON-NLS-1$
 		public static final String OLD = "OLD"; //$NON-NLS-1$
 		public static final String ON = "ON"; //$NON-NLS-1$
 		public static final String ONLY = "ONLY"; //$NON-NLS-1$
@@ -315,7 +321,7 @@
 	    public static final String SESSION_USER = "SESSION_USER"; //$NON-NLS-1$
 	    public static final String SET = "SET"; //$NON-NLS-1$
 	    public static final String SHORT = "SHORT"; //$NON-NLS-1$
-	    public static final String SIILAR = "SIMILAR"; //$NON-NLS-1$
+	    public static final String SIMILAR = "SIMILAR"; //$NON-NLS-1$
 	    public static final String SMALLINT = "SMALLINT"; //$NON-NLS-1$
 	    public static final String SOME = "SOME"; //$NON-NLS-1$
 	    public static final String SPECIFIC = "SPECIFIC"; //$NON-NLS-1$

Copied: branches/as7/api/src/main/java/org/teiid/language/WindowFunction.java (from rev 3382, trunk/api/src/main/java/org/teiid/language/WindowFunction.java)
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/WindowFunction.java	                        (rev 0)
+++ branches/as7/api/src/main/java/org/teiid/language/WindowFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,81 @@
+/*
+ * 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 org.teiid.language;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.language.visitor.LanguageObjectVisitor;
+
+public class WindowFunction extends BaseLanguageObject implements Expression {
+	
+	private AggregateFunction function;
+	private WindowSpecification windowSpecification;
+	
+	public WindowFunction() {
+		
+	}
+	
+	public AggregateFunction getFunction() {
+		return function;
+	}
+	
+	public void setFunction(AggregateFunction expression) {
+		this.function = expression;
+	}
+	
+	public WindowSpecification getWindowSpecification() {
+		return windowSpecification;
+	}
+	
+	public void setWindowSpecification(WindowSpecification windowSpecification) {
+		this.windowSpecification = windowSpecification;
+	}
+
+	@Override
+	public Class<?> getType() {
+		return function.getType();
+	}
+
+	@Override
+	public void acceptVisitor(LanguageObjectVisitor visitor) {
+		visitor.visit(this);
+	}
+	
+	@Override
+	public int hashCode() {
+		return HashCodeUtil.hashCode(function.hashCode(), windowSpecification);
+	}
+	
+	public boolean equals(Object obj) {
+		if (obj == this) {
+			return true;
+		}
+		if (!(obj instanceof WindowFunction)) {
+			return false;
+		}
+		WindowFunction other = (WindowFunction)obj;
+		return EquivalenceUtil.areEqual(this.function, other.function) &&
+		EquivalenceUtil.areEqual(this.windowSpecification, other.windowSpecification);
+	}
+	
+}

Copied: branches/as7/api/src/main/java/org/teiid/language/WindowSpecification.java (from rev 3382, trunk/api/src/main/java/org/teiid/language/WindowSpecification.java)
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/WindowSpecification.java	                        (rev 0)
+++ branches/as7/api/src/main/java/org/teiid/language/WindowSpecification.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,78 @@
+/*
+ * 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 org.teiid.language;
+
+import java.util.List;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.language.visitor.LanguageObjectVisitor;
+
+public class WindowSpecification extends BaseLanguageObject {
+	
+	private List<Expression> partition;
+	private OrderBy orderBy;
+	
+	public WindowSpecification() {
+		
+	}
+	
+	public List<Expression> getPartition() {
+		return partition;
+	}
+	
+	public void setPartition(List<Expression> grouping) {
+		this.partition = grouping;
+	}
+	
+	public OrderBy getOrderBy() {
+		return orderBy;
+	}
+	
+	public void setOrderBy(OrderBy orderBy) {
+		this.orderBy = orderBy;
+	}
+
+	@Override
+	public void acceptVisitor(LanguageObjectVisitor visitor) {
+		visitor.visit(this);
+	}
+	
+	@Override
+	public int hashCode() {
+		return HashCodeUtil.hashCode(partition.hashCode(), orderBy);
+	}
+	
+	public boolean equals(Object obj) {
+		if (obj == this) {
+			return true;
+		}
+		if (!(obj instanceof WindowSpecification)) {
+			return false;
+		}
+		WindowSpecification other = (WindowSpecification)obj;
+		return EquivalenceUtil.areEqual(this.partition, other.partition) &&
+		EquivalenceUtil.areEqual(this.orderBy, other.orderBy);
+	}
+	
+}


Property changes on: branches/as7/api/src/main/java/org/teiid/language/visitor
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/api/src/main/java/org/teiid/language/visitor/CollectorVisitor.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/visitor/CollectorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/language/visitor/CollectorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,44 +27,9 @@
 import java.util.HashSet;
 import java.util.Set;
 
-import org.teiid.language.AggregateFunction;
-import org.teiid.language.AndOr;
-import org.teiid.language.Argument;
-import org.teiid.language.BatchedUpdates;
-import org.teiid.language.Call;
 import org.teiid.language.ColumnReference;
-import org.teiid.language.Comparison;
-import org.teiid.language.Delete;
-import org.teiid.language.DerivedColumn;
-import org.teiid.language.DerivedTable;
-import org.teiid.language.Exists;
-import org.teiid.language.ExpressionValueSource;
-import org.teiid.language.Function;
-import org.teiid.language.GroupBy;
-import org.teiid.language.In;
-import org.teiid.language.Insert;
-import org.teiid.language.IsNull;
-import org.teiid.language.IteratorValueSource;
-import org.teiid.language.Join;
 import org.teiid.language.LanguageObject;
-import org.teiid.language.Like;
-import org.teiid.language.Limit;
-import org.teiid.language.Literal;
 import org.teiid.language.NamedTable;
-import org.teiid.language.Not;
-import org.teiid.language.OrderBy;
-import org.teiid.language.ScalarSubquery;
-import org.teiid.language.SearchedCase;
-import org.teiid.language.SearchedWhenClause;
-import org.teiid.language.Select;
-import org.teiid.language.SetClause;
-import org.teiid.language.SetQuery;
-import org.teiid.language.SortSpecification;
-import org.teiid.language.SubqueryComparison;
-import org.teiid.language.SubqueryIn;
-import org.teiid.language.Update;
-import org.teiid.language.With;
-import org.teiid.language.WithItem;
 
 
 /**
@@ -72,7 +37,7 @@
  * tree.  Each visit method does an instanceof method to check whether the object
  * is of the expected type.
  */
-public class CollectorVisitor<T> implements LanguageObjectVisitor {
+public class CollectorVisitor<T> extends HierarchyVisitor {
 
     private Class<T> type;
     private Collection<T> objects = new ArrayList<T>();
@@ -80,171 +45,20 @@
     public CollectorVisitor(Class<T> type) {
         this.type = type;
     }
-
+    
     @SuppressWarnings("unchecked")
-	private void checkInstance(LanguageObject obj) {
+    @Override
+    public void visitNode(LanguageObject obj) {
         if(type.isInstance(obj)) {
             this.objects.add((T)obj);
         }
+    	super.visitNode(obj);
     }
-    
+
     public Collection<T> getCollectedObjects() {
         return this.objects;
     }
 
-    public void visit(AggregateFunction obj) {
-        checkInstance(obj);        
-    }
-    
-    public void visit(BatchedUpdates obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Comparison obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(AndOr obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Delete obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(ColumnReference obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Exists obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Function obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(NamedTable obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(GroupBy obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(In obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(DerivedTable obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Insert obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(ExpressionValueSource obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(IsNull obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Join obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Like obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Limit obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Literal obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Not obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(OrderBy obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(SortSpecification obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Argument obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Call obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Select obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(ScalarSubquery obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(SearchedCase obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(DerivedColumn obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(SubqueryComparison obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(SubqueryIn obj) {
-        checkInstance(obj);
-    }
-
-    public void visit(Update obj) {
-        checkInstance(obj);
-    }
-    
-    public void visit(SetQuery obj) {
-        checkInstance(obj);
-    }
-    
-    @Override
-    public void visit(SetClause obj) {
-        checkInstance(obj);
-    }
-    
-    @Override
-    public void visit(SearchedWhenClause obj) {
-    	checkInstance(obj);    	
-    }
-    
-    @Override
-    public void visit(IteratorValueSource obj) {
-    	checkInstance(obj);    	
-    }
-    
-    @Override
-    public void visit(With obj) {
-    	checkInstance(obj); 
-    }
-    
-    @Override
-    public void visit(WithItem obj) {
-    	checkInstance(obj); 
-    }
-
     /**
      * This is a utility method to instantiate and run the visitor in conjunction 
      * with a HierarchyVisitor to collect all objects of the specified type
@@ -255,8 +69,7 @@
      */
     public static <T> Collection<T> collectObjects(Class<T> type, LanguageObject object) {
         CollectorVisitor<T> visitor = new CollectorVisitor<T>(type);
-        DelegatingHierarchyVisitor hierarchyVisitor = new DelegatingHierarchyVisitor(visitor, null);
-        hierarchyVisitor.visitNode(object);
+        visitor.visitNode(object);
         return visitor.getCollectedObjects();
     }
     

Modified: branches/as7/api/src/main/java/org/teiid/language/visitor/HierarchyVisitor.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/visitor/HierarchyVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/language/visitor/HierarchyVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -51,6 +51,8 @@
 import org.teiid.language.SubqueryComparison;
 import org.teiid.language.SubqueryIn;
 import org.teiid.language.Update;
+import org.teiid.language.WindowFunction;
+import org.teiid.language.WindowSpecification;
 import org.teiid.language.With;
 import org.teiid.language.WithItem;
 
@@ -79,6 +81,7 @@
     
     public void visit(AggregateFunction obj) {
         visitNode(obj.getExpression());
+        visitNode(obj.getCondition());
     }
     
     public void visit(BatchedUpdates obj) {
@@ -248,5 +251,16 @@
     	}
     }
     
-
+    @Override
+    public void visit(WindowFunction windowFunction) {
+    	visitNode(windowFunction.getFunction());
+    	visitNode(windowFunction.getWindowSpecification());
+    }
+    
+    @Override
+    public void visit(WindowSpecification windowSpecification) {
+    	visitNodes(windowSpecification.getPartition());
+    	visitNode(windowSpecification.getOrderBy());
+    }
+    
 }

Modified: branches/as7/api/src/main/java/org/teiid/language/visitor/LanguageObjectVisitor.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/visitor/LanguageObjectVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/language/visitor/LanguageObjectVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,7 +22,45 @@
 
 package org.teiid.language.visitor;
 
-import org.teiid.language.*;
+import org.teiid.language.AggregateFunction;
+import org.teiid.language.AndOr;
+import org.teiid.language.Argument;
+import org.teiid.language.BatchedUpdates;
+import org.teiid.language.Call;
+import org.teiid.language.ColumnReference;
+import org.teiid.language.Comparison;
+import org.teiid.language.Delete;
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.DerivedTable;
+import org.teiid.language.Exists;
+import org.teiid.language.ExpressionValueSource;
+import org.teiid.language.Function;
+import org.teiid.language.GroupBy;
+import org.teiid.language.In;
+import org.teiid.language.Insert;
+import org.teiid.language.IsNull;
+import org.teiid.language.IteratorValueSource;
+import org.teiid.language.Join;
+import org.teiid.language.Like;
+import org.teiid.language.Limit;
+import org.teiid.language.Literal;
+import org.teiid.language.NamedTable;
+import org.teiid.language.Not;
+import org.teiid.language.OrderBy;
+import org.teiid.language.ScalarSubquery;
+import org.teiid.language.SearchedCase;
+import org.teiid.language.SearchedWhenClause;
+import org.teiid.language.Select;
+import org.teiid.language.SetClause;
+import org.teiid.language.SetQuery;
+import org.teiid.language.SortSpecification;
+import org.teiid.language.SubqueryComparison;
+import org.teiid.language.SubqueryIn;
+import org.teiid.language.Update;
+import org.teiid.language.WindowFunction;
+import org.teiid.language.WindowSpecification;
+import org.teiid.language.With;
+import org.teiid.language.WithItem;
 
 /**
  */
@@ -64,4 +102,6 @@
 	public void visit(IteratorValueSource obj);
 	public void visit(With obj);
 	public void visit(WithItem obj);
+	public void visit(WindowFunction windowFunction);
+	public void visit(WindowSpecification windowSpecification);
 }

Modified: branches/as7/api/src/main/java/org/teiid/language/visitor/SQLStringVisitor.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/language/visitor/SQLStringVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/language/visitor/SQLStringVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -60,6 +60,7 @@
 import org.teiid.language.Not;
 import org.teiid.language.OrderBy;
 import org.teiid.language.QueryExpression;
+import org.teiid.language.SQLConstants;
 import org.teiid.language.ScalarSubquery;
 import org.teiid.language.SearchedCase;
 import org.teiid.language.SearchedWhenClause;
@@ -71,6 +72,8 @@
 import org.teiid.language.SubqueryIn;
 import org.teiid.language.TableReference;
 import org.teiid.language.Update;
+import org.teiid.language.WindowFunction;
+import org.teiid.language.WindowSpecification;
 import org.teiid.language.With;
 import org.teiid.language.WithItem;
 import org.teiid.language.Argument.Direction;
@@ -174,11 +177,22 @@
         }
         
         if (obj.getExpression() == null) {
-             buffer.append(Tokens.ALL_COLS);
+        	if (SQLConstants.NonReserved.COUNT.equalsIgnoreCase(obj.getName())) {
+        		buffer.append(Tokens.ALL_COLS);
+        	}
         } else {
             append(obj.getExpression());
         }
         buffer.append(Tokens.RPAREN);
+        if (obj.getCondition() != null) {
+        	buffer.append(Tokens.SPACE);
+        	buffer.append(FILTER);
+        	buffer.append(Tokens.LPAREN);
+        	buffer.append(WHERE);
+        	buffer.append(Tokens.SPACE);
+        	append(obj.getCondition());
+        	buffer.append(Tokens.RPAREN);
+        }
     }
 
     public void visit(Comparison obj) {
@@ -272,8 +286,7 @@
         if(elementID != null) {
             elemShortName = getName(elementID);            
         } else {
-            String elementName = obj.getName();
-            elemShortName = getShortName(elementName);
+            elemShortName = obj.getName();
         }
 
         // Check whether a subclass wants to replace the element name to use in special circumstances
@@ -397,7 +410,20 @@
                 }
             }
             buffer.append(Tokens.RPAREN);
-
+        } else if (name.equalsIgnoreCase(NonReserved.TRIM)) {
+        	buffer.append(name);
+        	buffer.append(Tokens.LPAREN);
+        	String value = (String)((Literal)args.get(0)).getValue();
+        	if (!value.equalsIgnoreCase(BOTH)) {
+                buffer.append(value);
+                buffer.append(Tokens.SPACE);
+        	}
+            append(args.get(1));
+            buffer.append(" "); //$NON-NLS-1$
+            buffer.append(FROM);
+            buffer.append(" "); //$NON-NLS-1$
+            buffer.append(args.get(2));
+            buffer.append(")"); //$NON-NLS-1$
         } else {
 
             buffer.append(obj.getName())
@@ -585,9 +611,19 @@
             buffer.append(Tokens.SPACE)
                   .append(NOT);
         }
-        buffer.append(Tokens.SPACE)
-              .append(LIKE)
-              .append(Tokens.SPACE);
+        buffer.append(Tokens.SPACE);
+        switch (obj.getMode()) {
+        case LIKE:
+            buffer.append(LIKE);
+            break;
+        case SIMILAR:
+        	buffer.append(SIMILAR)
+        		  .append(Tokens.SPACE)
+        		  .append(TO);
+        case REGEX:
+        	buffer.append(getLikeRegexString());
+        }
+        buffer.append(Tokens.SPACE);
         append(obj.getRightExpression());
         if (obj.getEscapeCharacter() != null) {
             buffer.append(Tokens.SPACE)
@@ -597,10 +633,13 @@
                   .append(obj.getEscapeCharacter().toString())
                   .append(Tokens.QUOTE);
         }
-        
     }
     
-    public void visit(Limit obj) {
+    protected String getLikeRegexString() {
+		return LIKE_REGEX;
+	}
+
+	public void visit(Limit obj) {
         buffer.append(LIMIT)
               .append(Tokens.SPACE);
         if (obj.getRowOffset() > 0) {
@@ -905,6 +944,36 @@
 		append(obj.getSubquery());
 		buffer.append(Tokens.RPAREN);
     }
+    
+    @Override
+    public void visit(WindowFunction windowFunction) {
+    	append(windowFunction.getFunction());
+    	buffer.append(Tokens.SPACE);
+    	buffer.append(OVER);
+    	buffer.append(Tokens.SPACE);
+    	append(windowFunction.getWindowSpecification());
+    }
+    
+    @Override
+    public void visit(WindowSpecification windowSpecification) {
+    	buffer.append(Tokens.LPAREN);
+    	boolean needsSpace = false;
+    	if (windowSpecification.getPartition() != null) {
+    		buffer.append(PARTITION);
+    		buffer.append(Tokens.SPACE);
+    		buffer.append(BY);
+    		buffer.append(Tokens.SPACE);
+    		append(windowSpecification.getPartition());
+    		needsSpace = true;
+    	}
+    	if (windowSpecification.getOrderBy() != null) {
+    		if (needsSpace) {
+    			buffer.append(Tokens.SPACE);
+    		}
+    		append(windowSpecification.getOrderBy());
+    	}
+    	buffer.append(Tokens.RPAREN);    	
+    }
  
     /**
      * Gets the SQL string representation for a given ILanguageObject.

Modified: branches/as7/api/src/main/java/org/teiid/logging/AuditMessage.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/logging/AuditMessage.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/logging/AuditMessage.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,20 +24,22 @@
 
 import java.util.Arrays;
 
+import org.teiid.CommandContext;
+
 /**
  * Log format for auditing.
  */
 public class AuditMessage {
 	private String context;
 	private String activity;
-	private String principal;
-	private Object[] resources;
+	private String[] resources;
+	private CommandContext commandContext;
 
-	public AuditMessage(String context, String activity, String principal, String[] resources ) {
+	public AuditMessage(String context, String activity, String[] resources, CommandContext commandContext) {
 	    this.context = context;
 	    this.activity = activity;
-	    this.principal = principal;
 	    this.resources = resources;
+	    this.commandContext = commandContext;
 	}
 
     public String getContext() {
@@ -49,15 +51,20 @@
     }
 
     public String getPrincipal() {
-        return this.principal;
+        return this.commandContext.getUserName();
     }
 
-	public Object[] getResources() {
+	public String[] getResources() {
 		return this.resources;
 	}
-
+	
+	public CommandContext getCommandContext() {
+		return commandContext;
+	}
+	
 	public String toString() {
         StringBuffer msg = new StringBuffer();
+        msg.append( this.commandContext.getRequestId());
         msg.append(" ["); //$NON-NLS-1$
         msg.append( getPrincipal() );
         msg.append("] <"); //$NON-NLS-1$


Property changes on: branches/as7/api/src/main/java/org/teiid/logging/JavaLogger.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/api/src/main/java/org/teiid/logging/LogManager.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/logging/LogManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/logging/LogManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -351,6 +351,9 @@
 		if (!isMessageToBeRecorded(context, msgLevel)) {
 			return;
 		} 
+		if (message != null && message.getClass().isArray()) {
+			message = new LogMessage((Object[]) message);
+		}
     	logListener.log(msgLevel, context, e, message);
     }
 
@@ -383,7 +386,7 @@
 		if (msgParts == null || msgParts.length == 0 || !isMessageToBeRecorded(context, level)) {
 			return;
 		} 
-		logListener.log(level, context, new LogMessage(msgParts));
+		logListener.log(level, context, msgParts.length == 1? msgParts[0] : new LogMessage(msgParts));
     }
 
     


Property changes on: branches/as7/api/src/main/java/org/teiid/logging/LogManager.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/api/src/main/java/org/teiid/logging/LogMessage.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/logging/LogMessage.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/logging/LogMessage.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,6 +27,8 @@
 
 public class LogMessage implements Serializable{
 
+	private static final long serialVersionUID = -134503344442009940L;
+	
 	private Object[] msgParts;
 
 	public LogMessage(Object[] msgParts) {


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/AbstractMetadataRecord.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/Column.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/ColumnSet.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/Datatype.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/ForeignKey.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/ProcedureParameter.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/Schema.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/api/src/main/java/org/teiid/metadata/Table.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/metadata/Table.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/metadata/Table.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,8 +23,10 @@
 package org.teiid.metadata;
 
 import java.util.Collection;
+import java.util.HashMap;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Map;
 
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.metadata.AbstractMetadataRecord.DataModifiable;
@@ -80,6 +82,8 @@
 	private transient long lastModified;
 	private transient long lastDataModification;
 	
+	private transient Map<Class<?>, Object> attachments;
+	
     public List<String> getBindings() {
 		return bindings;
 	}
@@ -333,4 +337,46 @@
 		this.updatePlanEnabled = updatePlanEnabled;
 	}
 	
+   /**
+    * Add attachment
+    *
+    * @param <T> the expected type
+    * @param attachment the attachment
+    * @param type the type
+    * @return any previous attachment
+    * @throws IllegalArgumentException for a null name, attachment or type
+    * @throws UnsupportedOperationException when not supported by the implementation
+    */	
+	synchronized public <T> T addAttchment(Class<T> type, T attachment) {
+      if (type == null)
+          throw new IllegalArgumentException("Null type"); //$NON-NLS-1$
+      if (this.attachments == null) {
+    	  this.attachments = new HashMap<Class<?>, Object>();
+      }
+      Object result = this.attachments.put(type, attachment);
+      if (result == null)
+         return null;
+      return type.cast(result);
+	}
+	
+   /**
+    * Get attachment
+    * 
+    * @param <T> the expected type
+    * @param type the type
+    * @return the attachment or null if not present
+    * @throws IllegalArgumentException for a null name or type
+    */
+	synchronized public <T> T getAttachment(Class<T> type) {
+      if (type == null)
+          throw new IllegalArgumentException("Null type"); //$NON-NLS-1$
+      if (this.attachments == null) {
+    	  return null;
+      }
+      Object result = this.attachments.get(type.getName());
+      if (result == null)
+         return null;
+      return type.cast(result);      
+   }
+	
 }
\ No newline at end of file


Property changes on: branches/as7/api/src/main/java/org/teiid/metadata/Table.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/translator/BaseDelegatingExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -111,9 +111,8 @@
 		return delegate.createUpdateExecution(command, executionContext,
 				metadata, connection);
 	}
-	@Override
-	public C getConnection(F factory) throws TranslatorException {
-		return delegate.getConnection(factory);
+	public C getConnection(F factory, ExecutionContext executionContext) throws TranslatorException {
+		return delegate.getConnection(factory, executionContext);
 	}
 	@Override
 	public NullOrder getDefaultNullOrder() {

Modified: branches/as7/api/src/main/java/org/teiid/translator/ExecutionContext.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/translator/ExecutionContext.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/translator/ExecutionContext.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,8 +26,10 @@
 
 import javax.security.auth.Subject;
 
+import org.teiid.adminapi.Session;
 
 
+
 /**
  * The security context provides information about the user context in which
  * this query is being run.
@@ -138,4 +140,10 @@
      * @return
      */
     boolean isTransactional();
+    
+    /**
+     * Get the current session.
+     * @return
+     */
+    Session getSession();
 }

Modified: branches/as7/api/src/main/java/org/teiid/translator/ExecutionFactory.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/translator/ExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/translator/ExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,8 +23,8 @@
 package org.teiid.translator;
 
 import java.util.Collection;
-import java.util.Collections;
 import java.util.Iterator;
+import java.util.LinkedList;
 import java.util.List;
 
 import javax.resource.ResourceException;
@@ -43,6 +43,7 @@
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.FunctionParameter;
 import org.teiid.metadata.MetadataFactory;
 import org.teiid.metadata.RuntimeMetadata;
 
@@ -108,6 +109,8 @@
 	private int maxInSize = DEFAULT_MAX_IN_CRITERIA_SIZE;
 	private int maxDependentInPredicates = DEFAULT_MAX_IN_CRITERIA_SIZE;
 	
+	private LinkedList<FunctionMethod> pushdownFunctionMethods = new LinkedList<FunctionMethod>();
+	
 	/**
 	 * Initialize the connector with supplied configuration
 	 */
@@ -134,8 +137,10 @@
 	 * The default implementation assumes a JCA {@link ConnectionFactory}.  Subclasses should override, if they use 
 	 * another type of connection factory.
 	 * 
+	 * @deprecated
+	 * @see #getConnection(Object, ExecutionContext)
 	 * @param factory
-	 * @return
+	 * @return a connection
 	 * @throws TranslatorException
 	 */
 	@SuppressWarnings("unchecked")
@@ -154,6 +159,22 @@
 	}
 	
 	/**
+	 * Return a connection object from the given connection factory.
+	 * 
+	 * The default implementation assumes a JCA {@link ConnectionFactory}.  Subclasses should override, if they use 
+	 * another type of connection factory or wish to use the {@link ExecutionContext}.  By default calls {@link #getConnection(Object)}
+	 * 
+	 * @param factory
+	 * @param executionContext null if this is a system request for a connection
+	 * @return a connection
+	 * @throws TranslatorException
+	 */
+	public C getConnection(F factory,
+			ExecutionContext executionContext) throws TranslatorException {
+		return getConnection(factory);
+	}
+
+	/**
 	 * Closes a connection object from the given connection factory.
 	 * 
 	 * The default implementation assumes a JCA {@link Connection}.  Subclasses should override, if they use 
@@ -651,10 +672,28 @@
     	return null;
     }
     
+    /**
+     * Get a list of {@link FunctionMethod}s that will be contributed to the SYS schema.  
+     * To avoid conflicts with system functions, the function name should contain a 
+     * qualifier - typically &lt;translator name&gt;.&lt;function name&gt; 
+     * @see ExecutionFactory#addPushDownFunction(String, String, FunctionParameter, FunctionParameter...)
+     * @return
+     */
     public List<FunctionMethod> getPushDownFunctions(){
-    	return Collections.emptyList();
+    	return pushdownFunctionMethods;
     }
     
+    protected FunctionMethod addPushDownFunction(String qualifier, String name, String returnType, String...paramTypes) {
+    	FunctionParameter[] params = new FunctionParameter[paramTypes.length];
+    	for (int i = 0; i < paramTypes.length; i++) {
+			params[i] = new FunctionParameter("param" + (i+1), paramTypes[i]); //$NON-NLS-1$
+		}
+    	FunctionMethod method = new FunctionMethod(qualifier + '.' + name, name, qualifier, params, new FunctionParameter("result", returnType)); //$NON-NLS-1$
+    	method.setNameInSource(name);
+    	pushdownFunctionMethods.add(method);
+    	return method;
+    }
+    
     /**
      * Get the integer value representing the number of values allowed in an IN criteria
      * in the WHERE clause of a query
@@ -686,8 +725,6 @@
     /**
      * <p>Support indicates that the connector supports functions in GROUP BY, such as:
      *  <code>SELECT dayofmonth(theDate), COUNT(*) FROM table GROUP BY dayofmonth(theDate)</code></p>
-     *  
-     * <br>NOT CURRENTLY USED - group by expressions create an inline view for pushdown
      * @since 5.0
      */
     public boolean supportsFunctionsInGroupBy() {
@@ -821,4 +858,56 @@
     public boolean supportsCommonTableExpressions() {
     	return false;
     }
+    
+    /**
+     * @return true if Advanced OLAP operations are supported
+     *  including the aggregate function filter clause.
+     * @since 7.5
+     */
+    public boolean supportsAdvancedOlapOperations() {
+    	return false;
+    }
+    
+    /**
+     * @return true if Elementary OLAP operations are supported
+     *  including window functions and inline window specifications that include 
+     *  simple expressions in partitioning and ordering 
+     * @since 7.5
+     */
+    public boolean supportsElementaryOlapOperations() {
+    	return false;
+    }
+    
+    /**
+     * @return true if all aggregates can have window function order by clauses.
+     * @since 7.5
+     */
+    public boolean supportsWindowOrderByWithAggregates() {
+    	return supportsElementaryOlapOperations();
+    }
+    
+    /**
+     * @return true if array_agg is supported
+     * @since 7.5
+     */
+    public boolean supportsArrayAgg() {
+    	return false;
+    }
+
+    /**
+     * @return true if the SIMILAR TO predicate is supported
+     * @since 7.5
+     */
+	public boolean supportsSimilarTo() {
+		return false;
+	}
+
+	/**
+	 * @return true if the LIKE_REGEX predicate is supported
+	 * @since 7.4
+	 */
+	public boolean supportsLikeRegex() {
+		return false;
+	}
+
 }

Modified: branches/as7/api/src/main/java/org/teiid/translator/FileConnection.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/translator/FileConnection.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/translator/FileConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,6 +23,7 @@
 
 import java.io.File;
 
+import javax.resource.ResourceException;
 import javax.resource.cci.Connection;
 
 import org.teiid.core.util.FileUtils;
@@ -37,7 +38,7 @@
 	 * @param path
 	 * @return
 	 */
-	File getFile(String path);
+	File getFile(String path) throws ResourceException;
 	
 	public static class Util {
 		
@@ -48,7 +49,7 @@
 		 * @param path
 		 * @return
 		 */
-		public static File[] getFiles(String location, FileConnection fc) {
+		public static File[] getFiles(String location, FileConnection fc) throws ResourceException {
 			File datafile = fc.getFile(location);
 	        
 	        if (datafile.isDirectory()) {

Modified: branches/as7/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java
===================================================================
--- branches/as7/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/main/java/org/teiid/translator/SourceSystemFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -58,6 +58,10 @@
 	public static final String SUBSTRING = "substring"; //$NON-NLS-1$
 	public static final String TO_BYTES = "to_bytes"; //$NON-NLS-1$
 	public static final String TO_CHARS = "to_chars"; //$NON-NLS-1$
+	/**
+	 * The trim function is only used for a non-space trim character
+	 */
+	public static final String TRIM = "trim"; //$NON-NLS-1$
 	public static final String UCASE = "ucase"; //$NON-NLS-1$
 	public static final String UNESCAPE = "unescape"; //$NON-NLS-1$
 	


Property changes on: branches/as7/api/src/main/java/org/teiid/translator/TranslatorException.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/resources/org
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/resources/org/teiid
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/main/resources/org/teiid/connector
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/test/java/org
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/test/java/org/teiid
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/api/src/test/java/org/teiid/connector
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/api/src/test/java/org/teiid/logging/TestLogManager.java
===================================================================
--- branches/as7/api/src/test/java/org/teiid/logging/TestLogManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/api/src/test/java/org/teiid/logging/TestLogManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,7 +41,7 @@
  */
 public class TestLogManager extends TestCase {
 
-	String context = "SomeContext"; //$NON-NLS-1$
+	private static final String CONTEXT = "SomeContext"; //$NON-NLS-1$
 	
     /**
      * Constructor for TestLogManager.
@@ -54,7 +54,7 @@
 	@Override
 	protected void setUp() throws Exception {
     	ListLogger logger = new ListLogger();
-    	logger.setLogLevel(context, MessageLevel.DETAIL);
+    	logger.setLogLevel(CONTEXT, MessageLevel.DETAIL);
     	LogManager.logListener = logger;
 	}    
     
@@ -66,11 +66,11 @@
      * Test for boolean isMessageToBeRecorded(String, int)
      */
     public void testIsMessageToBeRecordedString() {
-    	assertTrue(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) ); 
+    	assertTrue(LogManager.isMessageToBeRecorded(CONTEXT, MessageLevel.CRITICAL) ); 
     	
     	ListLogger cfg = (ListLogger)LogManager.logListener;
-        cfg.setLogLevel(context, MessageLevel.NONE);
-        assertFalse(LogManager.isMessageToBeRecorded(context, MessageLevel.CRITICAL) );
+        cfg.setLogLevel(CONTEXT, MessageLevel.NONE);
+        assertFalse(LogManager.isMessageToBeRecorded(CONTEXT, MessageLevel.CRITICAL) );
     }
 
     /**
@@ -78,7 +78,7 @@
      */
     public void testLogMessage() throws Exception {
     	ListLogger cfg = (ListLogger)LogManager.logListener;
-        cfg.setLogLevel(context, MessageLevel.INFO );
+        cfg.setLogLevel(CONTEXT, MessageLevel.INFO );
 
         List<String> sentMsgList = new ArrayList<String>();
         sentMsgList.add("A message 1"); //$NON-NLS-1$
@@ -88,12 +88,12 @@
         sentMsgList.add("A message 5"); //$NON-NLS-1$
         sentMsgList.add("A message 6"); //$NON-NLS-1$
 
-        for (Iterator iter = sentMsgList.iterator(); iter.hasNext();) {
-            String msg = (String) iter.next();
-            LogManager.logInfo(context, msg); 
+        for (Iterator<String> iter = sentMsgList.iterator(); iter.hasNext();) {
+            String msg = iter.next();
+            LogManager.logInfo(CONTEXT, msg); 
         }
         
-        List recevedMsgList = cfg.getLoggedMessages();
+        List<String> recevedMsgList = cfg.getLoggedMessages();
         assertEquals(sentMsgList.size(), recevedMsgList.size());
         assertEquals(sentMsgList, recevedMsgList);
     }
@@ -129,7 +129,7 @@
             return this.messages.size();
         }
 
-        public List getLoggedMessages() {
+        public List<String> getLoggedMessages() {
             return this.messages;
         }
     	

Modified: branches/as7/build/kits/jboss-as7/standalone/configuration/standalone-teiid.xml
===================================================================
--- branches/as7/build/kits/jboss-as7/standalone/configuration/standalone-teiid.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/kits/jboss-as7/standalone/configuration/standalone-teiid.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -59,7 +59,7 @@
     </management>
 
     <profile>
-        <subsystem xmlns="urn:jboss:domain:logging:1.0">
+        <subsystem xmlns="urn:jboss:domain:logging:1.1">
             <console-handler name="CONSOLE">
                 <level name="INFO"/>
                 <formatter>
@@ -104,9 +104,6 @@
                         <user-name>sa</user-name>
                         <password>sa</password>
                     </security>
-                    <validation></validation>
-                    <timeout></timeout>
-                    <statement></statement>
                 </datasource>
                 <drivers>
                     <driver name="h2" module="com.h2database.h2">
@@ -119,7 +116,23 @@
             <deployment-scanner scan-interval="5000" relative-to="jboss.server.base.dir" path="deployments" />
         </subsystem>
         <subsystem xmlns="urn:jboss:domain:ee:1.0" />
-        <subsystem xmlns="urn:jboss:domain:ejb3:1.0" />
+        <subsystem xmlns="urn:jboss:domain:ejb3:1.1" lite="true">
+            <!-- EJB3 pools -->
+            <pools>
+                <bean-instance-pools>
+                    <strict-max-pool name="slsb-strict-max-pool" max-pool-size="20" instance-acquisition-timeout="5"
+                                     instance-acquisition-timeout-unit="MINUTES"/>
+                </bean-instance-pools>
+            </pools>
+
+            <!-- Session bean configurations -->
+            <session-bean>
+                <stateless>
+                    <bean-instance-pool-ref pool-name="slsb-strict-max-pool"/>
+                </stateless>
+            </session-bean>
+
+        </subsystem>
         <subsystem xmlns="urn:jboss:domain:infinispan:1.0" default-cache-container="hibernate">
             <cache-container name="hibernate" default-cache="local-query">
                 <local-cache name="entity">
@@ -141,7 +154,7 @@
             <bean-validation enabled="false" />
             <default-workmanager>
                 <short-running-threads blocking="true">
-                <core-threads count="10" per-cpu="20"/>
+                        <core-threads count="10" per-cpu="20"/>
                         <queue-length count="10" per-cpu="20"/>
                         <max-threads count="10" per-cpu="20"/>
                         <keepalive-time time="10" unit="seconds"/>
@@ -230,7 +243,7 @@
             <security-domains>
                 <security-domain name="other" cache-type="default">
                     <authentication>
-                        <login-module code="UsersRoles" flag="required"/>
+                        <login-module code="Disabled" flag="required"/>
                     </authentication>
                 </security-domain>
                 <security-domain name="teiid-security" cache-type="default">
@@ -270,10 +283,11 @@
             </core-environment>
             <coordinator-environment default-timeout="300"/>
         </subsystem>
-        <subsystem xmlns="urn:jboss:domain:web:1.0">
+        <subsystem xmlns="urn:jboss:domain:web:1.0" default-virtual-server="default-host">
             <connector name="http" scheme="http" protocol="HTTP/1.1" socket-binding="http"/>
-            <virtual-server name="localhost" enable-welcome-root="true">
-                <alias name="example.com" />
+            <virtual-server name="default-host" enable-welcome-root="true">
+               <alias name="localhost" />
+               <alias name="example.com" />
             </virtual-server>
         </subsystem>
         <subsystem xmlns="urn:jboss:domain:weld:1.0" />

Modified: branches/as7/build/kits/jboss-container/deploy/teiid/teiid-cache-manager-jboss-beans-rename-me.xml
===================================================================
--- branches/as7/build/kits/jboss-container/deploy/teiid/teiid-cache-manager-jboss-beans-rename-me.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/kits/jboss-container/deploy/teiid/teiid-cache-manager-jboss-beans-rename-me.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -85,7 +85,7 @@
                             <!-- Hibernate 2LC can replicate custom types, so we use marshalling -->
                             <property name="useRegionBasedMarshalling">true</property>
                             <!-- Must match the value of "useRegionBasedMarshalling" -->
-                            <property name="inactiveOnStartup">true</property>
+                            <property name="inactiveOnStartup">false</property>
 
                             <!-- Disable asynchronous RPC marshalling/sending -->
                             <property name="serializationExecutorPoolSize">0</property>
@@ -145,7 +145,7 @@
         </property>
         <property name="clusterName">${jboss.partition.name:DefaultPartition}-teiid-events</property>
         <property name="multiplexerStack">${jboss.default.jgroups.stack:udp}</property>        
-        <property name="localEventDistributorName">teiid/runtime-engine</property>
+        <property name="localEventDistributorName">teiid/engine-deployer</property>
     </bean>
 
 </deployment>
\ No newline at end of file

Modified: branches/as7/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml
===================================================================
--- branches/as7/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/kits/jboss-container/deploy/teiid/teiid-jboss-beans.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -13,6 +13,10 @@
         <property name="sessionMaxLimit">5000</property>
         <!-- Max allowed time before the session is terminated by the system, 0 indicates unlimited (default 0) -->
         <property name="sessionExpirationTimeLimit">0</property>
+        <!-- authentication type are CLEARTEXT, KRB5 (default:CLEARTEXT) -->
+        <property name="authenticationType">CLEARTEXT</property>
+        <!-- When authenticationType=KRB5, then it requires a kerberos security domain to authorize first before teiid-security takes over -->
+        <property name="krb5SecurityDomain">teiid-krb5</property>
     </bean>
     
     <bean name="BufferService" class="org.teiid.services.BufferServiceImpl">
@@ -25,15 +29,15 @@
         <!-- The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024) -->
         <property name="connectorBatchSize">1024</property>
         <!-- 
-            The number of batch columns to allow in buffer memory. -1 means to automatically calculate a value (default -1).  
+            The approximate amount of buffer memory in kilobytes allowable for a single processing operation (sort, grouping, etc.) regardless of existing memory commitments. -1 means to automatically calculate a value (default -1).  
             See the admin guide for more.          
          -->
-        <property name="maxReserveBatchColumns">-1</property>
+        <property name="maxReserveKb">-1</property>
         <!-- 
-            The number of batch columns guaranteed to a processing operation. -1 means to automatically calculate a value (default -1).
+            The approximate amount of memory in kilobytes allowed to be held by the buffer manager. -1 means to automatically calculate a value (default -1).
             See the admin guide for more.        
          -->
-        <property name="maxProcessingBatchesColumns">-1</property>
+        <property name="maxProcessingKb">-1</property>
         <!--  Max File size in MB (default 2GB)-->
         <property name="maxFileSize">2048</property>
         <!-- Max storage space, in MB, to be used for buffer files (default 50G) -->
@@ -101,7 +105,8 @@
         <property name="cacheFactory"><inject bean="CacheFactory"/></property>
         <property name="resultsetCacheConfig"><inject bean="ResultsetCacheConfig"/></property>
         <property name="preparedPlanCacheConfig"><inject bean="PreparedPlanCacheConfig"/></property>
-        
+        <property name="authorizationValidator"><inject bean="AuthorizationValidator"/></property>
+        <property name="containerLifeCycleListener"><inject bean="JBossLifeCycleListener"/></property>
         <!-- Process pool maximum thread count. (default 64) -->
         <property name="maxThreads">64</property>
         <!-- Max active plans (default 20).  Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts. -->
@@ -117,12 +122,6 @@
         <property name="maxRowsFetchSize">20480</property>
         <!-- The max lob chunk size in KB transferred each time when processing blobs, clobs (100KB default) -->
         <property name="lobChunkSizeInKB">100</property>
-        <!-- Turn on role checking based upon the data roles defined in VDBs. (default true) -->
-        <property name="useDataRoles">true</property>
-        <!-- Sets whether temporary table usage is allowed by default with data roles enabled. If false, the user must have a role that grants creates temporary table rights to use temporary tables. (default true) -->
-        <property name="allowCreateTemporaryTablesByDefault">true</property>
-        <!-- Sets whether functions may be called by default with data roles enabled. If false, a specific permission must exist to call the function. (default true) -->
-        <property name="allowFunctionCallsByDefault">true</property>
         <!-- Long running query threshold, after which a alert can be generated by tooling if configured-->
         <property name="queryThresholdInSecs">600</property>
 		<!-- Maximum rows allowed from a source query. -1 indicates no limit. (default -1)-->
@@ -136,6 +135,24 @@
         <!-- Set to true for the engine to detect local change events. Should be disabled if using external change data capture tools. (default true) -->
         <property name="detectingChangeEvents">true</property>
     </bean>
+    
+    <!-- An authorization validator that by default uses data role information stored in VDBs -->
+    <bean name="AuthorizationValidator" class="org.teiid.dqp.internal.process.DefaultAuthorizationValidator">
+        <!-- Turn on authorization checking (default true) -->
+        <property name="enabled">true</property>
+        <!-- The policy decider to use. (default AuthorizationValidator). 
+             This instance may be changed to another org.teiid.PolicyDecider if needed.
+        -->
+        <property name="policyDecider"><inject bean="PolicyDecider"/></property>
+    </bean>
+   
+    <!-- A policy decider that uses data role information stored in VDBs -->
+    <bean name="PolicyDecider" class="org.teiid.dqp.internal.process.DataRolePolicyDecider">
+    	<!-- Sets whether temporary table usage is allowed by default with data roles enabled. If false, the user must have a role that grants creates temporary table rights to use temporary tables. (default true) -->
+        <property name="allowCreateTemporaryTablesByDefault">true</property>
+        <!-- Sets whether functions may be called by default with data roles enabled. If false, a specific permission must exist to call the function. (default true) -->
+        <property name="allowFunctionCallsByDefault">true</property>
+    </bean>
 
     <!-- JDBC Socket connection properties (SSL see below) -->
     <bean name="JdbcSocketConfiguration" class="org.teiid.transport.SocketConfiguration">
@@ -229,7 +246,7 @@
     <bean name="OdbcSslConfiguration" class="org.teiid.transport.SSLConfiguration">
         <!-- can be one of disabled or enabled 
              disabled = no transport or message level security will be used
-             enabled = traffic will be secured using this configuration
+             enabled = traffic will be secured using this configuration if the client supports SSL
         -->
         <property name="mode">disabled</property>
         <property name="keystoreFilename">cert.keystore</property>
@@ -243,10 +260,36 @@
         <property name="authenticationMode">1-way</property>
     </bean>    
             
-    <!-- teiid's default security domain, replace this with your own if needs to be any other JAAS domain  -->
+    <!-- un-comment and edit for Kerberos login configuration (comment the original login config below)
+    <application-policy xmlns="urn:jboss:security-beans:1.0" name="teiid-krb5">
+        <authentication>
+            <login-module code="com.sun.security.auth.module.Krb5LoginModule" flag="required">
+                <module-option name="storeKey">true</module-option>
+                <module-option name="useKeyTab">true</module-option>
+                <module-option  name="principal">demo at EXAMPLE.COM</module-option>
+                <module-option  name="keyTab">/path/to/krb5.keytab</module-option>
+                <module-option name="doNotPrompt">true</module-option>
+                <module-option name="debug">true</module-option>
+            </login-module>  
+        </authentication>
+    </application-policy>      
+    
     <application-policy xmlns="urn:jboss:security-beans:1.0" name="teiid-security">
         <authentication>
+            <login-module code="org.teiid.jboss.AssosiateCallerIdentityLoginModule" flag="required"/>
             <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
+                <module-option name="password-stacking">useFirstPass</module-option>
+                <module-option name="usersProperties">props/teiid-security-users.properties</module-option>
+                <module-option name="rolesProperties">props/teiid-security-roles.properties</module-option>
+            </login-module>
+        </authentication>
+    </application-policy>     
+    
+     -->
+    <!-- teiid's default security domain, replace this with your own if needs to be any other JAAS domain  --> 
+    <application-policy xmlns="urn:jboss:security-beans:1.0" name="teiid-security">
+        <authentication>
+            <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
                 <!-- property files can found under conf/props directory -->
                 <module-option name="usersProperties">props/teiid-security-users.properties</module-option>
                 <module-option name="rolesProperties">props/teiid-security-roles.properties</module-option>

Copied: branches/as7/build/kits/jboss-container/teiid-docs/licenses/MPL-1.0.html (from rev 3382, trunk/build/kits/jboss-container/teiid-docs/licenses/MPL-1.0.html)
===================================================================
--- branches/as7/build/kits/jboss-container/teiid-docs/licenses/MPL-1.0.html	                        (rev 0)
+++ branches/as7/build/kits/jboss-container/teiid-docs/licenses/MPL-1.0.html	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,421 @@
+<html><head>
+<meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>Mozilla Public License version 1.0</title>
+</head><body link="#0000ee" text="#000000" vlink="#551a8b" alink="#ff0000" bgcolor="#ffffff">
+
+<p align="CENTER">
+  <font size="+2"><b>MOZILLA PUBLIC LICENSE</b></font><br>
+  <b>Version 1.0</b>
+</p>
+
+<p></p><hr width="20%"><p>
+
+</p><p><b>1. Definitions.</b>
+</p><ul>
+
+    <b>1.1. ``Contributor''</b> means each entity that creates or contributes
+    to the creation of Modifications.
+
+    <p><b>1.2. ``Contributor Version''</b> means the combination of the
+    Original Code, prior Modifications used by a Contributor, and the
+    Modifications made by that particular Contributor.
+
+    </p><p><b>1.3. ``Covered Code''</b> means the Original Code or Modifications
+    or the combination of the Original Code and Modifications, in each case
+    including portions thereof<b>.</b>
+
+    </p><p><b>1.4. ``Electronic Distribution Mechanism''</b> means a mechanism
+    generally accepted in the software development community for the
+    electronic transfer of data.
+
+    </p><p><b>1.5. ``Executable''</b> means Covered Code in any form other than
+    Source Code.
+
+    </p><p><b>1.6. ``Initial Developer''</b> means the individual or entity
+    identified as the Initial Developer in the Source Code notice required by
+    <b>Exhibit A</b>.
+
+    </p><p><b>1.7. ``Larger Work''</b> means a work which combines Covered Code
+    or portions thereof with code not governed by the terms of this License.
+
+    </p><p><b>1.8. ``License''</b> means this document.
+
+    </p><p><b>1.9. ``Modifications''</b> means any addition to or deletion from
+    the substance or structure of either the Original Code or any previous
+    Modifications.  When Covered Code is released as a series of files, a
+    Modification is: 
+
+	</p><ul>
+
+	<p><b>A.</b> Any addition to or deletion from the contents of a file
+	containing Original Code or previous Modifications.
+
+	</p><p><b>B.</b> Any new file that contains any part of the Original
+	Code or previous Modifications.
+
+	</p></ul>
+
+    <p><b>1.10. ``Original Code''</b> means Source Code of computer software
+    code which is described in the Source Code notice required by <b>Exhibit
+    A</b> as Original Code, and which, at the time of its release under this
+    License is not already Covered Code governed by this License.
+
+    </p><p><b>1.11. ``Source Code''</b> means the preferred form of the Covered
+    Code for making modifications to it, including all modules it contains,
+    plus any associated interface definition files, scripts used to control
+    compilation and installation of an Executable, or a list of source code
+    differential comparisons against either the Original Code or another well
+    known, available Covered Code of the Contributor's choice. The Source
+    Code can be in a compressed or archival form, provided the appropriate
+    decompression or de-archiving software is widely available for no charge.
+
+    </p><p><b>1.12. ``You''</b> means an individual or a legal entity exercising
+    rights under, and complying with all of the terms of, this License or a
+    future version of this License issued under Section 6.1. For legal
+    entities, ``You'' includes any entity which controls, is controlled by,
+    or is under common control with You. For purposes of this definition,
+    ``control'' means (a) the power, direct or indirect, to cause the
+    direction or management of such entity, whether by contract or otherwise,
+    or (b) ownership of fifty percent (50%) or more of the outstanding shares
+    or beneficial ownership of such entity.
+
+</p></ul>
+<b>2. Source Code License.</b>
+<ul>
+
+    <b>2.1. The Initial Developer Grant.</b>
+
+    <br>The Initial Developer hereby grants You a world-wide, royalty-free,
+    non-exclusive license, subject to third party intellectual property
+    claims: 
+
+	<ul>
+
+	<p><b>(a)</b> to use, reproduce, modify, display, perform, sublicense
+	and distribute the Original Code (or portions thereof) with or
+	without Modifications, or as part of a Larger Work; and
+
+        </p><p><b>(b)</b> under patents now or hereafter owned or controlled by
+        Initial Developer, to make, have made, use and sell (``Utilize'') the
+        Original Code (or portions thereof), but solely to the extent that
+        any such patent is reasonably necessary to enable You to Utilize the
+        Original Code (or portions thereof) and not to any greater extent
+        that may be necessary to Utilize further Modifications or
+        combinations.
+    </p></ul>
+
+    <p><b>2.2. Contributor Grant.</b>
+
+    <br>Each Contributor hereby grants You a world-wide, royalty-free,
+    non-exclusive license, subject to third party intellectual property
+    claims: 
+
+    </p><ul>
+
+    <p><b>(a)</b> to use, reproduce, modify, display, perform, sublicense and
+    distribute the Modifications created by such Contributor (or portions
+    thereof) either on an unmodified basis, with other Modifications, as
+    Covered Code or as part of a Larger Work; and
+
+    </p><p><b>(b)</b> under patents now or hereafter owned or controlled by
+    Contributor, to Utilize the Contributor Version (or portions thereof),
+    but solely to the extent that any such patent is reasonably necessary to
+    enable You to Utilize the Contributor Version (or portions thereof), and
+    not to any greater extent that may be necessary to Utilize further
+    Modifications or combinations.
+
+    </p></ul>
+
+</ul>
+<b>3. Distribution Obligations.</b>
+<ul>
+
+    <b>3.1. Application of License.</b>
+
+    <br>The Modifications which You create or to which You contribute are
+    governed by the terms of this License, including without limitation
+    Section <b>2.2</b>.  The Source Code version of Covered Code may be
+    distributed only under the terms of this License or a future version of
+    this License released under Section <b>6.1</b>, and You must include a
+    copy of this License with every copy of the Source Code You
+    distribute. You may not offer or impose any terms on any Source Code
+    version that alters or restricts the applicable version of this License
+    or the recipients' rights hereunder. However, You may include an
+    additional document offering the additional rights described in Section
+    <b>3.5</b>.
+
+    <p><b>3.2. Availability of Source Code.</b>
+
+    <br>Any Modification which You create or to which You contribute must be
+    made available in Source Code form under the terms of this License either
+    on the same media as an Executable version or via an accepted Electronic
+    Distribution Mechanism to anyone to whom you made an Executable version
+    available; and if made available via Electronic Distribution Mechanism,
+    must remain available for at least twelve (12) months after the date it
+    initially became available, or at least six (6) months after a subsequent
+    version of that particular Modification has been made available to such
+    recipients. You are responsible for ensuring that the Source Code version
+    remains available even if the Electronic Distribution Mechanism is
+    maintained by a third party.
+
+    </p><p><b>3.3. Description of Modifications.</b>
+
+    <br>You must cause all Covered Code to which you contribute to contain a
+    file documenting the changes You made to create that Covered Code and the
+    date of any change. You must include a prominent statement that the
+    Modification is derived, directly or indirectly, from Original Code
+    provided by the Initial Developer and including the name of the Initial
+    Developer in (a) the Source Code, and (b) in any notice in an Executable
+    version or related documentation in which You describe the origin or
+    ownership of the Covered Code.
+
+    </p><p><b>3.4. Intellectual Property Matters</b>
+    </p><ul>
+
+	<p><b>(a) Third Party Claims</b>. 
+
+	<br>If You have knowledge that a party claims an intellectual
+	property right in particular functionality or code (or its
+	utilization under this License), you must include a text file with
+	the source code distribution titled ``LEGAL'' which describes the
+	claim and the party making the claim in sufficient detail that a
+	recipient will know whom to contact. If you obtain such knowledge
+	after You make Your Modification available as described in Section
+	<b>3.2</b>, You shall promptly modify the LEGAL file in all copies
+	You make available thereafter and shall take other steps (such as
+	notifying appropriate mailing lists or newsgroups) reasonably
+	calculated to inform those who received the Covered Code that new
+	knowledge has been obtained.
+
+	</p><p><b>(b) Contributor APIs</b>. 
+
+	<br>If Your Modification is an application programming interface and
+	You own or control patents which are reasonably necessary to
+	implement that API, you must also include this information in the
+	LEGAL file.
+
+    </p></ul>
+
+    <p><b>3.5. Required Notices.</b>
+
+    <br>You must duplicate the notice in <b>Exhibit A</b> in each file of the
+    Source Code, and this License in any documentation for the Source Code,
+    where You describe recipients' rights relating to Covered Code. If You
+    created one or more Modification(s), You may add your name as a
+    Contributor to the notice described in <b>Exhibit A</b>. If it is not
+    possible to put such notice in a particular Source Code file due to its
+    structure, then you must include such notice in a location (such as a
+    relevant directory file) where a user would be likely to look for such a
+    notice.  You may choose to offer, and to charge a fee for, warranty,
+    support, indemnity or liability obligations to one or more recipients of
+    Covered Code. However, You may do so only on Your own behalf, and not on
+    behalf of the Initial Developer or any Contributor.  You must make it
+    absolutely clear than any such warranty, support, indemnity or liability
+    obligation is offered by You alone, and You hereby agree to indemnify the
+    Initial Developer and every Contributor for any liability incurred by the
+    Initial Developer or such Contributor as a result of warranty, support,
+    indemnity or liability terms You offer.
+
+    </p><p><b>3.6. Distribution of Executable Versions.</b>
+
+    <br>You may distribute Covered Code in Executable form only if the
+    requirements of Section <b>3.1-3.5</b> have been met for that Covered
+    Code, and if You include a notice stating that the Source Code version of
+    the Covered Code is available under the terms of this License, including
+    a description of how and where You have fulfilled the obligations of
+    Section <b>3.2</b>.  The notice must be conspicuously included in any
+    notice in an Executable version, related documentation or collateral in
+    which You describe recipients' rights relating to the Covered Code. You
+    may distribute the Executable version of Covered Code under a license of
+    Your choice, which may contain terms different from this License,
+    provided that You are in compliance with the terms of this License and
+    that the license for the Executable version does not attempt to limit or
+    alter the recipient's rights in the Source Code version from the rights
+    set forth in this License. If You distribute the Executable version under
+    a different license You must make it absolutely clear that any terms
+    which differ from this License are offered by You alone, not by the
+    Initial Developer or any Contributor. You hereby agree to indemnify the
+    Initial Developer and every Contributor for any liability incurred by the
+    Initial Developer or such Contributor as a result of any such terms You
+    offer.
+
+    </p><p><b>3.7. Larger Works.</b>
+
+    <br>You may create a Larger Work by combining Covered Code with other
+    code not governed by the terms of this License and distribute the Larger
+    Work as a single product. In such a case, You must make sure the
+    requirements of this License are fulfilled for the Covered Code.
+
+</p></ul>
+<b>4. Inability to Comply Due to Statute or Regulation.</b>
+<ul>
+
+    <p>If it is impossible for You to comply with any of the terms of this
+    License with respect to some or all of the Covered Code due to statute or
+    regulation then You must: (a) comply with the terms of this License to
+    the maximum extent possible; and (b) describe the limitations and the
+    code they affect. Such description must be included in the LEGAL file
+    described in Section <b>3.4</b> and must be included with all
+    distributions of the Source Code. Except to the extent prohibited by
+    statute or regulation, such description must be sufficiently detailed for
+    a recipient of ordinary skill
+    to be able to understand it.
+
+</p></ul>
+<b>5. Application of this License.</b>
+<ul>
+
+    This License applies to code to which the Initial Developer has attached
+    the notice in <b>Exhibit A</b>, and to related Covered Code.
+
+</ul>
+<b>6. Versions of the License.</b>
+<ul>
+
+    <b>6.1. New Versions</b>. 
+
+    <br>Netscape Communications Corporation (``Netscape'') may publish
+    revised and/or new versions of the License from time to time.  Each
+    version will be given a distinguishing version number.
+
+    <p><b>6.2. Effect of New Versions</b>. 
+
+    <br>Once Covered Code has been published under a particular version of
+    the License, You may always continue to use it under the terms of that
+    version. You may also choose to use such Covered Code under the terms of
+    any subsequent version of the License published by Netscape. No one other
+    than Netscape has the right to modify the terms applicable to Covered
+    Code created under this License.
+
+    </p><p><b>6.3. Derivative Works</b>. 
+
+    <br>If you create or use a modified version of this License (which you
+    may only do in order to apply it to code which is not already Covered
+    Code governed by this License), you must (a) rename Your license so that
+    the phrases ``Mozilla'', ``MOZILLAPL'', ``MOZPL'', ``Netscape'', ``NPL''
+    or any confusingly similar phrase do not appear anywhere in your license
+    and (b) otherwise make it clear that your version of the license contains
+    terms which differ from the Mozilla Public License and Netscape Public
+    License. (Filling in the name of the Initial Developer, Original Code or
+    Contributor in the notice described in <b>Exhibit A</b> shall not of
+    themselves be deemed to be modifications of this License.)
+
+</p></ul>
+<b>7. DISCLAIMER OF WARRANTY.</b>
+<ul>
+
+    COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN ``AS IS'' BASIS,
+    WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
+    WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS,
+    MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
+    RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH
+    YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
+    INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
+    NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
+    CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE
+    IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+</ul>
+<b>8. TERMINATION.</b>
+<ul>
+
+    This License and the rights granted hereunder will terminate
+    automatically if You fail to comply with terms herein and fail to cure
+    such breach within 30 days of becoming aware of the breach. All
+    sublicenses to the Covered Code which are properly granted shall survive
+    any termination of this License.  Provisions which, by their nature, must
+    remain in effect beyond the termination of this License shall survive.
+
+</ul>
+<b>9. LIMITATION OF LIABILITY.</b>
+<ul>
+
+    UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING
+    NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL THE INITIAL DEVELOPER, ANY
+    OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED CODE, OR ANY SUPPLIER OF
+    ANY OF SUCH PARTIES, BE LIABLE TO YOU OR ANY OTHER PERSON FOR ANY
+    INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER
+    INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK
+    STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
+    COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED
+    OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL
+    NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH
+    PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH
+    LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION
+    OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THAT EXCLUSION AND LIMITATION
+    MAY NOT APPLY TO YOU.
+
+</ul>
+<b>10. U.S. GOVERNMENT END USERS.</b>
+<ul>
+
+    The Covered Code is a ``commercial item,'' as that term is defined in 48
+    C.F.R. 2.101 (Oct. 1995), consisting of ``commercial computer software''
+    and ``commercial computer software documentation,'' as such terms are
+    used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212
+    and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
+    U.S. Government End Users acquire Covered Code with only those rights set
+    forth herein.
+
+</ul>
+<b>11. MISCELLANEOUS.</b>
+<ul>
+
+    This License represents the complete agreement concerning subject matter
+    hereof. If any provision of this License is held to be unenforceable,
+    such provision shall be reformed only to the extent necessary to make it
+    enforceable. This License shall be governed by California law provisions
+    (except to the extent applicable law, if any, provides otherwise),
+    excluding its conflict-of-law provisions. With respect to disputes in
+    which at least one party is a citizen of, or an entity chartered or
+    registered to do business in, the United States of America: (a) unless
+    otherwise agreed in writing, all disputes relating to this License
+    (excepting any dispute relating to intellectual property rights) shall be
+    subject to final and binding arbitration, with the losing party paying
+    all costs of arbitration; (b) any arbitration relating to this Agreement
+    shall be held in Santa Clara County, California, under the auspices of
+    JAMS/EndDispute; and (c) any litigation relating to this Agreement shall
+    be subject to the jurisdiction of the Federal Courts of the Northern
+    District of California, with venue lying in Santa Clara County,
+    California, with the losing party responsible for costs, including
+    without limitation, court costs and reasonable attorneys fees and
+    expenses.  The application of the United Nations Convention on Contracts
+    for the International Sale of Goods is expressly excluded. Any law or
+    regulation which provides that the language of a contract shall be
+    construed against the drafter shall not apply to this License.
+
+</ul>
+<b>12. RESPONSIBILITY FOR CLAIMS.</b>
+<ul>
+
+    Except in cases where another Contributor has failed to comply with
+    Section <b>3.4</b>, You are responsible for damages arising, directly or
+    indirectly, out of Your utilization of rights under this License, based
+    on the number of copies of Covered Code you made available, the revenues
+    you received from utilizing such rights, and other relevant factors. You
+    agree to work with affected parties to distribute responsibility on an
+    equitable basis.
+
+</ul>
+<b>EXHIBIT A.</b>
+<ul>
+
+    ``The contents of this file are subject to the Mozilla Public License
+    Version 1.0 (the "License"); you may not use this file except in
+    compliance with the License. You may obtain a copy of the License at
+    http://www.mozilla.org/MPL/
+
+    <p>Software distributed under the License is distributed on an "AS IS"
+    basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+    License for the specific language governing rights and limitations under
+    the License.
+
+    </p><p>The Original Code is ______________________________________.
+
+    </p><p>The Initial Developer of the Original Code is
+    ________________________.  Portions created by ______________________ are
+    Copyright (C) ______ _______________________.  All Rights Reserved.
+
+    </p><p>Contributor(s): ______________________________________.''
+
+</p></ul>
+</body></html>
\ No newline at end of file

Modified: branches/as7/build/kits/jboss-container/teiid-examples/jca/file-ds.xml
===================================================================
--- branches/as7/build/kits/jboss-container/teiid-examples/jca/file-ds.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/kits/jboss-container/teiid-examples/jca/file-ds.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -13,6 +13,17 @@
 
        <!-- Directory where the data files are stored -->
       <config-property name="ParentDirectory" type="java.lang.String">directory</config-property>
+      
+      <!-- Optional properties -->
+      
+      <!-- Set FileMapping to redirect specific relative paths (case sensitive) to alternative locations.
+           The string value specifies a map in the format key=value(,key=value)*
+           -->
+      <!-- <config-property name="FileMapping" type="java.lang.String">file1.txt=fileX.txt,file2.txt=fileY.txt</config-property> -->
+      
+      <!-- Set AllowParentPaths to false to disallow .. in paths.
+           This prevent requesting files that are not contained in the parent directory -->
+      <config-property name="AllowParentPaths" type="java.lang.Boolean">true</config-property>
             
       <max-pool-size>20</max-pool-size>
 

Modified: branches/as7/build/kits/jboss-container/teiid-examples/jca/readme.txt
===================================================================
--- branches/as7/build/kits/jboss-container/teiid-examples/jca/readme.txt	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/kits/jboss-container/teiid-examples/jca/readme.txt	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,6 +3,28 @@
     LDAP
     SalesForce
     Web Services (for ws-security see Admin Guide)
+    ODBC
+    OLAP
+    Mondrian
+    Ingres
+    Intersystems Cache
+    Teiid JDBC template
 
-JDBC Users: Please see the examples in the "<jboss-as>/docs/examples/jca" directory for creating data source configuration 
-files for any type of relational database. These examples demonstrate creating both "local" and "xa" data sources.
+JDBC Users: Please see the examples in the "<jboss-as>/docs/examples/jca" directory for creating data source configuration files for any type of relational database. These examples demonstrate creating both "local" and "xa" data sources.
+
+
+---------
+
+When server applications wants to obtain their Teiid jdbc connection from the server connection pool, then Teiid needs to be deployed as a datasource.   
+
+We have provided a datasource -ds.xml template file to assist in the Teiid datasource deployment.   
+
+To deploy, using the template, do the following:
+
+1.	make a copy of the teiid-jdbc-template-ds.xml file
+2.	edit the file and replace "(vdb)" with the name of your vdb that you will be accessing, updating the user and password accordingly.
+3.	then copy the new -ds.xml file to the deploy directory of the profile you will be using.
+
+Your application should be able to obtain a jdbc connection from the connection pool using the JNDI name defined in the -ds.xml file.  
+By default, it called "TeiidDS".     If you have changed it, then your application will need to refer to it by the new name.
+

Modified: branches/as7/build/kits/jboss-container/teiid-examples/jca/teiid-jdbc-template-ds.xml
===================================================================
--- branches/as7/build/kits/jboss-container/teiid-examples/jca/teiid-jdbc-template-ds.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/kits/jboss-container/teiid-examples/jca/teiid-jdbc-template-ds.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,7 +21,7 @@
     <connection-url>jdbc:teiid:(vdb)@mm://localhost:31000</connection-url>
 
     <driver-class>org.teiid.jdbc.TeiidDriver</driver-class>
-    <user>user</user>
+    <user-name>user</user-name>
     <password>user</password>
 
       <metadata>

Modified: branches/as7/build/kits/jboss-container/teiid-releasenotes.html
===================================================================
--- branches/as7/build/kits/jboss-container/teiid-releasenotes.html	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/kits/jboss-container/teiid-releasenotes.html	2011-08-18 16:17:24 UTC (rev 3394)
@@ -10,7 +10,7 @@
 <P><A HREF="http://www.teiid.org/"><IMG SRC="https://www.jboss.org/dms/teiid/images/teiid-banner.png" NAME="graphics1" ALT="Teiid" ALIGN=BOTTOM WIDTH=800></A>
 
 <H1>Teiid ${project.version} Release Notes</H1>
-<P>Teiid ${project.version} adds performance, integration, and runtime metadata update features. 
+<P>Teiid ${project.version} adds performance and integration features. 
 
 <H2>Overview</H2>
 <UL>
@@ -25,13 +25,31 @@
 	<LI><A HREF="#About">About JBoss</A> 
 </UL>
 <H2><A NAME="Highlights"></A>Highlights</H2>
+<UL>
+  <LI><B>Procedure language features</B> - Added support for compound/block statements, BEGIN [[NOT] ATOMIC], loop/block labels, and the leave statement.  See the reference for more.
+  <LI><B>File Enhancements</B> - the file translator can now optionally (via the ExceptionIfFileNotFound property) throw an exception if the path refers to a file that doesn't exist.  The file resource adapter can be configured to map file names and can prevent parent path .. references.  See the Admin Guide or the file-ds.xml template for more.
+  <LI><B>TEXTTABLE Enhancements</B> - TEXTTABLE can now parse fixed width files that do not use a row delimiter and can optionally produce fixed values that haven't been trimmed.
+</UL>
 
 <h2><a name="Compatibility">Compatibility Issues</a></h2>
 <ul>
   <li>TRANSLATE/HAS CRITERIA has been deprecated.  An alternative approach to update procedures will be introduced in a subsequent version.
   <li>Support for named parameter syntax using param=value has been deprecated, since it is ambiguous with a comparison predicate boolean value expression.  param<b>=></b>value should be used instead.  
+  <li>Support for using the FROM clause post item hints MAKEDEP/MAKENOTDEP has been deprecated.  Use the pre item comment hint syntax instead, e.g. /*+ MAKEDEP */ tbl
 </ul>
 
+<h4>from 7.4</h4>
+<ul>
+  <li>Leave was added as a reserved word. 
+</ul>
+
+<h4>from 7.4</h4>
+<ul>
+  <li>OFFSET and LIKE_REGEX were added as reserved words. 
+  <li>ColumnReference.getName will always return just the element name.  Previously it inconsistently returned the qualified and unqualified form depending upon where the ColumnReference appeared.
+  <li>As per JDBC4, ResultSetMetadata.getColumnName will return the unaliased column name if available rather than return the alias.  Set useJDBC4ColumnNameAndLabelSemantics to false to use the alias name as the column name.
+</ul>
+
 <h4>from 7.3</h4>
 <ul>
   <li>SYS.PROPERTIES has a new column, ClobValue, to get values exceeding the max string length
@@ -93,6 +111,12 @@
 
 See the <a href="teiid-docs/teiid_admin_guide.pdf">Admin Guide</a> for more on configuration and installation.
 
+<h4>from 7.4</h4>
+<ul>
+  <LI>The configuration for authorization has been moved off of the RuntimeEngineDeployer bean and onto separate AuthorizationValidator and PolicyDecider beans.
+  <LI>The configuration for the buffer manager has been simplified to refer to memory sizes in KB, rather than batch columns.
+</ul>
+
 <h4>from 7.3</h4>
 <ul>
   <LI>The default value for the JDBC dynamic vdb importer setting importer.useFullSchemaName is now true, which matches the expected behavior from the documentation.
@@ -147,7 +171,8 @@
     <li>TEIID-1008 - Most versions of Oracle and MySQL do not support deeply nested correlated references.  There is currently no workaround for this issue.
 	<li>For compatibility with the 7.0 release if a stored procedure parameter list begins with identifier=, then it will be parsed as a named parameter invocation even if the intent was to use a comparison predicate 
 	as the first parameter value.  The workaround is to use nesting parens, e.g. call proc((identifier=value), ...), which clarifies that this is positional value.  This workaround will not be needed in later releases.
-	<li><a url="https://issues.jboss.org/browse/TEIID-1511">TEIID-1511<a/> - When a VDB is deployed and undeployed a socket is left open, which may lead to "too manay open files". Check the defect comments for details.	  
+	<li><a url="https://issues.jboss.org/browse/TEIID-1511">TEIID-1511<a/> - When a VDB is deployed and undeployed a socket is left open, which may lead to "too manay open files". Check the defect comments for details.
+	<li>TEIID-1648 - Teradata lobs can only be consistently read from an embedded client (with the default option to use the calling thread) and in single threaded mode (transactional or userRequestSourceConcurrency=1). Usage of Teradata lobs under any other configuration is unlikely to work.	  
 </ul>
 <h4>from 7.0</h4>
 <ul>
@@ -163,6 +188,12 @@
 <h2><a name="LibraryUpdates">Thirdparty Library Updates</a></h2>
 
 The following components have been updated:
+
+<h4>From 7.4</h4>
+<ul>
+    <li>Saxon was upgraded to 9.2.1.5
+    <li>nux 1.6, and xom 1.2 were added.
+</ul>
 <h4>From 7.1</h4>
 <ul>
     <li>json-simple 1.1 was added.

Modified: branches/as7/build/pom.xml
===================================================================
--- branches/as7/build/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/build/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <artifactId>teiid-parent</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>teiid</artifactId>

Modified: branches/as7/cache-jbosscache/pom.xml
===================================================================
--- branches/as7/cache-jbosscache/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/cache-jbosscache/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>teiid-cache-jbosscache</artifactId>

Modified: branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java
===================================================================
--- branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/JBossCacheFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -59,6 +59,9 @@
 			
 			if (!this.cacheStore.getCacheStatus().allowInvocations()) {
 				this.cacheStore.start();
+				if (this.cacheStore.getRegion(this.cacheStore.getRoot().getFqn(), false) != null) {
+					this.cacheStore.getRegion(this.cacheStore.getRoot().getFqn(), true).activate();	
+				}
 			}
 			
 			Node cacheRoot = this.cacheStore.getRoot().addChild(Fqn.fromString("Teiid")); //$NON-NLS-1$
@@ -67,6 +70,7 @@
 			
 			Region cacheRegion = this.cacheStore.getRegion(node.getFqn(), true);
 			cacheRegion.setEvictionRegionConfig(buildEvictionConfig(node.getFqn(), config));
+			cacheRegion.activate();
 						
 			JBossCache jc = null;
 			if (config != null && config.getPolicy().equals(Policy.EXPIRATION)) {

Modified: branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/TupleBatchCacheLoader.java
===================================================================
--- branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/TupleBatchCacheLoader.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/cache-jbosscache/src/main/java/org/teiid/cache/jboss/TupleBatchCacheLoader.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -62,9 +62,8 @@
 				map.put(id, b);
 				return map;
 			}
-			return super.get(fqn);
 		}
-		return null;
+		return super.get(fqn);
 	}
 
 	@Override

Modified: branches/as7/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java
===================================================================
--- branches/as7/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -35,7 +35,7 @@
 import org.jboss.util.naming.Util;
 import org.jgroups.Address;
 import org.jgroups.Channel;
-import org.jgroups.JChannelFactory;
+import org.jgroups.ChannelFactory;
 import org.jgroups.ReceiverAdapter;
 import org.jgroups.View;
 import org.jgroups.blocks.GroupRequest;
@@ -45,9 +45,20 @@
 
 public class JGroupsEventDistributor extends ReceiverAdapter implements Serializable {
 	
+	private final class ProxyHandler implements InvocationHandler, Serializable {
+		private static final long serialVersionUID = 3879554695890338832L;
+
+		@Override
+		public Object invoke(Object proxy, Method method, Object[] args)
+				throws Throwable {
+			rpcDispatcher.callRemoteMethods(members, new MethodCall(method, args), GroupRequest.GET_NONE, 0);
+			return null;
+		}
+	}
+
 	private static final long serialVersionUID = -1140683411842561358L;
 	
-	private transient JChannelFactory channelFactory;
+	private transient ChannelFactory channelFactory;
 	private String multiplexerStack;
 	private String clusterName;
 	private String jndiName;
@@ -60,7 +71,7 @@
 	private transient RpcDispatcher rpcDispatcher;
 	private transient Vector<Address> members;
 	
-	public JChannelFactory getChannelFactory() {
+	public ChannelFactory getChannelFactory() {
 		return channelFactory;
 	}
 	
@@ -88,7 +99,7 @@
 		return clusterName;
 	}
 	
-	public void setChannelFactory(JChannelFactory channelFactory) {
+	public void setChannelFactory(ChannelFactory channelFactory) {
 		this.channelFactory = channelFactory;
 	}
 	
@@ -104,18 +115,12 @@
 		if (this.channelFactory == null) {
 			return; //no need to distribute events
 		}
-		channel = this.channelFactory.createMultiplexerChannel(this.multiplexerStack, null);
+		channel = this.channelFactory.createMultiplexerChannel(this.multiplexerStack, "teiid-events"); //$NON-NLS-1$
 		channel.connect(this.clusterName);
-		
-		proxyEventDistributor = (EventDistributor) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {EventDistributor.class}, new InvocationHandler() {
-			
-			@Override
-			public Object invoke(Object proxy, Method method, Object[] args)
-					throws Throwable {
-				rpcDispatcher.callRemoteMethods(members, new MethodCall(method, args), GroupRequest.GET_NONE, 0);
-				return null;
-			}
-		});
+		if (channel.getView() != null) {
+			viewAccepted(channel.getView());
+		}
+		proxyEventDistributor = (EventDistributor) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {EventDistributor.class}, new ProxyHandler());
 		//wrap the local in a proxy to prevent unintended methods from being called
 		rpcDispatcher = new RpcDispatcher(channel, this, this, Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {EventDistributor.class}, new InvocationHandler() {
 			


Property changes on: branches/as7/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java:3149-3217
/trunk/cache-jbosscache/src/main/java/org/teiid/events/jboss/JGroupsEventDistributor.java:3188-3382

Modified: branches/as7/client/pom.xml
===================================================================
--- branches/as7/client/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>teiid-client</artifactId>

Modified: branches/as7/client/src/main/java/org/teiid/adminapi/DataPolicy.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/adminapi/DataPolicy.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/adminapi/DataPolicy.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,8 +25,20 @@
 
 public interface DataPolicy {
 	
-	public enum PermissionType {CREATE, READ, UPDATE, DELETE, ALTER, EXECUTE};
+	public enum Context {
+		CREATE,
+		DROP,
+		QUERY,
+		INSERT,
+		UPDATE,
+		DELETE,
+		FUNCTION,
+		ALTER,
+		STORED_PROCEDURE;
+    }
 	
+	public enum PermissionType {CREATE, READ, UPDATE, DELETE, ALTER, EXECUTE, DROP};
+	
 	/**
 	 * Get the Name of the Data Policy
 	 * @return

Modified: branches/as7/client/src/main/java/org/teiid/adminapi/Session.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/adminapi/Session.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/adminapi/Session.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,12 +24,11 @@
 
 
 /**
- * A Session is a lasting connection between a client and a Teiid System.
+ * A Session represents a single connection between a client and the server.
  * 
- * A user may be allowed to have multiple sessions active simultaneously.
- * 
+ * A user is allowed to have multiple sessions active simultaneously.
  */
-public interface Session extends  AdminObject {
+public interface Session extends AdminObject {
     
     /**
      * Get the Last time Client has check to see if the server is still available
@@ -90,6 +89,12 @@
     public String getClientHostName();
     
     /**
+     * Get the client hardware (typically MAC) address. Note this value is reported from the client.
+     * @return the hardware address as a hex string or null if not available.
+     */
+    public String getClientHardwareAddress();
+    
+    /**
      * Get the time the {@link Session} was created.
      * @return
      */

Modified: branches/as7/client/src/main/java/org/teiid/adminapi/impl/MetadataMapper.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/adminapi/impl/MetadataMapper.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/adminapi/impl/MetadataMapper.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -884,6 +884,7 @@
 		private static final String CLIENT_HOST_NAME = "client-host-address"; //$NON-NLS-1$
 		private static final String CREATED_TIME = "created-time"; //$NON-NLS-1$
 		private static final String APPLICATION_NAME = "application-name"; //$NON-NLS-1$
+		private static final String CLIENT_HARDWARE_ADRESS = "client-hardware-address"; //$NON-NLS-1$
 		
 		
 		public static ModelNode wrap(SessionMetadata session, ModelNode node) {
@@ -906,6 +907,9 @@
 			if (session.getSecurityDomain() != null){
 				node.get(SECURITY_DOMAIN).set(session.getSecurityDomain());
 			}
+			if (session.getClientHardwareAddress() != null) {
+				node.get(CLIENT_HARDWARE_ADRESS).set(session.getClientHardwareAddress());
+			}
 			return node;
 		}
 
@@ -928,6 +932,9 @@
 			if (node.has(SECURITY_DOMAIN)) {
 				session.setSecurityDomain(node.get(SECURITY_DOMAIN).asString());
 			}
+			if (node.has(CLIENT_HARDWARE_ADRESS)) {
+				session.setClientHardwareAddress(node.get(CLIENT_HARDWARE_ADRESS).asString());
+			}
 			return session;
 		}
 		

Modified: branches/as7/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/adminapi/impl/SessionMetadata.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,7 +32,10 @@
 
 /**
  * Add and delete properties also in the Mapper class for correct wrapping for profile service.
+ * 
  */
+/* TODO: it would probably be good to let ipAddress denote the connecting address 
+ and add clientIpAdress as the client reported value */
 public class SessionMetadata extends AdminObjectImpl implements Session {
 
 	private static final long serialVersionUID = 918638989081830034L;
@@ -41,6 +44,7 @@
     private long createdTime;
     private String ipAddress;
     private String clientHostName;    
+    private String clientHardwareAddress;
     private String userName;
     private String vdbName;
     private int vdbVersion;
@@ -154,6 +158,7 @@
     	str.append("; createdTime=").append(new Date(createdTime));
     	str.append("; applicationName=").append(applicationName);
     	str.append("; clientHostName=").append(clientHostName);
+    	str.append("; clientHardwareAddress=").append(clientHardwareAddress);
     	str.append("; IPAddress=").append(ipAddress);
     	str.append("; securityDomain=").append(securityDomain); 
     	str.append("; lastPingTime=").append(new Date(lastPingTime));
@@ -200,4 +205,13 @@
 		return embedded;
 	}
 	
+	@Override
+	public String getClientHardwareAddress() {
+		return this.clientHardwareAddress;
+	}
+	
+	public void setClientHardwareAddress(String clientHardwareAddress) {
+		this.clientHardwareAddress = clientHardwareAddress;
+	}
+	
 }


Property changes on: branches/as7/client/src/main/java/org/teiid/client/SourceWarning.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/client/src/main/java/org/teiid/client/security/ILogon.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/client/security/ILogon.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/client/security/ILogon.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,9 +34,14 @@
  * Generic logon interface.
  */
 public interface ILogon {
+	static final String KRB5TOKEN = "KRB5TOKEN"; //$NON-NLS-1$
+	static final String KRB5_ESTABLISHED = "KRB5_CONTEXT_ESTABLISHED"; //$NON-NLS-1$
+	
     LogonResult logon(Properties connectionProperties)
     throws LogonException, TeiidComponentException, CommunicationException;
-   
+
+    LogonResult neogitiateGssLogin(Properties connectionProperties, byte[] serviceToken, boolean createSession) throws LogonException;
+    
    /**
     * Ping the server to see if the client-server connection is alive.
     * @throws InvalidSessionException if the sessionID is invalid

Modified: branches/as7/client/src/main/java/org/teiid/client/security/LogonResult.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/client/security/LogonResult.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/client/security/LogonResult.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,10 +26,14 @@
 import java.io.IOException;
 import java.io.ObjectInput;
 import java.io.ObjectOutput;
+import java.util.HashMap;
+import java.util.Map;
 import java.util.TimeZone;
 
+import org.teiid.core.util.ExternalizeUtil;
 
 
+
 /**
  * Dataholder for the result of <code>ILogon.logon()</code>.
  * Contains a sessionID
@@ -44,8 +48,9 @@
     private SessionToken sessionToken;
     private String vdbName;
     private int vdbVersion;
+    private Map<Object, Object> addtionalProperties;
 
-    public LogonResult() {
+	public LogonResult() {
 	}
     
     public LogonResult(SessionToken token, String vdbName, int vdbVersion, String clusterName) {
@@ -89,6 +94,20 @@
 		return vdbVersion;
 	}
 	
+    public Object getProperty(String key) {
+		if (this.addtionalProperties == null) {
+			return null;
+		}
+		return addtionalProperties.get(key);
+    }
+
+	public void addProperty(String key, Object value) {
+		if (this.addtionalProperties == null) {
+			this.addtionalProperties = new HashMap<Object, Object>();
+		}
+		this.addtionalProperties.put(key, value);
+	}	
+	
 	@Override
 	public void readExternal(ObjectInput in) throws IOException,
 			ClassNotFoundException {
@@ -97,6 +116,7 @@
 		timeZone = (TimeZone)in.readObject();
 		clusterName = (String)in.readObject();
 		vdbVersion = in.readInt();
+		addtionalProperties = ExternalizeUtil.readMap(in);
 	}
 	
 	@Override
@@ -106,6 +126,7 @@
 		out.writeObject(timeZone);
 		out.writeObject(clusterName);
 		out.writeInt(vdbVersion);
+		ExternalizeUtil.writeMap(out, addtionalProperties);
 	}
     
 }

Deleted: branches/as7/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java
===================================================================
--- trunk/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,85 +0,0 @@
-/*-------------------------------------------------------------------------
-*
-* Copyright (c) 2008, PostgreSQL Global Development Group
-*
-* IDENTIFICATION
-*   $PostgreSQL: pgjdbc/org/postgresql/gss/GSSCallbackHandler.java,v 1.2 2008/11/29 07:43:47 jurka Exp $
-*
-*-------------------------------------------------------------------------
-*/
-
-/*
- * 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 org.teiid.gss;
-
-import java.io.IOException;
-import javax.security.auth.callback.*;
-
-import org.teiid.jdbc.JDBCPlugin;
-
-public class GSSCallbackHandler implements CallbackHandler {
-
-    private final String user;
-    private final String password;
-
-    public GSSCallbackHandler(String user, String password)
-    {
-        this.user = user;
-        this.password = password;
-    }
-
-    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
-    {
-        for (int i=0; i<callbacks.length; i++) {
-            if (callbacks[i] instanceof TextOutputCallback) {
-                TextOutputCallback toc = (TextOutputCallback)callbacks[i];
-                switch (toc.getMessageType()) {
-                    case TextOutputCallback.INFORMATION:
-                        System.out.println("INFO: " + toc.getMessage());//$NON-NLS-1$
-                        break;
-                    case TextOutputCallback.ERROR:
-                        System.out.println("ERROR: " + toc.getMessage()); //$NON-NLS-1$
-                        break;
-                    case TextOutputCallback.WARNING:
-                        System.out.println("WARNING: " + toc.getMessage());//$NON-NLS-1$
-                        break;
-                    default:
-                        throw new IOException("Unsupported message type: " + toc.getMessageType()); //$NON-NLS-1$
-                }
-            } else if (callbacks[i] instanceof NameCallback) {
-                NameCallback nc = (NameCallback)callbacks[i];
-                nc.setName(user);
-            } else if (callbacks[i] instanceof PasswordCallback) {
-                PasswordCallback pc = (PasswordCallback)callbacks[i];
-                if (password == null) {
-                    throw new IOException(JDBCPlugin.Util.getString("no_krb_ticket")); //$NON-NLS-1$
-                }
-                pc.setPassword(password.toCharArray());
-            } else {
-                throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); //$NON-NLS-1$
-            }
-        }
-    }
-
-}
-
-

Copied: branches/as7/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java (from rev 3382, trunk/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java)
===================================================================
--- branches/as7/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java	                        (rev 0)
+++ branches/as7/client/src/main/java/org/teiid/gss/GSSCallbackHandler.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,85 @@
+/*-------------------------------------------------------------------------
+*
+* Copyright (c) 2008, PostgreSQL Global Development Group
+*
+* IDENTIFICATION
+*   $PostgreSQL: pgjdbc/org/postgresql/gss/GSSCallbackHandler.java,v 1.2 2008/11/29 07:43:47 jurka Exp $
+*
+*-------------------------------------------------------------------------
+*/
+
+/*
+ * 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 org.teiid.gss;
+
+import java.io.IOException;
+import javax.security.auth.callback.*;
+
+import org.teiid.jdbc.JDBCPlugin;
+
+public class GSSCallbackHandler implements CallbackHandler {
+
+    private final String user;
+    private final String password;
+
+    public GSSCallbackHandler(String user, String password)
+    {
+        this.user = user;
+        this.password = password;
+    }
+
+    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
+    {
+        for (int i=0; i<callbacks.length; i++) {
+            if (callbacks[i] instanceof TextOutputCallback) {
+                TextOutputCallback toc = (TextOutputCallback)callbacks[i];
+                switch (toc.getMessageType()) {
+                    case TextOutputCallback.INFORMATION:
+                        System.out.println("INFO: " + toc.getMessage());//$NON-NLS-1$
+                        break;
+                    case TextOutputCallback.ERROR:
+                        System.out.println("ERROR: " + toc.getMessage()); //$NON-NLS-1$
+                        break;
+                    case TextOutputCallback.WARNING:
+                        System.out.println("WARNING: " + toc.getMessage());//$NON-NLS-1$
+                        break;
+                    default:
+                        throw new IOException("Unsupported message type: " + toc.getMessageType()); //$NON-NLS-1$
+                }
+            } else if (callbacks[i] instanceof NameCallback) {
+                NameCallback nc = (NameCallback)callbacks[i];
+                nc.setName(user);
+            } else if (callbacks[i] instanceof PasswordCallback) {
+                PasswordCallback pc = (PasswordCallback)callbacks[i];
+                if (password == null) {
+                    throw new IOException(JDBCPlugin.Util.getString("no_krb_ticket")); //$NON-NLS-1$
+                }
+                pc.setPassword(password.toCharArray());
+            } else {
+                throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); //$NON-NLS-1$
+            }
+        }
+    }
+
+}
+
+

Deleted: branches/as7/client/src/main/java/org/teiid/gss/MakeGSS.java
===================================================================
--- trunk/client/src/main/java/org/teiid/gss/MakeGSS.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/client/src/main/java/org/teiid/gss/MakeGSS.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,163 +0,0 @@
-/*-------------------------------------------------------------------------
-*
-* Copyright (c) 2008, PostgreSQL Global Development Group
-*
-* IDENTIFICATION
-*   $PostgreSQL: pgjdbc/org/postgresql/gss/MakeGSS.java,v 1.2.2.1 2009/08/18 03:37:08 jurka Exp $
-*
-*-------------------------------------------------------------------------
-*/
-
-/*
- * 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 org.teiid.gss;
-
-import java.security.PrivilegedAction;
-import java.util.Properties;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.security.auth.Subject;
-import javax.security.auth.login.LoginContext;
-
-import org.ietf.jgss.GSSContext;
-import org.ietf.jgss.GSSException;
-import org.ietf.jgss.GSSManager;
-import org.ietf.jgss.GSSName;
-import org.teiid.client.security.ILogon;
-import org.teiid.client.security.LogonException;
-import org.teiid.client.security.LogonResult;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.jdbc.JDBCPlugin;
-import org.teiid.jdbc.TeiidSQLException;
-import org.teiid.net.CommunicationException;
-import org.teiid.net.TeiidURL;
-
-
-
-public class MakeGSS {
-
-	private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
-
-	public static LogonResult authenticate(ILogon logon, Properties props) 
-			throws LogonException, TeiidComponentException, CommunicationException   {
-        if (logger.isLoggable(Level.FINE)) {
-            logger.fine("GSS Authentication Request"); //$NON-NLS-1$
-        }
-
-        Object result = null;
-
-        String jaasApplicationName = props.getProperty(TeiidURL.CONNECTION.JAAS_NAME, "teiid"); //$NON-NLS-1$
-        String kerberosPrincipalName =  props.getProperty(TeiidURL.CONNECTION.KERBEROS_SERVICE_PRINCIPLE_NAME, "teiid"); //$NON-NLS-1$
-        String user = props.getProperty(TeiidURL.CONNECTION.USER_NAME);
-        String password = props.getProperty(TeiidURL.CONNECTION.PASSWORD);
-        
-        try {
-            LoginContext lc = new LoginContext(jaasApplicationName, new GSSCallbackHandler(user, password));
-            lc.login();
-
-            Subject sub = lc.getSubject();
-            PrivilegedAction action = new GssAction(logon, kerberosPrincipalName, props);
-            result = Subject.doAs(sub, action);
-        } catch (Exception e) {
-            throw new LogonException(e, JDBCPlugin.Util.getString("gss_auth_failed")); //$NON-NLS-1$
-        }
-
-        if (result instanceof LogonException)
-        	throw (LogonException)result;
-        else if (result instanceof TeiidComponentException)
-        	throw (TeiidComponentException)result;
-        else if (result instanceof CommunicationException)
-        	throw (CommunicationException)result;
-        else if (result instanceof Exception)
-        	throw new LogonException((Exception)result, JDBCPlugin.Util.getString("gss_auth_failed")); //$NON-NLS-1$
-
-        return (LogonResult)result;
-    }
-
-}
-
-class GssAction implements PrivilegedAction {
-	
-	private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
-    private final ILogon logon;
-    private final String kerberosPrincipalName;
-    private Properties props;
-
-    public GssAction(ILogon pgStream, String kerberosPrincipalName, Properties props) {
-        this.logon = pgStream;
-        this.kerberosPrincipalName = kerberosPrincipalName;
-        this.props = props;
-    }
-
-    public Object run() {
-    	byte outToken[] = null;
-        
-    	try {
-            org.ietf.jgss.Oid desiredMechs[] = new org.ietf.jgss.Oid[1];
-            desiredMechs[0] = new org.ietf.jgss.Oid("1.2.840.113554.1.2.2"); //$NON-NLS-1$
-
-            GSSManager manager = GSSManager.getInstance();
-
-            // null on second param means the serverName is already in the native format. 
-            GSSName serverName = manager.createName(this.kerberosPrincipalName, null); 
-
-            GSSContext secContext = manager.createContext(serverName, desiredMechs[0], null, GSSContext.DEFAULT_LIFETIME);
-            secContext.requestMutualAuth(true);
-            secContext.requestConf(true);  // Will use confidentiality later
-            secContext.requestInteg(true); // Will use integrity later            
-
-            byte inToken[] = new byte[0];
-
-            boolean established = false;
-            LogonResult result = null;
-            while (!established) {
-            	outToken = secContext.initSecContext(inToken, 0, inToken.length);
-                if (outToken != null) {
-                	if (logger.isLoggable(Level.FINE)) {
-                        logger.fine("Sending Service Token to Server (GSS Authentication Token)"); //$NON-NLS-1$
-                	}
-                	result = logon.neogitiateGssLogin(this.props, outToken, true);
-                	inToken = (byte[])result.getProperty(ILogon.KRB5TOKEN);
-                }
-
-                if (!secContext.isEstablished()) {
-                	if (logger.isLoggable(Level.FINE)) {
-                        logger.fine("Authentication GSS Continue"); //$NON-NLS-1$    
-                	}
-                } else {
-                    established = true;
-                	if (logger.isLoggable(Level.FINE)) {
-                        logger.fine("Authentication GSS Established"); //$NON-NLS-1$    
-                	}                    
-                }
-            }  
-            return result;
-        }  catch (GSSException gsse) {
-        	return TeiidSQLException.create(gsse, JDBCPlugin.Util.getString("gss_auth_failed")); //$NON-NLS-1$
-        } catch(Exception e) {
-        	return e;
-        }
-    }
-}
-

Copied: branches/as7/client/src/main/java/org/teiid/gss/MakeGSS.java (from rev 3382, trunk/client/src/main/java/org/teiid/gss/MakeGSS.java)
===================================================================
--- branches/as7/client/src/main/java/org/teiid/gss/MakeGSS.java	                        (rev 0)
+++ branches/as7/client/src/main/java/org/teiid/gss/MakeGSS.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,163 @@
+/*-------------------------------------------------------------------------
+*
+* Copyright (c) 2008, PostgreSQL Global Development Group
+*
+* IDENTIFICATION
+*   $PostgreSQL: pgjdbc/org/postgresql/gss/MakeGSS.java,v 1.2.2.1 2009/08/18 03:37:08 jurka Exp $
+*
+*-------------------------------------------------------------------------
+*/
+
+/*
+ * 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 org.teiid.gss;
+
+import java.security.PrivilegedAction;
+import java.util.Properties;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
+
+import org.ietf.jgss.GSSContext;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.GSSManager;
+import org.ietf.jgss.GSSName;
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.LogonException;
+import org.teiid.client.security.LogonResult;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.jdbc.JDBCPlugin;
+import org.teiid.jdbc.TeiidSQLException;
+import org.teiid.net.CommunicationException;
+import org.teiid.net.TeiidURL;
+
+
+
+public class MakeGSS {
+
+	private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
+
+	public static LogonResult authenticate(ILogon logon, Properties props) 
+			throws LogonException, TeiidComponentException, CommunicationException   {
+        if (logger.isLoggable(Level.FINE)) {
+            logger.fine("GSS Authentication Request"); //$NON-NLS-1$
+        }
+
+        Object result = null;
+
+        String jaasApplicationName = props.getProperty(TeiidURL.CONNECTION.JAAS_NAME, "teiid"); //$NON-NLS-1$
+        String kerberosPrincipalName =  props.getProperty(TeiidURL.CONNECTION.KERBEROS_SERVICE_PRINCIPLE_NAME, "teiid"); //$NON-NLS-1$
+        String user = props.getProperty(TeiidURL.CONNECTION.USER_NAME);
+        String password = props.getProperty(TeiidURL.CONNECTION.PASSWORD);
+        
+        try {
+            LoginContext lc = new LoginContext(jaasApplicationName, new GSSCallbackHandler(user, password));
+            lc.login();
+
+            Subject sub = lc.getSubject();
+            PrivilegedAction action = new GssAction(logon, kerberosPrincipalName, props);
+            result = Subject.doAs(sub, action);
+        } catch (Exception e) {
+            throw new LogonException(e, JDBCPlugin.Util.getString("gss_auth_failed")); //$NON-NLS-1$
+        }
+
+        if (result instanceof LogonException)
+        	throw (LogonException)result;
+        else if (result instanceof TeiidComponentException)
+        	throw (TeiidComponentException)result;
+        else if (result instanceof CommunicationException)
+        	throw (CommunicationException)result;
+        else if (result instanceof Exception)
+        	throw new LogonException((Exception)result, JDBCPlugin.Util.getString("gss_auth_failed")); //$NON-NLS-1$
+
+        return (LogonResult)result;
+    }
+
+}
+
+class GssAction implements PrivilegedAction {
+	
+	private static Logger logger = Logger.getLogger("org.teiid.jdbc"); //$NON-NLS-1$
+    private final ILogon logon;
+    private final String kerberosPrincipalName;
+    private Properties props;
+
+    public GssAction(ILogon pgStream, String kerberosPrincipalName, Properties props) {
+        this.logon = pgStream;
+        this.kerberosPrincipalName = kerberosPrincipalName;
+        this.props = props;
+    }
+
+    public Object run() {
+    	byte outToken[] = null;
+        
+    	try {
+            org.ietf.jgss.Oid desiredMechs[] = new org.ietf.jgss.Oid[1];
+            desiredMechs[0] = new org.ietf.jgss.Oid("1.2.840.113554.1.2.2"); //$NON-NLS-1$
+
+            GSSManager manager = GSSManager.getInstance();
+
+            // null on second param means the serverName is already in the native format. 
+            GSSName serverName = manager.createName(this.kerberosPrincipalName, null); 
+
+            GSSContext secContext = manager.createContext(serverName, desiredMechs[0], null, GSSContext.DEFAULT_LIFETIME);
+            secContext.requestMutualAuth(true);
+            secContext.requestConf(true);  // Will use confidentiality later
+            secContext.requestInteg(true); // Will use integrity later            
+
+            byte inToken[] = new byte[0];
+
+            boolean established = false;
+            LogonResult result = null;
+            while (!established) {
+            	outToken = secContext.initSecContext(inToken, 0, inToken.length);
+                if (outToken != null) {
+                	if (logger.isLoggable(Level.FINE)) {
+                        logger.fine("Sending Service Token to Server (GSS Authentication Token)"); //$NON-NLS-1$
+                	}
+                	result = logon.neogitiateGssLogin(this.props, outToken, true);
+                	inToken = (byte[])result.getProperty(ILogon.KRB5TOKEN);
+                }
+
+                if (!secContext.isEstablished()) {
+                	if (logger.isLoggable(Level.FINE)) {
+                        logger.fine("Authentication GSS Continue"); //$NON-NLS-1$    
+                	}
+                } else {
+                    established = true;
+                	if (logger.isLoggable(Level.FINE)) {
+                        logger.fine("Authentication GSS Established"); //$NON-NLS-1$    
+                	}                    
+                }
+            }  
+            return result;
+        }  catch (GSSException gsse) {
+        	return TeiidSQLException.create(gsse, JDBCPlugin.Util.getString("gss_auth_failed")); //$NON-NLS-1$
+        } catch(Exception e) {
+        	return e;
+        }
+    }
+}
+

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/BaseDataSource.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/BaseDataSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/BaseDataSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -147,6 +147,8 @@
     
     private int queryTimeout;
     
+    private boolean useJDBC4ColumnNameAndLabelSemantics = true; 
+    
     /**
      * Reference to the logWriter, which is transient and is therefore not serialized with the DataSource.
      */
@@ -247,6 +249,10 @@
             props.setProperty(ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS, this.getDisableLocalTxn());
         }
         
+        if (!this.getUseJDBC4ColumnNameAndLabelSemantics()) {
+        	props.setProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS, "false");
+        }
+        
         if (this.additionalProperties != null) {
         	JDBCURL.parseConnectionProperties(this.additionalProperties, props);
         }
@@ -652,7 +658,16 @@
     public void setAutoCommitTxn(String transactionAutoWrap) {
     	this.transactionAutoWrap = transactionAutoWrap;
     }
+    
+    
+	public boolean getUseJDBC4ColumnNameAndLabelSemantics() {
+		return useJDBC4ColumnNameAndLabelSemantics;
+	}
 
+	public void setUseJDBC4ColumnNameAndLabelSemantics(boolean useJDBC4ColumnNameAndLabelSemantics) {
+		this.useJDBC4ColumnNameAndLabelSemantics = useJDBC4ColumnNameAndLabelSemantics;
+	}
+
     // --------------------------------------------------------------------------------------------
     //                  V A L I D A T I O N   M E T H O D S
     // --------------------------------------------------------------------------------------------

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -972,6 +972,21 @@
 		throw SqlUtil.createFeatureNotSupportedException();
 	}
 	
+	Object setPassword(Object newPassword) {
+		if (newPassword != null) {
+			return this.connectionProps.put(TeiidURL.CONNECTION.PASSWORD, newPassword);
+		} 
+		return this.connectionProps.remove(TeiidURL.CONNECTION.PASSWORD);
+	}
+	
+	String getPassword() {
+		Object result = this.connectionProps.get(TeiidURL.CONNECTION.PASSWORD);
+		if (result == null) {
+			return null;
+		}
+		return result.toString();
+	}
+	
 	@Override
 	public void changeUser(String userName, String newPassword)
 			throws SQLException {
@@ -983,11 +998,7 @@
 		} else {
 			oldName = this.connectionProps.remove(TeiidURL.CONNECTION.USER_NAME);
 		}
-		if (newPassword != null) {
-			oldPassword = this.connectionProps.put(TeiidURL.CONNECTION.PASSWORD, newPassword);
-		} else {
-			oldPassword = this.connectionProps.remove(TeiidURL.CONNECTION.PASSWORD);
-		}
+		oldPassword = setPassword(newPassword);
 		boolean success = false;
 		try {
 			this.serverConn.authenticate();
@@ -1003,11 +1014,7 @@
 				} else {
 					this.connectionProps.remove(TeiidURL.CONNECTION.USER_NAME);
 				}
-				if (oldPassword != null) {
-					this.connectionProps.put(TeiidURL.CONNECTION.PASSWORD, oldPassword);
-				} else {
-					this.connectionProps.remove(TeiidURL.CONNECTION.PASSWORD);
-				}
+				setPassword(oldPassword);
 			}
 		}
 	}


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java:3149-3217
/trunk/client/src/main/java/org/teiid/jdbc/ConnectionImpl.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/DatabaseMetaDataImpl.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/DatabaseMetaDataImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/DatabaseMetaDataImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1433,18 +1433,21 @@
         // query string to be submitted to get table metadata info
         StringBuffer sqlQuery = new StringBuffer(QUERY_TABLES);
 
-        StringBuffer typesString = new StringBuffer("("); // criteria string for different table types //$NON-NLS-1$
-        
         if (types != null) {
-            // construct the criteria string
-            for(int i=0; i < types.length; i++) {
-                if (types[i] != null && types[i].length() > 0) {
-                    if (i > 0) {
-                        typesString.append(" OR "); //$NON-NLS-1$
-                    } 
-                    typesString.append(TABLE_TYPE).append(LIKE_ESCAPE);
-                }
-            }
+        	StringBuffer typesString = new StringBuffer("("); // criteria string for different table types //$NON-NLS-1$
+        	if (types.length == 0) {
+        		typesString.append("1 = 0"); //$NON-NLS-1$
+        	} else {
+	            // construct the criteria string
+	            for(int i=0; i < types.length; i++) {
+	                if (types[i] != null && types[i].length() > 0) {
+	                    if (i > 0) {
+	                        typesString.append(" OR "); //$NON-NLS-1$
+	                    } 
+	                    typesString.append(TABLE_TYPE).append(LIKE_ESCAPE);
+	                }
+	            }
+        	}
             typesString.append(")"); //$NON-NLS-1$
             sqlQuery.append(" AND ").append(typesString.toString()); //$NON-NLS-1$
         }
@@ -1583,7 +1586,7 @@
         metadataList[16] = StatementImpl.getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.SQL_DATETIME_SUB, JDBCSQLTypeInfo.INTEGER,  ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, driverConnection);//$NON-NLS-1$ 
         metadataList[17] = StatementImpl.getColumnMetadata(CoreConstants.SYSTEM_MODEL + "." + DATA_TYPES, JDBCColumnNames.TYPE_INFO.NUM_PREC_RADIX, JDBCSQLTypeInfo.INTEGER,  ResultsMetadataConstants.NULL_TYPES.NULLABLE, ResultsMetadataConstants.SEARCH_TYPES.SEARCHABLE, Boolean.FALSE, Boolean.FALSE, Boolean.FALSE, driverConnection);//$NON-NLS-1$ 
 
-        ResultSetMetaData rmetadata = new ResultSetMetaDataImpl(new MetadataProvider(metadataList));
+        ResultSetMetaData rmetadata = new ResultSetMetaDataImpl(new MetadataProvider(metadataList), null);
 
         logger.fine(JDBCPlugin.Util.getString("MMDatabaseMetadata.getTypes_success")); //$NON-NLS-1$
 


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/DatabaseMetaDataImpl.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/DatabaseMetaDataImpl.java:3281-3325
/trunk/client/src/main/java/org/teiid/jdbc/DatabaseMetaDataImpl.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,6 +28,7 @@
 
 import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.util.PropertiesUtils;
 import org.teiid.core.util.ReflectionHelper;
 import org.teiid.net.CommunicationException;
 import org.teiid.net.ConnectionException;
@@ -36,7 +37,9 @@
 
 public class EmbeddedProfile implements ConnectionProfile {
 	
-    /**
+    public static final String USE_CALLING_THREAD = "useCallingThread"; //$NON-NLS-1$
+
+	/**
      * This method tries to make a connection to the given URL. This class
      * will return a null if this is not the right driver to connect to the given URL.
      * @param The URL used to establish a connection.
@@ -61,7 +64,7 @@
 
 	protected ServerConnection createServerConnection(Properties info)
 			throws TeiidException {
-		return (ServerConnection)ReflectionHelper.create("org.teiid.transport.LocalServerConnection", Arrays.asList(info, true), Thread.currentThread().getContextClassLoader()); //$NON-NLS-1$
+		return (ServerConnection)ReflectionHelper.create("org.teiid.transport.LocalServerConnection", Arrays.asList(info, PropertiesUtils.getBooleanProperty(info, USE_CALLING_THREAD, true)), Thread.currentThread().getContextClassLoader()); //$NON-NLS-1$
 	}
     
 }


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java:3149-3217
/trunk/client/src/main/java/org/teiid/jdbc/EmbeddedProfile.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/ExecutionProperties.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/ExecutionProperties.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/ExecutionProperties.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -104,5 +104,19 @@
     
     public static final String QUERYTIMEOUT = "QUERYTIMEOUT"; //$NON-NLS-1$
     
+	/**
+	 * TEIID-1651
+	 * A change was made in JDBC4 so that when an 'Alias' is used it will
+	 * now be returned as the label.   Prior to this, it was returned as
+	 * the name.   Setting this property to <code>false</code> will enable
+	 * backwards compatibility when JDBC3 and older support is still required.
+	 * 
+	 * Default is <code>true</code>
+	 * @since 7.4.1
+	 */
+    
+    public static final String JDBC4COLUMNNAMEANDLABELSEMANTICS = "useJDBC4ColumnNameAndLabelSemantics"; //$NON-NLS-1$
+    
+    
 }
     
\ No newline at end of file

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/JDBCURL.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/JDBCURL.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/JDBCURL.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -57,7 +57,9 @@
             ExecutionProperties.PROP_FETCH_SIZE,
             ExecutionProperties.PROP_XML_FORMAT,
             ExecutionProperties.PROP_XML_VALIDATION,
-            ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS)));
+            EmbeddedProfile.USE_CALLING_THREAD,
+            ExecutionProperties.DISABLE_LOCAL_TRANSACTIONS,
+            ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS)));
     
     public static final Set<String> KNOWN_PROPERTIES = getKnownProperties();
     
@@ -71,7 +73,10 @@
     	        BaseDataSource.PASSWORD,
     	        TeiidURL.CONNECTION.AUTO_FAILOVER,
     	        TeiidURL.CONNECTION.DISCOVERY_STRATEGY,
-    	        TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION));
+    	        TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION,
+    	        TeiidURL.CONNECTION.AUTHENTICATION_TYPE,
+    	        TeiidURL.CONNECTION.JAAS_NAME,
+    	        TeiidURL.CONNECTION.KERBEROS_SERVICE_PRINCIPLE_NAME));
     	props.addAll(EXECUTION_PROPERTIES);
     	return Collections.unmodifiableSet(props);
     }


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/JDBCURL.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/JDBCURL.java:3149-3217,3281-3325
/trunk/client/src/main/java/org/teiid/jdbc/JDBCURL.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/PreparedStatementImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -259,7 +259,7 @@
 					return null;
 				}
                 MetadataProvider provider = new MetadataProvider(getMetadataResults().getColumnMetadata());
-                metadata = new ResultSetMetaDataImpl(provider);
+                metadata = new ResultSetMetaDataImpl(provider, this.getExecutionProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
             }
         }
 
@@ -653,7 +653,7 @@
 	public ParameterMetaData getParameterMetaData() throws SQLException {
 		if (parameterMetaData == null) {
 			//TODO: some of the base implementation of ResultSetMetadata could be on the MetadataProvider
-			this.parameterMetaData = new ParameterMetaDataImpl(new ResultSetMetaDataImpl(new MetadataProvider(getMetadataResults().getParameterMetadata())));
+			this.parameterMetaData = new ParameterMetaDataImpl(new ResultSetMetaDataImpl(new MetadataProvider(getMetadataResults().getParameterMetadata()), this.getExecutionProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS)));
 		}
 		return parameterMetaData;
 	}

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetImpl.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -133,12 +133,11 @@
         this.batchResults = new BatchResults(this, getCurrentBatch(resultsMsg), this.cursorType == ResultSet.TYPE_FORWARD_ONLY ? 1 : BatchResults.DEFAULT_SAVED_BATCHES);
         accumulateWarnings(resultsMsg);
         this.serverTimeZone = statement.getServerTimeZone();
-
 		if (metadata == null) {
 			MetadataProvider provider = new DeferredMetadataProvider(resultsMsg.getColumnNames(),
 							resultsMsg.getDataTypes(), statement,
 							statement.getCurrentRequestID());
-			rmetadata = new ResultSetMetaDataImpl(provider);
+			rmetadata = new ResultSetMetaDataImpl(provider, this.statement.getExecutionProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
 		} else {
 			rmetadata = metadata;
 		}

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetMetaDataImpl.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetMetaDataImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetMetaDataImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,10 +34,15 @@
 public class ResultSetMetaDataImpl extends WrapperImpl implements ResultSetMetaData {
 
     private MetadataProvider provider;
+
+    private boolean useJDBC4ColumnNameAndLabelSemantics = true;
     
-    public ResultSetMetaDataImpl(MetadataProvider provider) {
+    public ResultSetMetaDataImpl(MetadataProvider provider, String supportBackwardsCompatibility) {
     	this.provider = provider;
-    }
+    	if (supportBackwardsCompatibility != null) {
+    		this.useJDBC4ColumnNameAndLabelSemantics = Boolean.parseBoolean(supportBackwardsCompatibility);
+    	}
+    }    
     
     /**
      * Adjust from 1-based to internal 0-based representation
@@ -105,6 +110,13 @@
     }
 
     public String getColumnName(int index) throws SQLException {
+
+    	if (!useJDBC4ColumnNameAndLabelSemantics) {
+            String result = provider.getStringValue(adjustColumn(index), ResultsMetadataConstants.ELEMENT_LABEL);
+            if (result != null) {
+            	return result;
+            }
+    	}
         return provider.getStringValue(adjustColumn(index), ResultsMetadataConstants.ELEMENT_NAME);
     }
 


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/ResultSetMetaDataImpl.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/ResultSetMetaDataImpl.java:3281-3325
/trunk/client/src/main/java/org/teiid/jdbc/ResultSetMetaDataImpl.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/SQLStates.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/SQLStates.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/SQLStates.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -82,6 +82,8 @@
 	 * conforms to the subclass DataDirect uses for SocketExceptions.
 	 */
 	public static final String CONNECTION_EXCEPTION_STALE_CONNECTION = "08S01"; //$NON-NLS-1$
+	
+	public static final String QUERY_CANCELED = "57014"; //$NON-NLS-1$
 
 	// Class 28 - invalid authorization specification
 


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/SQLStates.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/SQLStates.java:3220-3275
/trunk/client/src/main/java/org/teiid/jdbc/SQLStates.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/StatementImpl.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/StatementImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/StatementImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,8 +40,6 @@
 import java.util.Properties;
 import java.util.TimeZone;
 import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import java.util.regex.Matcher;
@@ -66,6 +64,7 @@
 import org.teiid.core.util.SqlUtil;
 import org.teiid.core.util.StringUtil;
 import org.teiid.jdbc.CancellationTimer.CancelTask;
+import org.teiid.net.TeiidURL;
 
 
 public class StatementImpl extends WrapperImpl implements TeiidStatement {
@@ -148,7 +147,7 @@
     private Serializable payload;
     
     /** List of INSERT, UPDATE, DELETE AND SELECT INTO commands */
-    private List batchedUpdates;
+    private List<String> batchedUpdates;
     
     /** Array of update counts as returned by executeBatch() */
     protected int[] updateCounts;
@@ -163,7 +162,7 @@
     protected Map outParamIndexMap = new HashMap();
     
     private static Pattern TRANSACTION_STATEMENT = Pattern.compile("\\s*(commit|rollback|(start\\s+transaction))\\s*;?", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
-    private static Pattern SET_STATEMENT = Pattern.compile("\\s*set\\s+(\\w+)\\s*([^;]*);?", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
+    private static Pattern SET_STATEMENT = Pattern.compile("\\s*set\\s+((?:session authorization)|(?:\\w+))\\s+(?:([a-zA-Z](?:\\w|_)*)|((?:'[^']*')+));?", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
     private static Pattern SHOW_STATEMENT = Pattern.compile("\\s*show\\s+(\\w*);?", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
     /**
      * Factory Constructor 
@@ -199,7 +198,7 @@
         String queryTimeoutStr = this.execProps.getProperty(ExecutionProperties.QUERYTIMEOUT);
         if(queryTimeoutStr != null) {
             try {
-                this.queryTimeoutMS = Integer.parseInt(fetchSizeStr)*1000;
+                this.queryTimeoutMS = Integer.parseInt(queryTimeoutStr)*1000;
             } catch(Exception e) {
                 // silently failover to default
             }
@@ -239,26 +238,18 @@
         this.batchedUpdates = null;
         this.updateCounts = null;
         this.outParamIndexMap.clear();
+        this.commandStatus = State.RUNNING;
     }
 
-    /**
-     * Adds sql to this statement object's current list of commands.
-     * @param sql statement to be added to the batch
-     */
     public void addBatch(String sql) throws SQLException {
         //Check to see the statement is closed and throw an exception
         checkStatement();
         if (batchedUpdates == null) {
-            batchedUpdates = new ArrayList();
+            batchedUpdates = new ArrayList<String>();
         }
         batchedUpdates.add(sql);
     }
 
-    /**
-     * This method can be used by one thread to cancel a statement that is being
-     * executed by another thread.
-     * @throws SQLException should never occur.
-     */
     public void cancel() throws SQLException {
         /* Defect 19848 - Mark the statement cancelled before sending the CANCEL request.
          * Otherwise, it's possible get into a race where the server response is quicker
@@ -270,10 +261,6 @@
         cancelRequest();
     }
 
-    /**
-     * Warning could be schema validation errors or partial results warnings.
-     * @throws SQLException should never occur.
-     */
     public void clearWarnings() throws SQLException {
         //Check to see the statement is closed and throw an exception
         checkStatement();
@@ -282,22 +269,12 @@
         serverWarnings = null;
     }
 
-    /**
-     * Makes the set of commands in the current batch empty.
-     *
-     * @throws SQLException if a database access error occurs or the
-     * driver does not support batch statements
-     */
     public void clearBatch() throws SQLException {
-        batchedUpdates.clear();
+    	if (batchedUpdates != null) {
+    		batchedUpdates.clear();
+    	}
     }
 
-    /**
-     * In many cases, it is desirable to immediately release a Statements's database
-     * and JDBC resources instead of waiting for this to happen when it is automatically
-     * closed; the close method provides this immediate release.
-     * @throws SQLException should never occur.
-     */
     public void close() throws SQLException {
         if ( isClosed ) {
             return;
@@ -344,7 +321,7 @@
         if (batchedUpdates == null || batchedUpdates.isEmpty()) {
             return new int[0];
         }
-        String[] commands = (String[])batchedUpdates.toArray(new String[batchedUpdates.size()]);
+        String[] commands = batchedUpdates.toArray(new String[batchedUpdates.size()]);
         executeSql(commands, true, ResultsMode.UPDATECOUNT, true);
         return updateCounts;
     }
@@ -429,8 +406,19 @@
         		}
         		String key = match.group(1);
         		String value = match.group(2);
-        		if (ExecutionProperties.NEWINSTANCE.equalsIgnoreCase(key) && Boolean.valueOf(value)) {
-        			this.getMMConnection().getServerConnection().cleanUp();
+        		if (value == null) {
+        			value = match.group(3);
+        			value = StringUtil.replaceAll(value, "''", "'"); //$NON-NLS-1$ //$NON-NLS-2$
+        			value = value.substring(1, value.length() - 1);
+        		}
+        		if ("SESSION AUTHORIZATION".equalsIgnoreCase(key)) { //$NON-NLS-1$
+        			this.getMMConnection().changeUser(value, this.getMMConnection().getPassword());
+        		} else if (key.equalsIgnoreCase(TeiidURL.CONNECTION.PASSWORD)) {
+        			this.getMMConnection().setPassword(value);
+        		} else if (ExecutionProperties.NEWINSTANCE.equalsIgnoreCase(key)) {
+        			if (Boolean.valueOf(value)) {
+        				this.getMMConnection().getServerConnection().cleanUp();
+        			}
         		} else {
         			JDBCURL.addNormalizedProperty(key, value, this.driverConnection.getExecutionProperties());
         		}
@@ -533,7 +521,6 @@
         }
         
         final RequestMessage reqMessage = createRequestMessage(commands, isBatchedCommand, resultsMode);
-        reqMessage.setSync(synch);
     	ResultsFuture<ResultsMessage> pendingResult = execute(reqMessage, synch);
     	final ResultsFuture<Boolean> result = new ResultsFuture<Boolean>();
     	pendingResult.addCompletionListener(new ResultsFuture.CompletionListener<ResultsMessage>() {
@@ -549,11 +536,7 @@
 		});
     	if (synch) {
     		try {
-    			if (queryTimeoutMS > 0) {
-    				pendingResult.get(queryTimeoutMS, TimeUnit.MILLISECONDS);
-    			} else {
-    				pendingResult.get();
-    			}
+				pendingResult.get();
     			result.get(); //throw an exception if needed
     			return result;
     		} catch (ExecutionException e) {
@@ -563,8 +546,6 @@
     			throw TeiidSQLException.create(e);
     		} catch (InterruptedException e) {
     			timeoutOccurred();
-    		} catch (TimeoutException e) {
-    			timeoutOccurred();
 			}
     		throw new TeiidSQLException(JDBCPlugin.Util.getString("MMStatement.Timeout_before_complete")); //$NON-NLS-1$
     	}
@@ -581,14 +562,15 @@
         reqMsg.setFetchSize(this.fetchSize);
         reqMsg.setRowLimit(this.maxRows);
         reqMsg.setTransactionIsolation(this.driverConnection.getTransactionIsolation());
-
+        String useCallingThread = getExecutionProperty(EmbeddedProfile.USE_CALLING_THREAD);
+        reqMsg.setSync(synch && (useCallingThread == null || Boolean.valueOf(useCallingThread)));
         // Get connection properties and set them onto request message
         copyPropertiesToRequest(reqMsg);
 
         reqMsg.setExecutionId(this.currentRequestID);
         
         ResultsFuture.CompletionListener<ResultsMessage> compeletionListener = null;
-		if (queryTimeoutMS > 0 && !synch) {
+		if (queryTimeoutMS > 0) {
 			final CancelTask c = new QueryTimeoutCancelTask(queryTimeoutMS, this);
 			cancellationTimer.add(c);
 			compeletionListener = new ResultsFuture.CompletionListener<ResultsMessage>() {
@@ -641,7 +623,7 @@
             	updateCounts[i] = (Integer)results[i].get(0);
             }
             if (logger.isLoggable(Level.FINER)) {
-            	logger.fine(JDBCPlugin.Util.getString("Recieved update counts: " + Arrays.toString(updateCounts))); //$NON-NLS-1$
+            	logger.finer("Recieved update counts: " + Arrays.toString(updateCounts)); //$NON-NLS-1$
             }
             // In update scenarios close the statement implicitly
             try {
@@ -1078,9 +1060,15 @@
     }
 
 	protected void setAnalysisInfo(ResultsMessage resultsMsg) {
-        this.debugLog = resultsMsg.getDebugLog();
-        this.currentPlanDescription = resultsMsg.getPlanDescription();
-        this.annotations = resultsMsg.getAnnotations(); 
+		if (resultsMsg.getDebugLog() != null) {
+			this.debugLog = resultsMsg.getDebugLog();
+		}
+		if (resultsMsg.getPlanDescription() != null) {
+			this.currentPlanDescription = resultsMsg.getPlanDescription();
+		}
+		if (resultsMsg.getAnnotations() != null) {
+			this.annotations = resultsMsg.getAnnotations();
+		}
         this.driverConnection.setDebugLog(debugLog);
         this.driverConnection.setCurrentPlanDescription(currentPlanDescription);
         this.driverConnection.setAnnotations(annotations);
@@ -1168,7 +1156,7 @@
 	}
 	
     ResultSetImpl createResultSet(List records, Map[] columnMetadata) throws SQLException {
-        ResultSetMetaData rsmd = new ResultSetMetaDataImpl(new MetadataProvider(columnMetadata));
+        ResultSetMetaData rsmd = new ResultSetMetaDataImpl(new MetadataProvider(columnMetadata), this.getExecutionProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
 
         return createResultSet(records, rsmd);
     }


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/StatementImpl.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/StatementImpl.java:3149-3217,3220-3275,3281-3325,3355-3365
/trunk/client/src/main/java/org/teiid/jdbc/StatementImpl.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/TeiidDataSource.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/TeiidDataSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/TeiidDataSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -98,7 +98,21 @@
      */
     private boolean passthroughAuthentication = false;
     
-
+    /**
+     * Authentication type to used from client. choices are simple - which is plain user/password; krb5 - kerberos
+     */
+    private String authenticationType;
+    
+    /**
+     * Name of the jass configuration to use from the -Djava.security.auth.login.config=login.conf property
+     */
+    private String jaasName;
+    
+	/**
+     * Name of Kerberos KDC service principle name
+     */
+    private String kerberosServicePrincipleName;
+    
 	public TeiidDataSource() {
     }
 
@@ -243,6 +257,16 @@
 	private Properties buildEmbeddedProperties(final String userName, final String password) {
 		Properties props = buildProperties(userName, password);
 		props.setProperty(TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION, Boolean.toString(this.passthroughAuthentication));
+		
+		if (getAuthenticationType() != null) {
+			props.setProperty(TeiidURL.CONNECTION.AUTHENTICATION_TYPE, getAuthenticationType());
+		}
+		if (getJaasName() != null) {
+			props.setProperty(TeiidURL.CONNECTION.JAAS_NAME, getJaasName());
+		}
+		if (getKerberosServicePrincipleName() != null) {
+			props.setProperty(TeiidURL.CONNECTION.KERBEROS_SERVICE_PRINCIPLE_NAME, getKerberosServicePrincipleName());
+		}
 		return props;
 	}    
 	
@@ -466,6 +490,57 @@
 	 */
 	public void setPassthroughAuthentication(final boolean passthroughAuthentication) {
 		this.passthroughAuthentication = passthroughAuthentication;
-	}	
+	}	
+	
+    /**
+     * Authentication Type {simple, krb5} default:simple
+     * @return
+     */
+    public String getAuthenticationType() {
+		return authenticationType;
+	}
+    
+	/**
+	 * Authentication Type.
+	 * @since 7.6 
+	 * @return
+	 */
+	public void setAuthenticationType(final String authType) {
+		this.authenticationType = authType;
+	}
+	
+	/**
+	 * Application name from JAAS Login Config file
+	 * @since 7.6
+	 * @return
+	 */
+    public String getJaasName() {
+		return jaasName;
+	}
+
+	/**
+	 * Application name from JAAS Login Config file
+	 * @since 7.6
+	 */    
+	public void setJaasName(String jaasApplicationName) {
+		this.jaasName = jaasApplicationName;
+	}
+
+	/**
+	 * Kerberos KDC service principle name
+	 * @since 7.6
+	 * @return
+	 */	
+	public String getKerberosServicePrincipleName() {
+		return kerberosServicePrincipleName;
+	}
+
+	/**
+	 * Kerberos KDC service principle name
+	 * @since 7.6
+	 */	
+	public void setKerberosServicePrincipleName(String kerberosServerName) {
+		this.kerberosServicePrincipleName = kerberosServerName;
+	}
 }
 

Modified: branches/as7/client/src/main/java/org/teiid/jdbc/TeiidSQLException.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/jdbc/TeiidSQLException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/jdbc/TeiidSQLException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,6 +32,7 @@
 import org.teiid.client.ProcedureErrorInstructionException;
 import org.teiid.client.security.InvalidSessionException;
 import org.teiid.client.security.LogonException;
+import org.teiid.client.util.ExceptionUtil;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidRuntimeException;
@@ -102,10 +103,13 @@
 			return new TeiidSQLException((SQLException) exception, message, true);
 		}
 		String sqlState = SQLStates.DEFAULT;
-
-		exception = findRootException(exception);
-
-		sqlState = determineSQLState(exception, sqlState);
+		TeiidException te = ExceptionUtil.getExceptionOfType(exception, TeiidException.class);
+		if (te != null && te.getCode() != null) {
+			sqlState = te.getCode();
+		} else {
+			exception = findRootException(exception);
+			sqlState = determineSQLState(exception, sqlState);
+		}
 		return new TeiidSQLException(origException, message, sqlState);
 	}
 


Property changes on: branches/as7/client/src/main/java/org/teiid/jdbc/TeiidSQLException.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/jdbc/TeiidSQLException.java:3220-3275
/trunk/client/src/main/java/org/teiid/jdbc/TeiidSQLException.java:3188-3382

Modified: branches/as7/client/src/main/java/org/teiid/net/TeiidURL.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/net/TeiidURL.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/net/TeiidURL.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -51,6 +51,7 @@
 	public static interface CONNECTION {
 		public static final String CLIENT_IP_ADDRESS = "clientIpAddress"; //$NON-NLS-1$
 		public static final String CLIENT_HOSTNAME = "clientHostName"; //$NON-NLS-1$
+		public static final String CLIENT_MAC = "clientMAC"; //$NON-NLS-1$
 		/**
 		 * If true, will automatically select a new server instance after a communication exception.
 		 * @since 5.6
@@ -79,6 +80,16 @@
 		public static final String PASSWORD = "password"; //$NON-NLS-1$
 		
 		public static final String PASSTHROUGH_AUTHENTICATION = "PassthroughAuthentication"; //$NON-NLS-1$
+		
+		public static final String AUTHENTICATION_TYPE = "authenticationType"; //$NON-NLS-1$
+		
+		public static final String JAAS_NAME = "jaasName"; //$NON-NLS-1$
+		
+		public static final String KERBEROS_SERVICE_PRINCIPLE_NAME = "kerberosServicePrincipleName"; //$NON-NLS-1$
+        
+		public enum AuthenticationType {
+			CLEARTEXT,KRB5
+		};
 	}
 
 	public static final String DOT_DELIMITER = "."; //$NON-NLS-1$

Modified: branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnection.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnection.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -49,12 +49,14 @@
 import org.teiid.client.util.ResultsFuture;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidException;
+import org.teiid.gss.MakeGSS;
 import org.teiid.jdbc.JDBCPlugin;
 import org.teiid.net.CommunicationException;
 import org.teiid.net.ConnectionException;
 import org.teiid.net.HostInfo;
 import org.teiid.net.ServerConnection;
 import org.teiid.net.TeiidURL;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
 
 
 /**
@@ -165,8 +167,18 @@
 
 	private void logon(ILogon newLogon, boolean logoff) throws LogonException,
 			TeiidComponentException, CommunicationException {
-		LogonResult newResult = newLogon.logon(connProps);
+
 		SocketServerInstance instance = this.serverInstance;
+		LogonResult newResult = null;
+
+		AuthenticationType authType  = getAuthenticationType();
+		if (AuthenticationType.CLEARTEXT.equals(authType)) {
+			newResult = newLogon.logon(connProps);
+		}
+		else if (AuthenticationType.KRB5.equals(authType)) {
+			newResult = MakeGSS.authenticate(newLogon, connProps);
+		}
+		
 		if (logoff) {
 			if ("7.3".compareTo(this.serverInstance.getServerVersion()) <= 0) { //$NON-NLS-1$
 				//just remove the current instance - the server has already logged off the current user
@@ -175,10 +187,19 @@
 			}
 			logoffAll();
 		}
+		
 		this.logonResult = newResult;
 		this.logonResults.put(instance.getHostInfo(), this.logonResult);
 		this.connectionFactory.connected(instance, this.logonResult.getSessionToken());
 	}
+	
+	private AuthenticationType getAuthenticationType() {
+		String authStr = this.connProps.getProperty(TeiidURL.CONNECTION.AUTHENTICATION_TYPE);
+		if (authStr == null) {
+			return AuthenticationType.CLEARTEXT;
+		}
+		return AuthenticationType.valueOf(authStr);
+	}
 
 	private ILogon connect(HostInfo hostInfo) throws CommunicationException,
 			IOException {

Modified: branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
===================================================================
--- branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,6 +30,8 @@
 import java.lang.reflect.Proxy;
 import java.net.InetAddress;
 import java.net.MalformedURLException;
+import java.net.NetworkInterface;
+import java.net.SocketException;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.HashMap;
@@ -323,8 +325,19 @@
 			InetAddress addr = InetAddress.getLocalHost();
 			connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, addr.getHostAddress());
 			connectionProperties.put(TeiidURL.CONNECTION.CLIENT_HOSTNAME, addr.getCanonicalHostName());
+			NetworkInterface ni = NetworkInterface.getByInetAddress(addr);
+			if (ni != null && ni.getHardwareAddress() != null) {
+				StringBuilder sb = new StringBuilder();
+				for (byte b : ni.getHardwareAddress()) {
+					sb.append(PropertiesUtils.toHex(b >> 4));
+					sb.append(PropertiesUtils.toHex(b));
+				}
+				connectionProperties.put(TeiidURL.CONNECTION.CLIENT_MAC, sb.toString());
+			}
         } catch (UnknownHostException err1) {
         	connectionProperties.put(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS, "UnknownClientAddress"); //$NON-NLS-1$
+        } catch (SocketException e) {
+        	
         }
 	}
 


Property changes on: branches/as7/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java:3149-3217
/trunk/client/src/main/java/org/teiid/net/socket/SocketServerConnectionFactory.java:3188-3382


Property changes on: branches/as7/client/src/main/java/org/teiid/netty/handler/codec/serialization
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/client/src/main/resources/org/teiid/jdbc/i18n.properties
===================================================================
--- branches/as7/client/src/main/resources/org/teiid/jdbc/i18n.properties	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/main/resources/org/teiid/jdbc/i18n.properties	2011-08-18 16:17:24 UTC (rev 3394)
@@ -150,3 +150,8 @@
 TeiidURL.port_out_of_range=The port ''{0}'' is out of range.
 
 BatchSerializer.datatype_mismatch=The modeled datatype {0} for column {1} doesn''t match the runtime type "{2}". Please ensure that the column''s modeled datatype matches the expected data.
+
+
+no_krb_ticket=No cached kerberos ticket found and/or no password supplied
+gss_auth_failed=GSS Authentication failed
+setup_failed=Protocol error.  Session setup failed.


Property changes on: branches/as7/client/src/test/java/org/teiid/client/TestRequestMessage.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/client/src/test/java/org/teiid/jdbc/TestAllResultsImpl.java
===================================================================
--- branches/as7/client/src/test/java/org/teiid/jdbc/TestAllResultsImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/java/org/teiid/jdbc/TestAllResultsImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -733,7 +733,7 @@
 		}
 		
 		ResultsMessage msg = exampleResultsMsg4(1, batchLength, fetchSize, batchLength == totalLength);
-		return new ResultSetImpl(msg, statement, new ResultSetMetaDataImpl(new MetadataProvider(DeferredMetadataProvider.loadPartialMetadata(msg.getColumnNames(), msg.getDataTypes()))), 0);
+		return new ResultSetImpl(msg, statement, new ResultSetMetaDataImpl(new MetadataProvider(DeferredMetadataProvider.loadPartialMetadata(msg.getColumnNames(), msg.getDataTypes())), null), 0);
 	}
 
 	// /////////////////////Helper Method///////////////////

Modified: branches/as7/client/src/test/java/org/teiid/jdbc/TestConnection.java
===================================================================
--- branches/as7/client/src/test/java/org/teiid/jdbc/TestConnection.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/java/org/teiid/jdbc/TestConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,7 +22,8 @@
 
 package org.teiid.jdbc;
 
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.stub;
 
 import java.sql.SQLException;
 import java.util.Properties;
@@ -38,8 +39,6 @@
 import org.teiid.client.util.ResultsFuture;
 import org.teiid.client.xa.XATransactionException;
 import org.teiid.client.xa.XidImpl;
-import org.teiid.jdbc.BaseDataSource;
-import org.teiid.jdbc.ConnectionImpl;
 import org.teiid.net.ServerConnection;
 
 
@@ -48,13 +47,28 @@
 	protected static final String STD_DATABASE_NAME         = "QT_Ora9DS"; //$NON-NLS-1$
     protected static final int STD_DATABASE_VERSION      = 1; 
     
-    static String serverUrl = "jdbc:metamatrix:QT_Ora9DS at mm://localhost:7001;version=1;user=metamatrixadmin;password=mm"; //$NON-NLS-1$
+    static String serverUrl = "jdbc:teiid:QT_Ora9DS at mm://localhost:7001;version=1;user=metamatrixadmin;password=mm"; //$NON-NLS-1$
 
     public TestConnection(String name) {
         super(name);
     }
     
+    static class  InnerDriver extends TeiidDriver {
+    	String iurl = null;
+    	public InnerDriver(String url) {
+    		iurl = url;
+    	}
+
+    	public void parseUrl(Properties props) throws SQLException {
+ 				super.parseURL(iurl, props);
+    	}
+    }
+    
     public static ConnectionImpl getMMConnection() {
+    	return getMMConnection(serverUrl);  	
+    }
+    
+    public static ConnectionImpl getMMConnection(String url) {
     	ServerConnection mock = mock(ServerConnection.class);
     	DQP dqp = mock(DQP.class);
     	try {
@@ -79,13 +93,20 @@
 		} catch (XATransactionException e) {
 			throw new RuntimeException(e);
 		}
+		
+		Properties props = new Properties();
+		
+		try {
+			new InnerDriver(url).parseUrl(props);
+		} catch (SQLException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+		
     	stub(mock.getService(DQP.class)).toReturn(dqp);
-    	Properties props = new Properties();
-    	props.setProperty(BaseDataSource.VDB_NAME, STD_DATABASE_NAME);
-    	props.setProperty(BaseDataSource.VDB_VERSION, String.valueOf(STD_DATABASE_VERSION));
-    	props.setProperty(BaseDataSource.USER_NAME, "metamatrixadmin"); //$NON-NLS-1$
-    	stub(mock.getLogonResult()).toReturn(new LogonResult(new SessionToken(1, "metamatrixadmin"), STD_DATABASE_NAME,STD_DATABASE_VERSION , "fake")); //$NON-NLS-1$
-    	return new ConnectionImpl(mock, props, serverUrl);
+    	
+    	stub(mock.getLogonResult()).toReturn(new LogonResult(new SessionToken(1, "admin"), STD_DATABASE_NAME,STD_DATABASE_VERSION , "fake")); //$NON-NLS-1$
+    	return new ConnectionImpl(mock, props, url);
     }
 
     public void testGetMetaData() throws Exception {
@@ -103,7 +124,7 @@
 
     /** test getUserName() through DriverManager */
     public void testGetUserName2() throws Exception {        
-        assertEquals("Actual userName is not equal to the expected one. ", "metamatrixadmin", getMMConnection().getUserName()); //$NON-NLS-1$ //$NON-NLS-2$
+        assertEquals("Actual userName is not equal to the expected one. ", "admin", getMMConnection().getUserName()); //$NON-NLS-1$ //$NON-NLS-2$
     }
       
     /** test isReadOnly default value on Connection */
@@ -129,4 +150,27 @@
             // error expected
         }
     }
+    
+    /**
+     * Test the default of the JDBC4 spec semantics is true
+     */
+    public void testDefaultSpec() throws Exception {
+        assertEquals("true",
+        		(getMMConnection().getExecutionProperties().getProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS) == null ? "true" : "false"));
+    } 
+    
+    /**
+     * Test turning off the JDBC 4 semantics
+     */
+    public void testTurnOnSpec() throws Exception {
+        assertEquals("true", getMMConnection(serverUrl + ";useJDBC4ColumnNameAndLabelSemantics=true").getExecutionProperties().getProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
+    }    
+    
+    /**
+     * Test turning off the JDBC 4 semantics
+     */
+    public void testTurnOffSpec() throws Exception {
+        assertEquals("false", getMMConnection(serverUrl + ";useJDBC4ColumnNameAndLabelSemantics=false").getExecutionProperties().getProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
+    }
+
 }


Property changes on: branches/as7/client/src/test/java/org/teiid/jdbc/TestConnection.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/test/java/org/teiid/jdbc/TestConnection.java:3281-3325
/trunk/client/src/test/java/org/teiid/jdbc/TestConnection.java:3188-3382

Modified: branches/as7/client/src/test/java/org/teiid/jdbc/TestSQLException.java
===================================================================
--- branches/as7/client/src/test/java/org/teiid/jdbc/TestSQLException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/java/org/teiid/jdbc/TestSQLException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,6 +22,8 @@
 
 package org.teiid.jdbc;
 
+import static org.junit.Assert.*;
+
 import java.io.IOException;
 import java.net.ConnectException;
 import java.net.MalformedURLException;
@@ -31,23 +33,21 @@
 import java.net.UnknownHostException;
 import java.sql.SQLException;
 
-import junit.framework.TestCase;
-
+import org.junit.Test;
 import org.teiid.client.ProcedureErrorInstructionException;
-import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidException;
-import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.net.CommunicationException;
 import org.teiid.net.ConnectionException;
 
 
-public class TestSQLException extends TestCase {
+public class TestSQLException {
   
 	/*
 	 * Test method for 'com.metamatrix.jdbc.MMSQLException.MMSQLException()'
 	 */
-	public void testMMSQLException() {
+	@Test public void testMMSQLException() {
 		TeiidSQLException e = new TeiidSQLException();
 		String sqlState = e.getSQLState();
 		Throwable cause = e.getCause();
@@ -82,7 +82,7 @@
 	 * Tests various simple exceptions to see if the expected SQLState is
 	 * returend.
 	 */
-	public void testCreateThrowable_01() {
+	@Test public void testCreateThrowable_01() {
 		testCreateThrowable(new CommunicationException(
 				"A test MM Communication Exception"), //$NON-NLS-1$
 				SQLStates.CONNECTION_EXCEPTION_STALE_CONNECTION);
@@ -133,7 +133,7 @@
 	 * Tests various nested exceptions to see if the expected SQLState is
 	 * returend.
 	 */
-	public void testCreateThrowable_02() {
+	@Test public void testCreateThrowable_02() {
 		testCreateThrowable(
 				new CommunicationException(new ConnectException(
 						"A test java.net.ConnectException"), //$NON-NLS-1$
@@ -150,7 +150,7 @@
 				SQLStates.CONNECTION_EXCEPTION_STALE_CONNECTION);
 	}
     
-    public void testCreateThrowable3() {
+    @Test public void testCreateThrowable3() {
         TeiidSQLException e = testCreateThrowable(
                             new TeiidException(
                                     new TeiidRuntimeException(
@@ -180,31 +180,15 @@
 		Throwable nestedException = e.getCause();
 		SQLException nextException = e.getNextException();
 
-		assertTrue("Expected MMSQLException.getSQLState() to return \"" //$NON-NLS-1$
-				+ esqlState + "\" but got \"" + sqlState + "\" instead.", //$NON-NLS-1$ //$NON-NLS-2$
-				sqlState.compareTo(esqlState) == 0);
-		assertTrue("Expected MMSQLException.getCause() to return [" //$NON-NLS-1$
-				+ (ecause != null ? ecause.getClass().getName() : "<null>") //$NON-NLS-1$
-				+ "] but got [" //$NON-NLS-1$
-				+ (cause != null ? cause.getClass().getName() : "<unknown>") //$NON-NLS-1$
-				+ "] instead.", cause == ecause); //$NON-NLS-1$
-		assertTrue(
-				"Expected MMSQLException.getErrorCode() to return [0] but got [" //$NON-NLS-1$
-						+ errorCode + "] instead.", errorCode == 0); //$NON-NLS-1$
-		assertTrue("Expected MMSQLException.getNestedException() to return [" //$NON-NLS-1$
-				+ (ecause != null ? ecause.getClass().getName() : "<null>") //$NON-NLS-1$
-				+ "] but got [" //$NON-NLS-1$
-				+ (nestedException != null ? nestedException.getClass()
-						.getName() : "<unknown>") + "] instead.", //$NON-NLS-1$ //$NON-NLS-2$
-				nestedException == ecause);
-		assertTrue(
-				"Expected MMSQLException.getNextException() to return <null> but got a SQLException with message \"" //$NON-NLS-1$
-						+ (nextException != null ? nextException.getMessage()
-								: "") + "\" instead.", nextException == null); //$NON-NLS-1$ //$NON-NLS-2$
+		assertEquals(esqlState, sqlState);
+		assertEquals(ecause, cause);
+		assertEquals(0, errorCode);
+		assertEquals(nestedException, ecause);
+		assertNull(nextException);
 		return e;
     }
     
-    public void testCreate() {
+    @Test public void testCreate() {
         TeiidSQLException exception = TeiidSQLException.create(new Exception());
         
         assertEquals(exception.getMessage(), Exception.class.getName());
@@ -214,7 +198,7 @@
         assertEquals(exception, TeiidSQLException.create(exception));
     }
     
-    public void testCreateFromSQLException() {
+    @Test public void testCreateFromSQLException() {
         SQLException sqlexception = new SQLException("foo", "21"); //$NON-NLS-1$ //$NON-NLS-2$
         
         SQLException nested = new SQLException("bar"); //$NON-NLS-1$
@@ -230,5 +214,15 @@
         assertEquals(exception.getNextException().getMessage(), sqlexception.getMessage());
         assertEquals(exception.getNextException().getNextException().getMessage(), nested.getMessage());
     }
+    
+    @Test public void testCodeAsSQLState() {
+        TeiidException sqlexception = new TeiidException("foo", "21"); //$NON-NLS-1$ //$NON-NLS-2$
+        
+        String message = "top level message"; //$NON-NLS-1$
+        
+        TeiidSQLException exception = TeiidSQLException.create(sqlexception, message);
+        
+        assertEquals(sqlexception.getCode(), exception.getSQLState());        
+    }
 
 }


Property changes on: branches/as7/client/src/test/java/org/teiid/jdbc/TestSQLException.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/test/java/org/teiid/jdbc/TestSQLException.java:3220-3275
/trunk/client/src/test/java/org/teiid/jdbc/TestSQLException.java:3188-3382

Modified: branches/as7/client/src/test/java/org/teiid/jdbc/TestStatement.java
===================================================================
--- branches/as7/client/src/test/java/org/teiid/jdbc/TestStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/java/org/teiid/jdbc/TestStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -50,6 +50,7 @@
 		results.getResultsReceiver().receiveResults(rm);
 		Mockito.stub(conn.getDQP()).toReturn(dqp);
 		StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+		statement.clearBatch(); //previously caused npe
 		statement.addBatch("delete from table"); //$NON-NLS-1$
 		statement.addBatch("delete from table1"); //$NON-NLS-1$
 		assertTrue(Arrays.equals(new int[] {1, 2}, statement.executeBatch()));
@@ -62,8 +63,20 @@
 		StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
 		assertFalse(statement.execute("set foo bar")); //$NON-NLS-1$
 		assertEquals("bar", p.get("foo")); //$NON-NLS-1$ //$NON-NLS-2$
+		
+		assertFalse(statement.execute("set foo 'b''ar'")); //$NON-NLS-1$
+		assertEquals("b'ar", p.get("foo")); //$NON-NLS-1$ //$NON-NLS-2$
 	}
 	
+	@Test public void testSetAuthorizationStatement() throws Exception {
+		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+		Properties p = new Properties();
+		Mockito.stub(conn.getExecutionProperties()).toReturn(p);
+		StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+		assertFalse(statement.execute("set session authorization bar")); //$NON-NLS-1$
+		Mockito.verify(conn).changeUser("bar", null);
+	}
+	
 	@Test public void testPropertiesOverride() throws Exception {
 		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
 		Properties p = new Properties();
@@ -115,8 +128,32 @@
 		ResultsFuture<ResultsMessage> future = new ResultsFuture<ResultsMessage>();
 		Mockito.stub(dqp.executeRequest(Mockito.anyLong(), (RequestMessage) Mockito.anyObject())).toReturn(future);
 		statement.submitExecute("select 'hello world'");
-		Thread.sleep(100);
+		Thread.sleep(300);
 		Mockito.verify(dqp).cancelRequest(0);
+		statement.setQueryTimeoutMS(1);
+		statement.submitExecute("select 'hello world'");
+		Thread.sleep(300);
+		Mockito.verify(dqp, Mockito.times(2)).cancelRequest(0);
 	}
 	
+	@Test public void testTimeoutProperty() throws Exception {
+		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+		Properties p = new Properties();
+		p.setProperty(ExecutionProperties.QUERYTIMEOUT, "2");
+		Mockito.stub(conn.getExecutionProperties()).toReturn(p);
+		StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+		assertEquals(2, statement.getQueryTimeout());
+	}
+	
+	@Test public void testUseJDBC4ColumnNameAndLabelSemantics() throws Exception {
+		ConnectionImpl conn = Mockito.mock(ConnectionImpl.class);
+		Properties p = new Properties();
+		p.setProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS, "false");
+
+		Mockito.stub(conn.getExecutionProperties()).toReturn(p);
+		StatementImpl statement = new StatementImpl(conn, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+		assertEquals(Boolean.FALSE.toString(), statement.getExecutionProperty(ExecutionProperties.JDBC4COLUMNNAMEANDLABELSEMANTICS));
+		
+	}	
+	
 }


Property changes on: branches/as7/client/src/test/java/org/teiid/jdbc/TestStatement.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/test/java/org/teiid/jdbc/TestStatement.java:3149-3217,3220-3275
/trunk/client/src/test/java/org/teiid/jdbc/TestStatement.java:3188-3382

Modified: branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDataSource.java
===================================================================
--- branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDataSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDataSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -75,6 +75,7 @@
         dataSource.setPartialResultsMode(STD_PARTIAL_MODE);
         dataSource.setSecure(true);
         dataSource.setAlternateServers(STD_ALTERNATE_SERVERS);
+        dataSource.setUseJDBC4ColumnNameAndLabelSemantics(true);
     }
 
     // =========================================================================
@@ -141,6 +142,19 @@
                                      final int fetchSize, final boolean showPlan,
                                      final boolean secure, final String expectedURL) {
 
+ 
+    		helpTestBuildingURL2(vdbName, vdbVersion, serverName, portNumber, alternateServers,
+    					txnAutoWrap, partialMode, fetchSize, showPlan, secure, true, expectedURL);
+    }
+    
+    public void helpTestBuildingURL2( final String vdbName, final String vdbVersion,
+            final String serverName, final int portNumber,
+            final String alternateServers,
+            final String txnAutoWrap, final String partialMode,
+            final int fetchSize, final boolean showPlan,
+            final boolean secure, final boolean useJDBC4Semantics,
+            final String expectedURL ) {
+    	
         final TeiidDataSource ds = new TeiidDataSource();
         ds.setServerName(serverName);
         ds.setDatabaseVersion(vdbVersion);
@@ -154,6 +168,7 @@
         }
         ds.setSecure(secure);
         ds.setAlternateServers(alternateServers);
+        ds.setUseJDBC4ColumnNameAndLabelSemantics(useJDBC4Semantics);
 
         String url;
 		try {
@@ -184,6 +199,7 @@
         ds.setTransactionAutoWrap(txnAutoWrap);
         ds.setPartialResultsMode(partialMode);
         ds.setAlternateServers(alternateServers);
+        ds.setUseJDBC4ColumnNameAndLabelSemantics(true);
 
         return ds.getConnection();
 
@@ -627,6 +643,21 @@
                             "jdbc:teiid:vdbName at mm://hostName:7001,hostName:7002,hostName2:7001,hostName2:7002;ApplicationName=JDBC;SHOWPLAN=ON;partialResultsMode=false;autoCommitTxn=DETECT;VirtualDatabaseName=vdbName"); //$NON-NLS-1$ 
     }
     
+    /**
+     * Test turning off using JDBC4 semantics
+     */
+    public void testBuildURL8() {
+        final String serverName = "hostName"; //$NON-NLS-1$
+        final String vdbName = "vdbName"; //$NON-NLS-1$
+        final String vdbVersion = "1.2.3"; //$NON-NLS-1$
+        final int portNumber = 7001;
+        final String transactionAutoWrap = null;
+        final String partialMode = "true"; //$NON-NLS-1$
+        final boolean secure = false;
+        helpTestBuildingURL2(vdbName,vdbVersion,serverName,portNumber,null,transactionAutoWrap, partialMode, 500, false, secure, false,
+                            "jdbc:teiid:vdbName at mm://hostname:7001;fetchSize=500;ApplicationName=JDBC;VirtualDatabaseVersion=1.2.3;partialResultsMode=true;useJDBC4ColumnNameAndLabelSemantics=false;VirtualDatabaseName=vdbName"); //$NON-NLS-1$
+    }
+    
     public void testBuildURL_AdditionalProperties() throws TeiidSQLException {
     	final TeiidDataSource ds = new TeiidDataSource();
     	ds.setAdditionalProperties("foo=bar;a=b"); //$NON-NLS-1$

Modified: branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java
===================================================================
--- branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -89,7 +89,10 @@
         assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log")); //$NON-NLS-1$
         assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234;logLevel=2;logFile=D:\\metamatrix\\work\\DQP\\log\\jdbcLogFile.log;autoCommitTxn=OFF;paritalResultsMode=true")); //$NON-NLS-1$
         assertTrue(!drv.acceptsURL("jdbc:teiid:@localhost:1234;stickyConnections=false;socketsPerVM=4")); //$NON-NLS-1$
-        assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://my_host.mydomain.com:53535,127.0.0.1:1234")); //$NON-NLS-1$        
+        assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://my_host.mydomain.com:53535,127.0.0.1:1234")); //$NON-NLS-1$    
+        
+        assertTrue(drv.acceptsURL("jdbc:teiid:vdb at mm://localhost:1234;version=x;useJDBC4ColumnNameAndLabelSemantics=false")); //$NON-NLS-1$
+
     }
 
     /** Invalid format of urls*/
@@ -135,7 +138,7 @@
     @Test public void testGetPropertyInfo1() throws Exception {        
         DriverPropertyInfo info[] = drv.getPropertyInfo("jdbc:teiid:vdb at mm://localhost:12345;applicationName=x", null); //$NON-NLS-1$
 
-        assertEquals(19, info.length);
+        assertEquals(24, info.length);
         assertEquals(false, info[0].required);
         assertEquals("ApplicationName", info[0].name); //$NON-NLS-1$
         assertEquals("x", info[0].value); //$NON-NLS-1$


Property changes on: branches/as7/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java:3149-3217,3281-3325
/trunk/client/src/test/java/org/teiid/jdbc/TestTeiidDriver.java:3188-3382

Modified: branches/as7/client/src/test/java/org/teiid/net/socket/TestSocketServerConnection.java
===================================================================
--- branches/as7/client/src/test/java/org/teiid/net/socket/TestSocketServerConnection.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/java/org/teiid/net/socket/TestSocketServerConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -107,6 +107,12 @@
 				throws TeiidComponentException, CommunicationException {
 			return ping();
 		}
+
+		@Override
+		public LogonResult neogitiateGssLogin(Properties connectionProperties,
+				byte[] serviceToken, boolean createSession) throws LogonException {
+			return null;
+		}
 	}
 
 	/**


Property changes on: branches/as7/client/src/test/resources/metamatrix.keystore
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/client/src/test/resources/metamatrix.truststore
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/client/src/test/resources/vdb-describe.txt
===================================================================
--- branches/as7/client/src/test/resources/vdb-describe.txt	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client/src/test/resources/vdb-describe.txt	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,7 +24,7 @@
             "description" : "The Virtual Database Status",
             "required" : true
         },
-        "version" : {
+        "vdb-version" : {
             "type" : {
                 "TYPE_MODEL_VALUE" : "INT"
             },

Modified: branches/as7/client-jdk15/pom.xml
===================================================================
--- branches/as7/client-jdk15/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/client-jdk15/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>teiid-client-jdk15</artifactId>

Deleted: branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java
===================================================================
--- trunk/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,35 +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 net.sf.retrotranslator.runtime.java.net;
-
-import java.net.NetworkInterface;
-import java.net.SocketException;
-
-public class _NetworkInterface {
-	
-	@SuppressWarnings("unused")
-	public static byte[] getHardwareAddress(NetworkInterface ni) throws SocketException {
-		return null;
-	}
-
-}

Copied: branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java (from rev 3382, trunk/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java)
===================================================================
--- branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java	                        (rev 0)
+++ branches/as7/client-jdk15/src/main/java/net/sf/retrotranslator/runtime/java/net/_NetworkInterface.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,35 @@
+/*
+ * 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 net.sf.retrotranslator.runtime.java.net;
+
+import java.net.NetworkInterface;
+import java.net.SocketException;
+
+public class _NetworkInterface {
+	
+	@SuppressWarnings("unused")
+	public static byte[] getHardwareAddress(NetworkInterface ni) throws SocketException {
+		return null;
+	}
+
+}

Modified: branches/as7/common-core/pom.xml
===================================================================
--- branches/as7/common-core/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/common-core/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>teiid-common-core</artifactId>

Modified: branches/as7/common-core/src/main/java/org/teiid/core/TeiidException.java
===================================================================
--- branches/as7/common-core/src/main/java/org/teiid/core/TeiidException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/common-core/src/main/java/org/teiid/core/TeiidException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -58,7 +58,7 @@
 
     public TeiidException(Throwable e, String message) {
         super(message, e);
-        setCode(e);
+        setCode(getCode(e));
     }
     
     public TeiidException(Throwable e, String errorCode, String message) {
@@ -82,14 +82,15 @@
 		this.originalType = originalType;
 	}
     
-    private void setCode(Throwable e) {
+    static String getCode(Throwable e) {
         if (e instanceof TeiidException) {
-            this.code = (((TeiidException) e).getCode());
+            return (((TeiidException) e).getCode());
         } else if (e instanceof TeiidRuntimeException) {
-        	this.code = ((TeiidRuntimeException) e).getCode();
+        	return ((TeiidRuntimeException) e).getCode();
         } else if (e instanceof SQLException) {
-        	this.code = Integer.toString(((SQLException)e).getErrorCode());
+        	return ((SQLException)e).getSQLState();
         }
+        return null;
     }
     
 	public String getMessage() {


Property changes on: branches/as7/common-core/src/main/java/org/teiid/core/TeiidException.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/common-core/src/main/java/org/teiid/core/TeiidException.java:3220-3275
/trunk/common-core/src/main/java/org/teiid/core/TeiidException.java:3188-3382

Modified: branches/as7/common-core/src/main/java/org/teiid/core/TeiidRuntimeException.java
===================================================================
--- branches/as7/common-core/src/main/java/org/teiid/core/TeiidRuntimeException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/common-core/src/main/java/org/teiid/core/TeiidRuntimeException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,10 +22,6 @@
 
 package org.teiid.core;
 
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.sql.SQLException;
-
 import org.teiid.core.util.ExceptionUtil;
 
 
@@ -40,26 +36,9 @@
 public class TeiidRuntimeException extends RuntimeException {
     public static final long serialVersionUID = -4035276728007979320L;
     
-    private static final String EMPTY_STRING = ""; //$NON-NLS-1$
     public static final String CAUSED_BY_STRING = CorePlugin.Util.getString("RuntimeException.Caused_by"); //$NON-NLS-1$
     
     //############################################################################################################################
-    //# Static Methods                                                                                                           #
-    //############################################################################################################################
-    
-    /**
-     * Utility method to get the name of a class, without package information.
-     *
-     * @param cls The class to get the name of
-     * @return The name of the class, without package info
-     */
-    public static String getClassShortName( Class cls ) {
-        if ( cls == null ) return EMPTY_STRING;
-        String className = cls.getName();
-        return className.substring( className.lastIndexOf('.')+1 );
-    }
-    
-    //############################################################################################################################
     //# Variables                                                                                                                #
     //############################################################################################################################
 
@@ -86,19 +65,6 @@
         super(message);
     }
 
-    /**
-     * Construct an instance with the specified error code and message.  If the message is actually a key, the actual message will
-     * be retrieved from a resource bundle using the key, and the specified parameters will be substituted for placeholders within
-     * the message.
-     * @param code    The error code 
-     * @param message The error message or a resource bundle key
-     */
-    public TeiidRuntimeException(final int code, final String message) {
-        super(message);
-        // The following setCode call should be executed after setting the message 
-        setCode(code);
-    }
-    
     public TeiidRuntimeException(final String code, final String message) {
         super(message);
         // The following setCode call should be executed after setting the message 
@@ -125,23 +91,10 @@
      */
     public TeiidRuntimeException(final Throwable e, final String message) {
         super(message, e);
-        setCode(e);
+        setCode(TeiidException.getCode(e));
     }
 
     /**
-     * Construct an instance with the linked exception, error code, and error message specified.  If the message is actually a
-     * key, the error message will be retrieved from a resource bundle using the key.
-     * @param e       The exception to chain to this exception
-     * @param code    The error code 
-     * @param message The error message or a resource bundle key
-     */
-    public TeiidRuntimeException(final Throwable e, final int code, final String message) {
-        super(message, e);
-        // The following setCode call should be executed after setting the message 
-        setCode(code);
-    }
-    
-    /**
      * Construct an instance with the linked exception, error code, and error message specified. If the specified
      * exception is a {@link TeiidException} or a MetaMatrixRuntimeException, the code will
      * be set to the exception's code.
@@ -164,6 +117,7 @@
      * Get the exception which is linked to this exception.
      *
      * @return The linked exception
+     * @deprecated use {@link #getCause()} instead
      */
     public Throwable getChild() {
         return this.getCause();
@@ -175,47 +129,13 @@
      * @return The error code 
      */
     public String getCode() {
-    	if (code == null) {
-    		return "0"; //$NON-NLS-1$
-    	}
         return this.code;
     }
     
-    public int getIntCode() {
-    	if (code == null) {
-    		return 0;
-    	}
-        try {
-        	return Integer.parseInt(code);
-        } catch (NumberFormatException e) {
-        	
-        }
-        return 0;
-    }
-
-    /**
-     * Set the error code.
-     *
-     * @param code The error code 
-     */
-    private void setCode( int code ) {
-        this.code = Integer.toString(code);
-    }
-    
     private void setCode( String code ) {
         this.code = code;
     }
 
-    private void setCode(Throwable e) {
-        if (e instanceof TeiidException) {
-            this.code = (((TeiidException) e).getCode());
-        } else if (e instanceof TeiidRuntimeException) {
-        	this.code = ((TeiidRuntimeException) e).getCode();
-        } else if (e instanceof SQLException) {
-        	this.code = Integer.toString(((SQLException)e).getErrorCode());
-        }
-    }
-
     /**
      * Returns a string representation of this class.
      *
@@ -225,12 +145,4 @@
         return ExceptionUtil.getLinkedMessages(this);
     }
 
-    public void superPrintStackTrace(PrintStream output) {
-        super.printStackTrace(output);
-    }
-
-    public void superPrintStackTrace(PrintWriter output) {
-        super.printStackTrace(output);
-    }
-    
 }


Property changes on: branches/as7/common-core/src/main/java/org/teiid/core/TeiidRuntimeException.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/common-core/src/main/java/org/teiid/core/TeiidRuntimeException.java:3220-3275
/trunk/common-core/src/main/java/org/teiid/core/TeiidRuntimeException.java:3188-3382


Property changes on: branches/as7/common-core/src/main/java/org/teiid/core/util/ApplicationInfo.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java
===================================================================
--- branches/as7/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/common-core/src/main/java/org/teiid/core/util/PropertiesUtils.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -716,7 +716,7 @@
      * Convert a nibble to a hex character
      * @param   nibble  the nibble to convert.
      */
-    private static char toHex(int nibble) {
+    public static char toHex(int nibble) {
     return hexDigit[(nibble & 0xF)];
     }
 

Modified: branches/as7/common-core/src/main/java/org/teiid/core/util/StringUtil.java
===================================================================
--- branches/as7/common-core/src/main/java/org/teiid/core/util/StringUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/common-core/src/main/java/org/teiid/core/util/StringUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -947,7 +947,9 @@
      */
     @SuppressWarnings("unchecked")
 	public static <T> T valueOf(String value, Class type){
-    	
+    	if (value == null) {
+    		return null;
+    	}
     	if(type == String.class) {
     		return (T) value;
     	}
@@ -1011,7 +1013,7 @@
 	public static String[] getLines(final String value) {
 	    StringReader stringReader = new StringReader(value);
 	    BufferedReader reader = new BufferedReader(stringReader);
-	    ArrayList result = new ArrayList();
+	    ArrayList<String> result = new ArrayList<String>();
 	    try {
 	        String line = reader.readLine();
 	        while (line != null) {
@@ -1021,7 +1023,16 @@
 	    } catch (IOException e) {
 	        throw new TeiidRuntimeException(e);
 	    }
-	    return (String[]) result.toArray(new String[result.size()]);
+	    return result.toArray(new String[result.size()]);
 	}
 	
+	public static boolean equalsIgnoreCase(String s1, String s2) {
+		if (s1 != null) {
+			return s1.equalsIgnoreCase(s2);
+		} else if (s2 != null) {
+			return false;
+		}
+		return true;
+	}
+	
 }

Modified: branches/as7/common-core/src/test/java/org/teiid/core/TestMetaMatrixRuntimeException.java
===================================================================
--- branches/as7/common-core/src/test/java/org/teiid/core/TestMetaMatrixRuntimeException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/common-core/src/test/java/org/teiid/core/TestMetaMatrixRuntimeException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -63,16 +63,16 @@
 
     public void testMetaMatrixRuntimeExceptionWithNullThrowable() {
         final TeiidRuntimeException err = new TeiidRuntimeException((Throwable)null);
-        assertNull(err.getChild());
-        assertEquals("0", err.getCode()); //$NON-NLS-1$
+        assertNull(err.getCause());
+        assertNull(err.getCode()); 
         assertNull(err.getMessage());
         
     }
 
     public void testMetaMatrixRuntimeExceptionWithMessage() {
         final TeiidRuntimeException err = new TeiidRuntimeException("Test"); //$NON-NLS-1$
-        assertNull(err.getChild());
-        assertEquals("0", err.getCode()); //$NON-NLS-1$
+        assertNull(err.getCause());
+        assertNull(err.getCode());
         assertEquals("Test", err.getMessage()); //$NON-NLS-1$
         
     }
@@ -80,7 +80,7 @@
     public void testMetaMatrixRuntimeExceptionWithCodeAndMessage() {
         final String code = "1234"; //$NON-NLS-1$
         final TeiidRuntimeException err = new TeiidRuntimeException(code, "Test"); //$NON-NLS-1$
-        assertNull(err.getChild());
+        assertNull(err.getCause());
         assertEquals(code, err.getCode());
         assertEquals("Test", err.getMessage()); //$NON-NLS-1$
         
@@ -90,7 +90,7 @@
         final String code = "1234"; //$NON-NLS-1$
         final TeiidRuntimeException child = new TeiidRuntimeException(code, "Child"); //$NON-NLS-1$
         final TeiidRuntimeException err = new TeiidRuntimeException(child, "Test"); //$NON-NLS-1$
-        assertSame(child, err.getChild());
+        assertSame(child, err.getCause());
         assertEquals(code, err.getCode());
         assertEquals("Test", err.getMessage()); //$NON-NLS-1$
         
@@ -100,7 +100,7 @@
         final String code = "1234"; //$NON-NLS-1$
         final TeiidRuntimeException child = new TeiidRuntimeException(code, "Child"); //$NON-NLS-1$
         final TeiidRuntimeException err = new TeiidRuntimeException(child, "Code", "Test"); //$NON-NLS-1$ //$NON-NLS-2$
-        assertSame(child, err.getChild());
+        assertSame(child, err.getCause());
         assertEquals("Code", err.getCode()); //$NON-NLS-1$
         assertEquals("Test", err.getMessage()); //$NON-NLS-1$
         


Property changes on: branches/as7/common-core/src/test/java/org/teiid/core/TestMetaMatrixRuntimeException.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/common-core/src/test/java/org/teiid/core/TestMetaMatrixRuntimeException.java:3220-3275
/trunk/common-core/src/test/java/org/teiid/core/TestMetaMatrixRuntimeException.java:3188-3382


Property changes on: branches/as7/common-core/src/test/java/org/teiid/query/unittest/TimestampUtil.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/connector-file/pom.xml
===================================================================
--- branches/as7/connectors/connector-file/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-file/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>connector-file</artifactId>

Modified: branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java
===================================================================
--- branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileConnectionImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,6 +23,9 @@
 package org.teiid.resource.adapter.file;
 
 import java.io.File;
+import java.util.Collections;
+import java.util.Map;
+import java.util.regex.Pattern;
 
 import javax.resource.ResourceException;
 
@@ -36,17 +39,32 @@
 public class FileConnectionImpl extends BasicConnection implements FileConnection {
 	
 	private File parentDirectory;
+	private Map<String, String> fileMapping;
+	private boolean allowParentPaths;
+	private static final Pattern parentRef = Pattern.compile("(^\\.\\.(\\\\{2}|/)?.*)|((\\\\{2}|/)\\.\\.)"); //$NON-NLS-1$
 	
-	public FileConnectionImpl(String parentDirectory) {
+	public FileConnectionImpl(String parentDirectory, Map<String, String> fileMapping, boolean allowParentPaths) {
 		this.parentDirectory = new File(parentDirectory);
+		if (fileMapping == null) {
+			fileMapping = Collections.emptyMap();
+		}
+		this.fileMapping = fileMapping;
+		this.allowParentPaths = allowParentPaths;
 	}
 	
 	@Override
-	public File getFile(String path) {
+	public File getFile(String path) throws ResourceException {
     	if (path == null) {
     		return this.parentDirectory;
         }
-    	return new File(parentDirectory, path);	
+		String altPath = fileMapping.get(path);
+		if (altPath != null) {
+			path = altPath;
+		}
+    	if (!allowParentPaths && parentRef.matcher(path).matches()) {	
+			throw new ResourceException(FileManagedConnectionFactory.UTIL.getString("parentpath_not_allowed", path)); //$NON-NLS-1$
+		}
+		return new File(parentDirectory, path);	
     }
 
 	@Override

Modified: branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileManagedConnectionFactory.java
===================================================================
--- branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileManagedConnectionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-file/src/main/java/org/teiid/resource/adapter/file/FileManagedConnectionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,10 +21,13 @@
  */
 package org.teiid.resource.adapter.file;
 
+import java.util.Map;
+
 import javax.resource.ResourceException;
 import javax.resource.spi.InvalidPropertyException;
 
 import org.teiid.core.BundleUtil;
+import org.teiid.core.util.StringUtil;
 import org.teiid.resource.spi.BasicConnection;
 import org.teiid.resource.spi.BasicConnectionFactory;
 import org.teiid.resource.spi.BasicManagedConnectionFactory;
@@ -35,17 +38,20 @@
 	public static final BundleUtil UTIL = BundleUtil.getBundleUtil(FileManagedConnectionFactory.class);
 
 	private String parentDirectory;
+	private String fileMapping;
+	private boolean allowParentPaths = true;
 	
 	@Override
 	public BasicConnectionFactory createConnectionFactory() throws ResourceException {
 		if (this.parentDirectory == null) {
 			throw new InvalidPropertyException(UTIL.getString("parentdirectory_not_set")); //$NON-NLS-1$
 		}
+		final Map<String, String> map = StringUtil.valueOf(this.fileMapping, Map.class);
 		return new BasicConnectionFactory() {
 			
 			@Override
 			public BasicConnection getConnection() throws ResourceException {
-				return new FileConnectionImpl(parentDirectory);
+				return new FileConnectionImpl(parentDirectory, map, allowParentPaths);
 			}
 		};
 	}
@@ -58,4 +64,20 @@
 		this.parentDirectory = parentDirectory;
 	}
 	
+	public String getFileMapping() {
+		return fileMapping;
+	}
+	
+	public void setFileMapping(String fileMapping) {
+		this.fileMapping = fileMapping;
+	}
+	
+	public boolean isAllowParentPaths() {
+		return allowParentPaths;
+	}
+	
+	public void setAllowParentPaths(boolean allowParentPaths) {
+		this.allowParentPaths = allowParentPaths;
+	}
+	
 }

Modified: branches/as7/connectors/connector-file/src/main/rar/META-INF/ra.xml
===================================================================
--- branches/as7/connectors/connector-file/src/main/rar/META-INF/ra.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-file/src/main/rar/META-INF/ra.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -46,6 +46,19 @@
                <config-property-type>java.lang.String</config-property-type>
             </config-property>
             
+            <config-property>
+               <description>{$display:"File Mapping"}</description>
+               <config-property-name>FileMapping</config-property-name>
+               <config-property-type>java.lang.String</config-property-type>
+            </config-property>
+            
+             <config-property>
+               <description>{$display:"Allow Parent Paths"}</description>
+               <config-property-name>AllowParentPaths</config-property-name>
+               <config-property-type>java.lang.Boolean</config-property-type>
+               <config-property-value>true</config-property-value>
+            </config-property>
+            
             <connectionfactory-interface>javax.resource.cci.ConnectionFactory</connectionfactory-interface>
             <connectionfactory-impl-class>org.teiid.resource.spi.WrappedConnectionFactory</connectionfactory-impl-class>
             <connection-interface>javax.resource.cci.Connection</connection-interface>

Modified: branches/as7/connectors/connector-file/src/main/resources/org/teiid/resource/adapter/file/i18n.properties
===================================================================
--- branches/as7/connectors/connector-file/src/main/resources/org/teiid/resource/adapter/file/i18n.properties	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-file/src/main/resources/org/teiid/resource/adapter/file/i18n.properties	2011-08-18 16:17:24 UTC (rev 3394)
@@ -20,4 +20,5 @@
 # 02110-1301 USA.
 #
 
-parentdirectory_not_set=ParentDirectory is not set
\ No newline at end of file
+parentdirectory_not_set=ParentDirectory is not set
+parentpath_not_allowed=Parent path .. not allowed in file path {0}
\ No newline at end of file

Deleted: branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java
===================================================================
--- trunk/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,68 +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 org.teiid.resource.adapter.file;
-
-import static org.junit.Assert.*;
-
-import java.io.File;
-
-import javax.resource.ResourceException;
-
-import org.junit.Test;
-import org.teiid.resource.spi.BasicConnectionFactory;
-import org.teiid.translator.FileConnection;
-
- at SuppressWarnings("nls")
-public class TestFileConnection {
-	
-	@Test public void testFileMapping() throws Exception {
-		FileManagedConnectionFactory fmcf = new FileManagedConnectionFactory();
-		fmcf.setParentDirectory("foo");
-		fmcf.setFileMapping("x=y,z=a");
-		BasicConnectionFactory bcf = fmcf.createConnectionFactory();
-		FileConnection fc = (FileConnection)bcf.getConnection();
-		File f = fc.getFile("x");
-		assertEquals("foo/y", f.getPath());
-		f = fc.getFile("n");
-		assertEquals("foo/n", f.getPath());
-	}
-	
-	@Test(expected=ResourceException.class) public void testParentPaths() throws Exception {
-		FileManagedConnectionFactory fmcf = new FileManagedConnectionFactory();
-		fmcf.setParentDirectory("foo");
-		fmcf.setAllowParentPaths(false);
-		BasicConnectionFactory bcf = fmcf.createConnectionFactory();
-		FileConnection fc = (FileConnection)bcf.getConnection();
-		fc.getFile("../x");
-	}
-	
-	@Test public void testParentPaths1() throws Exception {
-		FileManagedConnectionFactory fmcf = new FileManagedConnectionFactory();
-		fmcf.setParentDirectory("foo");
-		fmcf.setAllowParentPaths(true);
-		BasicConnectionFactory bcf = fmcf.createConnectionFactory();
-		FileConnection fc = (FileConnection)bcf.getConnection();
-		fc.getFile("../x");
-	}
-
-}

Copied: branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java (from rev 3382, trunk/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java)
===================================================================
--- branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java	                        (rev 0)
+++ branches/as7/connectors/connector-file/src/test/java/org/teiid/resource/adapter/file/TestFileConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,68 @@
+/*
+ * 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 org.teiid.resource.adapter.file;
+
+import static org.junit.Assert.*;
+
+import java.io.File;
+
+import javax.resource.ResourceException;
+
+import org.junit.Test;
+import org.teiid.resource.spi.BasicConnectionFactory;
+import org.teiid.translator.FileConnection;
+
+ at SuppressWarnings("nls")
+public class TestFileConnection {
+	
+	@Test public void testFileMapping() throws Exception {
+		FileManagedConnectionFactory fmcf = new FileManagedConnectionFactory();
+		fmcf.setParentDirectory("foo");
+		fmcf.setFileMapping("x=y,z=a");
+		BasicConnectionFactory bcf = fmcf.createConnectionFactory();
+		FileConnection fc = (FileConnection)bcf.getConnection();
+		File f = fc.getFile("x");
+		assertEquals("foo/y", f.getPath());
+		f = fc.getFile("n");
+		assertEquals("foo/n", f.getPath());
+	}
+	
+	@Test(expected=ResourceException.class) public void testParentPaths() throws Exception {
+		FileManagedConnectionFactory fmcf = new FileManagedConnectionFactory();
+		fmcf.setParentDirectory("foo");
+		fmcf.setAllowParentPaths(false);
+		BasicConnectionFactory bcf = fmcf.createConnectionFactory();
+		FileConnection fc = (FileConnection)bcf.getConnection();
+		fc.getFile("../x");
+	}
+	
+	@Test public void testParentPaths1() throws Exception {
+		FileManagedConnectionFactory fmcf = new FileManagedConnectionFactory();
+		fmcf.setParentDirectory("foo");
+		fmcf.setAllowParentPaths(true);
+		BasicConnectionFactory bcf = fmcf.createConnectionFactory();
+		FileConnection fc = (FileConnection)bcf.getConnection();
+		fc.getFile("../x");
+	}
+
+}

Modified: branches/as7/connectors/connector-ldap/pom.xml
===================================================================
--- branches/as7/connectors/connector-ldap/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-ldap/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>connector-ldap</artifactId>

Modified: branches/as7/connectors/connector-salesforce/pom.xml
===================================================================
--- branches/as7/connectors/connector-salesforce/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-salesforce/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>connector-salesforce</artifactId>

Modified: branches/as7/connectors/connector-ws/pom.xml
===================================================================
--- branches/as7/connectors/connector-ws/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/connector-ws/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>connector-ws</artifactId>

Modified: branches/as7/connectors/pom.xml
===================================================================
--- branches/as7/connectors/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
   <parent>
     <artifactId>teiid-parent</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.jboss.teiid</groupId>
@@ -71,6 +71,17 @@
         <scope>test</scope>
     </dependency>     
      -->
+     
+    <dependency>
+        <groupId>org.jboss</groupId>
+        <artifactId>jboss-vfs</artifactId>
+        <scope>test</scope>
+    </dependency> 
+    <dependency>
+        <groupId>org.jboss.logging</groupId>
+        <artifactId>jboss-logging</artifactId>
+        <scope>test</scope>        
+    </dependency>          
     
   </dependencies>
   

Modified: branches/as7/connectors/salesforce-api/pom.xml
===================================================================
--- branches/as7/connectors/salesforce-api/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/salesforce-api/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <artifactId>connectors</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>salesforce-api</artifactId>

Deleted: branches/as7/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml
===================================================================
--- trunk/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<deployment xmlns="urn:jboss:bean-deployer:2.0">
-
-    <!-- Custom COHERENCE translator -->
-    <bean name="translator-customoracle-template" class="org.teiid.templates.TranslatorDeploymentTemplate">
-        <property name="info"><inject bean="translator-coherence" /> </property>
-        <property name="managedObjectFactory"> <inject bean="ManagedObjectFactory" /> </property>
-    </bean>
-
-    <bean name="translator-coherence" class="org.teiid.templates.TranslatorTemplateInfo">
-        <constructor factoryMethod="createTemplateInfo">
-            <factory bean="TranslatorDeploymentTemplateInfoFactory" />
-            <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
-            <parameter class="java.lang.Class">org.teiid.coherence.CoherenceExecutionFactory</parameter>
-            <parameter class="java.lang.String">translator-coherence</parameter>
-            <parameter class="java.lang.String">coherence</parameter>
-        </constructor>
-    </bean>
-
-</deployment>
\ No newline at end of file

Copied: branches/as7/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml (from rev 3382, trunk/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml)
===================================================================
--- branches/as7/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml	                        (rev 0)
+++ branches/as7/connectors/sandbox/coherence_translator/src/META-INF/jboss-beans.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<deployment xmlns="urn:jboss:bean-deployer:2.0">
+
+    <!-- Custom COHERENCE translator -->
+    <bean name="translator-customoracle-template" class="org.teiid.templates.TranslatorDeploymentTemplate">
+        <property name="info"><inject bean="translator-coherence" /> </property>
+        <property name="managedObjectFactory"> <inject bean="ManagedObjectFactory" /> </property>
+    </bean>
+
+    <bean name="translator-coherence" class="org.teiid.templates.TranslatorTemplateInfo">
+        <constructor factoryMethod="createTemplateInfo">
+            <factory bean="TranslatorDeploymentTemplateInfoFactory" />
+            <parameter class="java.lang.Class">org.teiid.templates.TranslatorTemplateInfo</parameter>
+            <parameter class="java.lang.Class">org.teiid.coherence.CoherenceExecutionFactory</parameter>
+            <parameter class="java.lang.String">translator-coherence</parameter>
+            <parameter class="java.lang.String">coherence</parameter>
+        </constructor>
+    </bean>
+
+</deployment>
\ No newline at end of file

Deleted: branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java
===================================================================
--- trunk/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,128 +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 org.teiid.coherence.connector;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Test;
-import org.teiid.coherence.translator.Leg;
-import org.teiid.coherence.translator.Trade;
-
-import com.tangosol.net.CacheFactory;
-import com.tangosol.net.NamedCache;
-
-public class TestCoherenceConnection {
-
-	static {
-		try {
-			loadCoherence();
-		} catch (Exception e) {
-			// TODO Auto-generated catch block
-			e.printStackTrace();
-		}
-	}
-
-	/**
-	 * Load the cache with 3 trades and 10 legs for each trade.
-	 * 
-	 * @throws Exception
-	 */
-	private static void loadCoherence() throws Exception {
-		NamedCache tradesCache = CacheFactory.getCache("Trades");
-
-		// populate the cache
-		Map legsMap = new HashMap();
-		Trade trade = new Trade();
-
-		for (int i = 1; i <= 3; i++) {
-
-			for (int j = 1; j <= 10; j++) {
-				Leg leg = new Leg();
-				leg.setId(j);
-				leg.setNotional(i + j);
-				legsMap.put(j, leg);
-			}
-			trade.setId(i);
-			trade.setLegs(legsMap);
-			tradesCache.put(i, trade);
-		}
-
-		System.out.println("Loaded Coherence");
-
-	}
-
-	/**
-	 * This will instantiate the {@link CoherenceManagedConnectionFactory} and
-	 * obtain a connection to
-	 * 
-	 * @throws Exception
-	 */
-	@Test
-	public void testGet1Trade() throws Exception {
-
-		CoherenceManagedConnectionFactory f = new CoherenceManagedConnectionFactory();
-		CoherenceConnection conn = (CoherenceConnection) f.createConnectionFactory().getConnection();
-
-		List<Long> ids = new ArrayList<Long>();
-		ids.add(new Long(1));
-		// List<Trade> trades = conn.getTrades(ids);
-
-		List<?> trades = conn.get("Id = " + 1 + "l");
-		if (trades == null || trades.size() == 0) {
-			throw new Exception("get1Trade: No trade found for 1");
-		} else {
-			System.out
-					.println("get1Trade: # of Trades found: " + trades.size());
-		}
-
-		// grab the first trade to confirm trade 1 was found in the cache.
-		Trade t = (Trade) trades.get(0);
-		Map legs = t.getLegs();
-		System.out.println("Num of legs are: " + legs.size());
-
-	}
-
-	@Test
-	public void testGetAllTrades() throws Exception {
-
-		CoherenceManagedConnectionFactory f = new CoherenceManagedConnectionFactory();
-		CoherenceConnection conn = (CoherenceConnection) f
-				.createConnectionFactory().getConnection();
-
-		List<Object> trades = conn.get(null);
-		if (trades == null || trades.size() == 0) {
-			throw new Exception("getAllTrades: No trades found for 1");
-		} else {
-			System.out.println("getAllTrades: # of Trades found: "
-					+ trades.size());
-		}
-
-		Trade t = (Trade) trades.get(0);
-		Map legs = t.getLegs();
-		System.out.println("Num of legs are: " + legs.size());
-
-	}
-}

Copied: branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java (from rev 3382, trunk/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java)
===================================================================
--- branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java	                        (rev 0)
+++ branches/as7/connectors/sandbox/coherence_translator/src/test/java/org/teiid/coherence/connector/TestCoherenceConnection.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,128 @@
+/*
+ * 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 org.teiid.coherence.connector;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.Test;
+import org.teiid.coherence.translator.Leg;
+import org.teiid.coherence.translator.Trade;
+
+import com.tangosol.net.CacheFactory;
+import com.tangosol.net.NamedCache;
+
+public class TestCoherenceConnection {
+
+	static {
+		try {
+			loadCoherence();
+		} catch (Exception e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * Load the cache with 3 trades and 10 legs for each trade.
+	 * 
+	 * @throws Exception
+	 */
+	private static void loadCoherence() throws Exception {
+		NamedCache tradesCache = CacheFactory.getCache("Trades");
+
+		// populate the cache
+		Map legsMap = new HashMap();
+		Trade trade = new Trade();
+
+		for (int i = 1; i <= 3; i++) {
+
+			for (int j = 1; j <= 10; j++) {
+				Leg leg = new Leg();
+				leg.setId(j);
+				leg.setNotional(i + j);
+				legsMap.put(j, leg);
+			}
+			trade.setId(i);
+			trade.setLegs(legsMap);
+			tradesCache.put(i, trade);
+		}
+
+		System.out.println("Loaded Coherence");
+
+	}
+
+	/**
+	 * This will instantiate the {@link CoherenceManagedConnectionFactory} and
+	 * obtain a connection to
+	 * 
+	 * @throws Exception
+	 */
+	@Test
+	public void testGet1Trade() throws Exception {
+
+		CoherenceManagedConnectionFactory f = new CoherenceManagedConnectionFactory();
+		CoherenceConnection conn = (CoherenceConnection) f.createConnectionFactory().getConnection();
+
+		List<Long> ids = new ArrayList<Long>();
+		ids.add(new Long(1));
+		// List<Trade> trades = conn.getTrades(ids);
+
+		List<?> trades = conn.get("Id = " + 1 + "l");
+		if (trades == null || trades.size() == 0) {
+			throw new Exception("get1Trade: No trade found for 1");
+		} else {
+			System.out
+					.println("get1Trade: # of Trades found: " + trades.size());
+		}
+
+		// grab the first trade to confirm trade 1 was found in the cache.
+		Trade t = (Trade) trades.get(0);
+		Map legs = t.getLegs();
+		System.out.println("Num of legs are: " + legs.size());
+
+	}
+
+	@Test
+	public void testGetAllTrades() throws Exception {
+
+		CoherenceManagedConnectionFactory f = new CoherenceManagedConnectionFactory();
+		CoherenceConnection conn = (CoherenceConnection) f
+				.createConnectionFactory().getConnection();
+
+		List<Object> trades = conn.get(null);
+		if (trades == null || trades.size() == 0) {
+			throw new Exception("getAllTrades: No trades found for 1");
+		} else {
+			System.out.println("getAllTrades: # of Trades found: "
+					+ trades.size());
+		}
+
+		Trade t = (Trade) trades.get(0);
+		Map legs = t.getLegs();
+		System.out.println("Num of legs are: " + legs.size());
+
+	}
+}

Deleted: branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.vdb
===================================================================
(Binary files differ)

Copied: branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.vdb (from rev 3382, trunk/connectors/sandbox/coherence_translator/src/test/resources/Coherence.vdb)
===================================================================
(Binary files differ)

Deleted: branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi
===================================================================
--- trunk/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="ASCII"?>
-<xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:diagram="http://www.metamatrix.com/metamodels/Diagram" xmlns:mmcore="http://www.metamatrix.com/metamodels/Core" xmlns:relational="http://www.metamatrix.com/metamodels/Relational">
-  <mmcore:ModelAnnotation xmi:uuid="mmuuid:f415b6fc-e09b-466a-b19b-f7bdfea4195f" primaryMetamodelUri="http://www.metamatrix.com/metamodels/Relational" modelType="PHYSICAL" ProducerName="Teiid Designer" ProducerVersion="7.1.0.v20110215-1224-H420-GA">
-    <modelImports xmi:uuid="mmuuid:c704e924-4d3e-46c1-ab88-d9811254770a" name="XMLSchema" modelLocation="http://www.w3.org/2001/XMLSchema" modelType="TYPE" primaryMetamodelUri="http://www.eclipse.org/xsd/2002/XSD"/>
-  </mmcore:ModelAnnotation>
-  <diagram:DiagramContainer xmi:uuid="mmuuid:edd4ddef-d373-4aeb-8cf8-212cdd21c3f2">
-    <diagram xmi:uuid="mmuuid:7f6fce9d-a334-4260-9a3a-33f397b9f188" type="packageDiagramType" target="mmuuid/f415b6fc-e09b-466a-b19b-f7bdfea4195f">
-      <diagramEntity xmi:uuid="mmuuid:56b9d09d-2135-4f2f-b19d-eb2925dc1192" name="Trade" modelObject="mmuuid/be73e0b2-9cf2-4d65-a26a-b8fa0892c191" xPosition="20" yPosition="20"/>
-    </diagram>
-  </diagram:DiagramContainer>
-  <mmcore:AnnotationContainer xmi:uuid="mmuuid:7de5077c-41da-4353-b854-d97d63fb5a2c"/>
-  <relational:BaseTable xmi:uuid="mmuuid:be73e0b2-9cf2-4d65-a26a-b8fa0892c191" name="Trade">
-    <columns xmi:uuid="mmuuid:6daf8dc7-6d1b-4564-98dd-3ab2a7f2c0dd" name="TradeID" nativeType="Long">
-      <type href="http://www.w3.org/2001/XMLSchema#long"/>
-    </columns>
-    <columns xmi:uuid="mmuuid:54267915-2eb5-4291-8ca0-0e2f24eb4901" name="LegID" nativeType="Long">
-      <type href="http://www.w3.org/2001/XMLSchema#long"/>
-    </columns>
-    <columns xmi:uuid="mmuuid:e8356ebb-6ee7-49ef-bb21-a713fc692ff5" name="Notational" nativeType="Double">
-      <type href="http://www.w3.org/2001/XMLSchema#double"/>
-    </columns>
-  </relational:BaseTable>
-</xmi:XMI>

Copied: branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi (from rev 3382, trunk/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi)
===================================================================
--- branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi	                        (rev 0)
+++ branches/as7/connectors/sandbox/coherence_translator/src/test/resources/Coherence.xmi	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="ASCII"?>
+<xmi:XMI xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:diagram="http://www.metamatrix.com/metamodels/Diagram" xmlns:mmcore="http://www.metamatrix.com/metamodels/Core" xmlns:relational="http://www.metamatrix.com/metamodels/Relational">
+  <mmcore:ModelAnnotation xmi:uuid="mmuuid:f415b6fc-e09b-466a-b19b-f7bdfea4195f" primaryMetamodelUri="http://www.metamatrix.com/metamodels/Relational" modelType="PHYSICAL" ProducerName="Teiid Designer" ProducerVersion="7.1.0.v20110215-1224-H420-GA">
+    <modelImports xmi:uuid="mmuuid:c704e924-4d3e-46c1-ab88-d9811254770a" name="XMLSchema" modelLocation="http://www.w3.org/2001/XMLSchema" modelType="TYPE" primaryMetamodelUri="http://www.eclipse.org/xsd/2002/XSD"/>
+  </mmcore:ModelAnnotation>
+  <diagram:DiagramContainer xmi:uuid="mmuuid:edd4ddef-d373-4aeb-8cf8-212cdd21c3f2">
+    <diagram xmi:uuid="mmuuid:7f6fce9d-a334-4260-9a3a-33f397b9f188" type="packageDiagramType" target="mmuuid/f415b6fc-e09b-466a-b19b-f7bdfea4195f">
+      <diagramEntity xmi:uuid="mmuuid:56b9d09d-2135-4f2f-b19d-eb2925dc1192" name="Trade" modelObject="mmuuid/be73e0b2-9cf2-4d65-a26a-b8fa0892c191" xPosition="20" yPosition="20"/>
+    </diagram>
+  </diagram:DiagramContainer>
+  <mmcore:AnnotationContainer xmi:uuid="mmuuid:7de5077c-41da-4353-b854-d97d63fb5a2c"/>
+  <relational:BaseTable xmi:uuid="mmuuid:be73e0b2-9cf2-4d65-a26a-b8fa0892c191" name="Trade">
+    <columns xmi:uuid="mmuuid:6daf8dc7-6d1b-4564-98dd-3ab2a7f2c0dd" name="TradeID" nativeType="Long">
+      <type href="http://www.w3.org/2001/XMLSchema#long"/>
+    </columns>
+    <columns xmi:uuid="mmuuid:54267915-2eb5-4291-8ca0-0e2f24eb4901" name="LegID" nativeType="Long">
+      <type href="http://www.w3.org/2001/XMLSchema#long"/>
+    </columns>
+    <columns xmi:uuid="mmuuid:e8356ebb-6ee7-49ef-bb21-a713fc692ff5" name="Notational" nativeType="Double">
+      <type href="http://www.w3.org/2001/XMLSchema#double"/>
+    </columns>
+  </relational:BaseTable>
+</xmi:XMI>

Modified: branches/as7/connectors/sandbox/pom.xml
===================================================================
--- branches/as7/connectors/sandbox/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/sandbox/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
   <parent>
     <artifactId>connectors</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.jboss.teiid.connectors</groupId>

Modified: branches/as7/connectors/sandbox/translator-yahoo/pom.xml
===================================================================
--- branches/as7/connectors/sandbox/translator-yahoo/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/sandbox/translator-yahoo/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>sandbox</artifactId>
         <groupId>org.jboss.teiid.connectors</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>translator-yahoo</artifactId>

Modified: branches/as7/connectors/translator-file/pom.xml
===================================================================
--- branches/as7/connectors/translator-file/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-file/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>translator-file</artifactId>

Modified: branches/as7/connectors/translator-file/src/main/java/org/teiid/translator/file/FileExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-file/src/main/java/org/teiid/translator/file/FileExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-file/src/main/java/org/teiid/translator/file/FileExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,6 +34,7 @@
 import java.util.Collections;
 import java.util.List;
 
+import javax.resource.ResourceException;
 import javax.resource.cci.ConnectionFactory;
 
 import org.teiid.core.BundleUtil;
@@ -46,6 +47,8 @@
 import org.teiid.core.util.ObjectConverterUtil;
 import org.teiid.core.util.ReaderInputStream;
 import org.teiid.language.Call;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
 import org.teiid.metadata.MetadataFactory;
 import org.teiid.metadata.Procedure;
 import org.teiid.metadata.ProcedureParameter;
@@ -78,7 +81,16 @@
 
 		@Override
 		public void execute() throws TranslatorException {
-			files = FileConnection.Util.getFiles((String)command.getArguments().get(0).getArgumentValue().getValue(), fc);
+			String path = (String)command.getArguments().get(0).getArgumentValue().getValue();
+			try {
+				files = FileConnection.Util.getFiles(path, fc);
+			} catch (ResourceException e) {
+				throw new TranslatorException(e);
+			}
+			if (files == null && exceptionIfFileNotFound) {
+				throw new TranslatorException(UTIL.getString("file_not_found", path)); //$NON-NLS-1$
+			}
+			LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Getting", files != null ? files.length : 0, "file(s)"); //$NON-NLS-1$ //$NON-NLS-2$
 			String name = command.getProcedureName();
 			if (name.equalsIgnoreCase(GETTEXTFILES)) {
 				isText = true;
@@ -104,6 +116,7 @@
 			}
 			ArrayList<Object> result = new ArrayList<Object>(2);
 			final File file = files[index++];
+			LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Getting", file); //$NON-NLS-1$
 			FileInputStreamFactory isf = new FileInputStreamFactory(file);
 			isf.setLength(file.length());
 			Object value = null;
@@ -132,6 +145,7 @@
 	public static final String SAVEFILE = "saveFile"; //$NON-NLS-1$
 	
 	private Charset encoding = Charset.defaultCharset();
+	private boolean exceptionIfFileNotFound;
 	
 	@TranslatorProperty(display="File Encoding",advanced=true)
 	public String getEncoding() {
@@ -142,6 +156,15 @@
 		this.encoding = Charset.forName(encoding);
 	}
 	
+	@TranslatorProperty(display="Exception if file not found",advanced=true)
+	public boolean isExceptionIfFileNotFound() {
+		return exceptionIfFileNotFound;
+	}
+	
+	public void setExceptionIfFileNotFound(boolean exceptionIfFileNotFound) {
+		this.exceptionIfFileNotFound = exceptionIfFileNotFound;
+	}
+	
 	//@Override
 	public ProcedureExecution createProcedureExecution(final Call command,
 			final ExecutionContext executionContext, final RuntimeMetadata metadata,
@@ -156,6 +179,7 @@
 					if (file == null || filePath == null) {
 						throw new TranslatorException(UTIL.getString("non_null")); //$NON-NLS-1$
 					}
+					LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Saving", filePath); //$NON-NLS-1$
 					InputStream is = null;
 					try {
 						if (file instanceof SQLXML) {
@@ -173,6 +197,8 @@
 						throw new TranslatorException(e, UTIL.getString("error_writing")); //$NON-NLS-1$
 					} catch (SQLException e) {
 						throw new TranslatorException(e, UTIL.getString("error_writing")); //$NON-NLS-1$
+					} catch (ResourceException e) {
+						throw new TranslatorException(e, UTIL.getString("error_writing")); //$NON-NLS-1$
 					}
 				}
 				
@@ -201,24 +227,24 @@
 	@Override
 	public void getMetadata(MetadataFactory metadataFactory, FileConnection connection) throws TranslatorException {
 		Procedure p = metadataFactory.addProcedure(GETTEXTFILES);
-		p.setAnnotation("Returns text files that match the given path and pattern as CLOBs");
+		p.setAnnotation("Returns text files that match the given path and pattern as CLOBs"); //$NON-NLS-1$
 		ProcedureParameter param = metadataFactory.addProcedureParameter("pathAndPattern", TypeFacility.RUNTIME_NAMES.STRING, Type.In, p); //$NON-NLS-1$
-		param.setAnnotation("The path and pattern of what files to return.  Currently the only pattern supported is *.<ext>, which returns only the files matching the given extension at the given path.");
+		param.setAnnotation("The path and pattern of what files to return.  Currently the only pattern supported is *.<ext>, which returns only the files matching the given extension at the given path."); //$NON-NLS-1$
 		metadataFactory.addProcedureResultSetColumn("file", TypeFacility.RUNTIME_NAMES.CLOB, p); //$NON-NLS-1$
 		metadataFactory.addProcedureResultSetColumn("filePath", TypeFacility.RUNTIME_NAMES.STRING, p); //$NON-NLS-1$
 		
 		Procedure p1 = metadataFactory.addProcedure(GETFILES);
-		p1.setAnnotation("Returns text files that match the given path and pattern as BLOBs");
+		p1.setAnnotation("Returns text files that match the given path and pattern as BLOBs"); //$NON-NLS-1$
 		param = metadataFactory.addProcedureParameter("pathAndPattern", TypeFacility.RUNTIME_NAMES.STRING, Type.In, p1); //$NON-NLS-1$
-		param.setAnnotation("The path and pattern of what files to return.  Currently the only pattern supported is *.<ext>, which returns only the files matching the given extension at the given path.");
+		param.setAnnotation("The path and pattern of what files to return.  Currently the only pattern supported is *.<ext>, which returns only the files matching the given extension at the given path."); //$NON-NLS-1$
 		metadataFactory.addProcedureResultSetColumn("file", TypeFacility.RUNTIME_NAMES.BLOB, p1); //$NON-NLS-1$
 		metadataFactory.addProcedureResultSetColumn("filePath", TypeFacility.RUNTIME_NAMES.STRING, p1); //$NON-NLS-1$
 		
 		Procedure p2 = metadataFactory.addProcedure(SAVEFILE);
-		p2.setAnnotation("Saves the given vale to the given path.  Any existing file will be overriden.");
+		p2.setAnnotation("Saves the given vale to the given path.  Any existing file will be overriden."); //$NON-NLS-1$
 		metadataFactory.addProcedureParameter("filePath", TypeFacility.RUNTIME_NAMES.STRING, Type.In, p2); //$NON-NLS-1$
 		param = metadataFactory.addProcedureParameter("file", TypeFacility.RUNTIME_NAMES.OBJECT, Type.In, p2); //$NON-NLS-1$
-		param.setAnnotation("The contents to save.  Can be one of CLOB, BLOB, or XML");
+		param.setAnnotation("The contents to save.  Can be one of CLOB, BLOB, or XML"); //$NON-NLS-1$
 	} 
 	
 	@Override

Modified: branches/as7/connectors/translator-file/src/main/resources/org/teiid/translator/file/i18n.properties
===================================================================
--- branches/as7/connectors/translator-file/src/main/resources/org/teiid/translator/file/i18n.properties	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-file/src/main/resources/org/teiid/translator/file/i18n.properties	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,4 +22,5 @@
 
 non_null=Expected non-null values for filePath and file
 unknown_type=Unknown type for file, was expecting an XML, CLOB, or BLOB value
-error_writing=Error writing file
\ No newline at end of file
+error_writing=Error writing file
+file_not_found=File not found {0}
\ No newline at end of file

Modified: branches/as7/connectors/translator-jdbc/pom.xml
===================================================================
--- branches/as7/connectors/translator-jdbc/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
   <parent>
     <artifactId>connectors</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>translator-jdbc</artifactId>


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/AliasModifier.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/EscapeSyntaxModifier.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/FunctionModifier.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCBaseExecution.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,6 +41,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.TimeZone;
+import java.util.TreeMap;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import javax.sql.DataSource;
@@ -56,6 +57,7 @@
 import org.teiid.language.Limit;
 import org.teiid.language.Literal;
 import org.teiid.language.QueryExpression;
+import org.teiid.language.SQLConstants;
 import org.teiid.language.SetQuery;
 import org.teiid.language.Argument.Direction;
 import org.teiid.language.SetQuery.Operation;
@@ -144,7 +146,7 @@
     	}
     };
     
-    private Map<String, FunctionModifier> functionModifiers = new HashMap<String, FunctionModifier>();
+    private Map<String, FunctionModifier> functionModifiers = new TreeMap<String, FunctionModifier>(String.CASE_INSENSITIVE_ORDER);
 	
 	private boolean useBindVariables = true;
 	private String databaseTimeZone;
@@ -511,9 +513,18 @@
     	if (obj instanceof Function) {
     		Function function = (Function)obj;
     		if (functionModifiers != null) {
-    			FunctionModifier modifier = functionModifiers.get(function.getName().toLowerCase());
-    			if (modifier != null) {
-    				parts = modifier.translate(function);
+    			String name = function.getName();
+    			while (true) {
+	    			FunctionModifier modifier = functionModifiers.get(name);
+	    			if (modifier != null) {
+	    				parts = modifier.translate(function);
+	    				break;
+	    			}
+	    			int index = name.indexOf('.');
+	    			if (index < 0 || index == name.length() - 1) {
+	    				break;
+	    			}
+    				name = name.substring(index + 1);
     			}
     		}
     	} else if (obj instanceof Command) {
@@ -553,7 +564,7 @@
     }
     
     /**
-     * Return a map of function name in lower case to FunctionModifier.
+     * Return a map of function name to FunctionModifier.
      * @return Map of function name to FunctionModifier.
      */
     public Map<String, FunctionModifier> getFunctionModifiers() {
@@ -566,7 +577,7 @@
      * @param modifier
      */
     public void registerFunctionModifier(String name, FunctionModifier modifier) {
-    	this.functionModifiers.put(name.toLowerCase(), modifier);
+    	this.functionModifiers.put(name, modifier);
     }
     
     /**
@@ -1137,5 +1148,9 @@
         }
         return nameParts;
 	}
+
+	public String getLikeRegexString() {
+		return SQLConstants.Reserved.LIKE_REGEX;
+	}
 	
 }


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCExecutionFactory.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCMetdataProcessor.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCMetdataProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCMetdataProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -85,6 +85,7 @@
 	private boolean widenUnsingedTypes = true;
 	private boolean quoteNameInSource = true;
 	private boolean useProcedureSpecificName;
+	private boolean useCatalogName = true;
 	
 	private Set<String> unsignedTypes = new HashSet<String>();
 	private String quoteString;
@@ -422,14 +423,12 @@
 		if (schemaName != null && schemaName.length() > 0) {
 			fullName = (quoted?quoteName(schemaName):schemaName) + AbstractMetadataRecord.NAME_DELIM_CHAR + fullName;
 		}
-		if (catalogName != null && catalogName.length() > 0) {
+		if (useCatalogName && catalogName != null && catalogName.length() > 0) {
 			fullName = (quoted?quoteName(catalogName):catalogName) + AbstractMetadataRecord.NAME_DELIM_CHAR + fullName;
 		}
 		return fullName;
 	}
-		
 
-
 	public void setTableNamePattern(String tableNamePattern) {
 		this.tableNamePattern = tableNamePattern;
 	}
@@ -483,4 +482,8 @@
 		this.useProcedureSpecificName = useProcedureSpecificName;
 	}
 	
+	public void setUseCatalogName(boolean useCatalog) {
+		this.useCatalogName = useCatalog;
+	}
+	
 }


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCPlugin.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCProcedureExecution.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCQueryExecution.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/JDBCUpdateExecution.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ModFunctionModifier.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -350,4 +350,9 @@
 		return executionFactory.useSelectLimit();
 	}
 	
+	@Override
+	protected String getLikeRegexString() {
+		return executionFactory.getLikeRegexString();
+	}
+	
 }


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SQLConversionVisitor.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/SimpleJDBCExecutionFactory.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/TranslatedCommand.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Copied: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/BaseDB2ExecutionFactory.java (from rev 3382, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/BaseDB2ExecutionFactory.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/BaseDB2ExecutionFactory.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/BaseDB2ExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,176 @@
+/*
+ * 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 org.teiid.translator.jdbc.db2;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.language.DerivedColumn;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.Join;
+import org.teiid.language.LanguageFactory;
+import org.teiid.language.LanguageObject;
+import org.teiid.language.Limit;
+import org.teiid.language.Literal;
+import org.teiid.language.Comparison.Operator;
+import org.teiid.language.Join.JoinType;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.SourceSystemFunctions;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+import org.teiid.translator.jdbc.ModFunctionModifier;
+
+public class BaseDB2ExecutionFactory extends JDBCExecutionFactory {
+
+	private final class NullHandlingFormatModifier extends
+			ConvertModifier.FormatModifier {
+		private NullHandlingFormatModifier(String alias) {
+			super(alias);
+		}
+
+		@Override
+		public List<?> translate(Function function) {
+			Expression arg = function.getParameters().get(0);
+			if (arg instanceof Literal && ((Literal)arg).getValue() == null) {
+				((Literal)function.getParameters().get(1)).setValue(this.alias);
+				return null;
+			}
+			return super.translate(function);
+		}
+	}
+
+	@Override
+	public void start() throws TranslatorException {
+		super.start();
+        registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr")); //$NON-NLS-1$ 
+        registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new AliasModifier("day")); //$NON-NLS-1$ 
+        registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("coalesce")); //$NON-NLS-1$ 
+        registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory()));
+        registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new SubstringFunctionModifier());  
+
+        registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier("MOD", getLanguageFactory()));  //$NON-NLS-1$
+        
+        //add in type conversion
+        ConvertModifier convertModifier = new ConvertModifier();
+    	convertModifier.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
+    	convertModifier.addTypeMapping("numeric(31,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
+    	convertModifier.addTypeMapping("numeric(31,12)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
+    	convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
+    	convertModifier.addTypeMapping("blob", FunctionModifier.BLOB, FunctionModifier.OBJECT); //$NON-NLS-1$
+    	convertModifier.addTypeMapping("clob", FunctionModifier.CLOB, FunctionModifier.XML); //$NON-NLS-1$
+    	convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("timestamp('1970-01-01', ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		});
+    	convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("timestamp(",function.getParameters().get(0), ", '00:00:00')"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		});
+    	//the next convert is not strictly necessary for db2, but it also works for derby
+    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("cast(double(", function.getParameters().get(0), ") as real)"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		});
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("char"), FunctionModifier.STRING); //$NON-NLS-1$
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("smallint"), FunctionModifier.BYTE, FunctionModifier.SHORT); //$NON-NLS-1$
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("integer"), FunctionModifier.INTEGER); //$NON-NLS-1$
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("bigint"), FunctionModifier.LONG); //$NON-NLS-1$
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("double"), FunctionModifier.DOUBLE); //$NON-NLS-1$
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("date"), FunctionModifier.DATE); //$NON-NLS-1$
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("time"), FunctionModifier.TIME); //$NON-NLS-1$
+    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("timestamp"), FunctionModifier.TIMESTAMP); //$NON-NLS-1$
+    	convertModifier.addNumericBooleanConversions();
+    	registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+    }
+		
+	@SuppressWarnings("unchecked")
+	@Override
+	public List<?> translateLimit(Limit limit, ExecutionContext context) {
+		return Arrays.asList("FETCH FIRST ", limit.getRowLimit(), " ROWS ONLY"); //$NON-NLS-1$ //$NON-NLS-2$ 
+	}
+	
+	@Override
+	public List<?> translate(LanguageObject obj, ExecutionContext context) {
+		//DB2 doesn't support cross join
+		convertCrossJoinToInner(obj, getLanguageFactory());
+		//DB2 needs projected nulls wrapped in casts
+		if (obj instanceof DerivedColumn) {
+			DerivedColumn selectSymbol = (DerivedColumn)obj;
+			if (selectSymbol.getExpression() instanceof Literal) {
+				Literal literal = (Literal)selectSymbol.getExpression();
+				if (literal.getValue() == null) {
+					String type = TypeFacility.RUNTIME_NAMES.INTEGER;
+					if (literal.getType() != TypeFacility.RUNTIME_TYPES.NULL) {
+						type = TypeFacility.getDataTypeName(literal.getType());
+					}
+					selectSymbol.setExpression(ConvertModifier.createConvertFunction(getLanguageFactory(), literal, type));
+				}
+			}
+		}
+		return super.translate(obj, context);
+	}
+
+	public static void convertCrossJoinToInner(LanguageObject obj, LanguageFactory lf) {
+		if (obj instanceof Join) {
+			Join join = (Join)obj;
+			if (join.getJoinType() == JoinType.CROSS_JOIN) {
+				Literal one = lf.createLiteral(1, TypeFacility.RUNTIME_TYPES.INTEGER);
+				join.setCondition(lf.createCompareCriteria(Operator.EQ, one, one));
+				join.setJoinType(JoinType.INNER_JOIN);
+			}
+		}
+	}
+	
+	@Override
+	public NullOrder getDefaultNullOrder() {
+		return NullOrder.HIGH;
+	}
+	
+	@Override
+	public boolean supportsInlineViews() {
+		return true;
+	}
+
+	@Override
+	public boolean supportsExcept() {
+		return true;
+	}
+
+	@Override
+	public boolean supportsIntersect() {
+		return true;
+	}
+	
+}

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2ExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2ExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/db2/DB2ExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,139 +26,22 @@
 import java.util.Arrays;
 import java.util.List;
 
-import org.teiid.language.DerivedColumn;
 import org.teiid.language.Expression;
 import org.teiid.language.Function;
-import org.teiid.language.Join;
-import org.teiid.language.LanguageFactory;
-import org.teiid.language.LanguageObject;
-import org.teiid.language.Limit;
 import org.teiid.language.Literal;
-import org.teiid.language.Comparison.Operator;
-import org.teiid.language.Join.JoinType;
-import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
 import org.teiid.translator.TranslatorException;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.AliasModifier;
-import org.teiid.translator.jdbc.ConvertModifier;
 import org.teiid.translator.jdbc.FunctionModifier;
-import org.teiid.translator.jdbc.JDBCExecutionFactory;
-import org.teiid.translator.jdbc.LocateFunctionModifier;
-import org.teiid.translator.jdbc.ModFunctionModifier;
 
 @Translator(name="db2", description="A translator for IBM DB2 Database")
-public class DB2ExecutionFactory extends JDBCExecutionFactory {
-
-	private final class NullHandlingFormatModifier extends
-			ConvertModifier.FormatModifier {
-		private NullHandlingFormatModifier(String alias) {
-			super(alias);
-		}
-
-		@Override
-		public List<?> translate(Function function) {
-			Expression arg = function.getParameters().get(0);
-			if (arg instanceof Literal && ((Literal)arg).getValue() == null) {
-				((Literal)function.getParameters().get(1)).setValue(this.alias);
-				return null;
-			}
-			return super.translate(function);
-		}
-	}
-
-	@Override
-	public void start() throws TranslatorException {
-		super.start();
-        registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr")); //$NON-NLS-1$ 
-        registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new AliasModifier("day")); //$NON-NLS-1$ 
-        registerFunctionModifier(SourceSystemFunctions.IFNULL, new AliasModifier("coalesce")); //$NON-NLS-1$ 
-        registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory()));
-        registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new SubstringFunctionModifier());  
-
-        registerFunctionModifier(SourceSystemFunctions.MOD, new ModFunctionModifier("MOD", getLanguageFactory()));  //$NON-NLS-1$
-        
-        //add in type conversion
-        ConvertModifier convertModifier = new ConvertModifier();
-    	convertModifier.addTypeMapping("real", FunctionModifier.FLOAT); //$NON-NLS-1$
-    	convertModifier.addTypeMapping("numeric(31,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
-    	convertModifier.addTypeMapping("numeric(31,12)", FunctionModifier.BIGDECIMAL); //$NON-NLS-1$
-    	convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
-    	convertModifier.addTypeMapping("blob", FunctionModifier.BLOB, FunctionModifier.OBJECT); //$NON-NLS-1$
-    	convertModifier.addTypeMapping("clob", FunctionModifier.CLOB, FunctionModifier.XML); //$NON-NLS-1$
-    	convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new FunctionModifier() {
-			@Override
-			public List<?> translate(Function function) {
-				return Arrays.asList("timestamp('1970-01-01', ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
-			}
-		});
-    	convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP, new FunctionModifier() {
-			@Override
-			public List<?> translate(Function function) {
-				return Arrays.asList("timestamp(",function.getParameters().get(0), ", '00:00:00')"); //$NON-NLS-1$ //$NON-NLS-2$
-			}
-		});
-    	//the next convert is not strictly necessary for db2, but it also works for derby
-    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new FunctionModifier() {
-			@Override
-			public List<?> translate(Function function) {
-				return Arrays.asList("cast(double(", function.getParameters().get(0), ") as real)"); //$NON-NLS-1$ //$NON-NLS-2$
-			}
-		});
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("char"), FunctionModifier.STRING); //$NON-NLS-1$
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("smallint"), FunctionModifier.BYTE, FunctionModifier.SHORT); //$NON-NLS-1$
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("integer"), FunctionModifier.INTEGER); //$NON-NLS-1$
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("bigint"), FunctionModifier.LONG); //$NON-NLS-1$
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("double"), FunctionModifier.DOUBLE); //$NON-NLS-1$
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("date"), FunctionModifier.DATE); //$NON-NLS-1$
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("time"), FunctionModifier.TIME); //$NON-NLS-1$
-    	convertModifier.addTypeConversion(new NullHandlingFormatModifier("timestamp"), FunctionModifier.TIMESTAMP); //$NON-NLS-1$
-    	convertModifier.addNumericBooleanConversions();
-    	registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
-    }
-		
-	@SuppressWarnings("unchecked")
-	@Override
-	public List<?> translateLimit(Limit limit, ExecutionContext context) {
-		return Arrays.asList("FETCH FIRST ", limit.getRowLimit(), " ROWS ONLY"); //$NON-NLS-1$ //$NON-NLS-2$ 
-	}
+public class DB2ExecutionFactory extends BaseDB2ExecutionFactory {
 	
-	@Override
-	public List<?> translate(LanguageObject obj, ExecutionContext context) {
-		//DB2 doesn't support cross join
-		convertCrossJoinToInner(obj, getLanguageFactory());
-		//DB2 needs projected nulls wrapped in casts
-		if (obj instanceof DerivedColumn) {
-			DerivedColumn selectSymbol = (DerivedColumn)obj;
-			if (selectSymbol.getExpression() instanceof Literal) {
-				Literal literal = (Literal)selectSymbol.getExpression();
-				if (literal.getValue() == null) {
-					String type = TypeFacility.RUNTIME_NAMES.INTEGER;
-					if (literal.getType() != TypeFacility.RUNTIME_TYPES.NULL) {
-						type = TypeFacility.getDataTypeName(literal.getType());
-					}
-					selectSymbol.setExpression(ConvertModifier.createConvertFunction(getLanguageFactory(), literal, type));
-				}
-			}
-		}
-		return super.translate(obj, context);
-	}
-
-	public static void convertCrossJoinToInner(LanguageObject obj, LanguageFactory lf) {
-		if (obj instanceof Join) {
-			Join join = (Join)obj;
-			if (join.getJoinType() == JoinType.CROSS_JOIN) {
-				Literal one = lf.createLiteral(1, TypeFacility.RUNTIME_TYPES.INTEGER);
-				join.setCondition(lf.createCompareCriteria(Operator.EQ, one, one));
-				join.setJoinType(JoinType.INNER_JOIN);
-			}
-		}
-	}
+	public static final String EIGHT_0 = "8.0"; //$NON-NLS-1$
+	public static final String NINE_1 = "9.1"; //$NON-NLS-1$
 	
-	@Override
-	public NullOrder getDefaultNullOrder() {
-		return NullOrder.HIGH;
+	public DB2ExecutionFactory() {
+		setDatabaseVersion(EIGHT_0);
 	}
 	
 	@Override
@@ -204,6 +87,7 @@
 		supportedFunctions.add("RIGHT"); //$NON-NLS-1$
 		supportedFunctions.add("RTRIM"); //$NON-NLS-1$
 		supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+		supportedFunctions.add(SourceSystemFunctions.TRIM);
 		//supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
 		supportedFunctions.add("UCASE"); //$NON-NLS-1$
 		supportedFunctions.add("UPPER"); //$NON-NLS-1$
@@ -228,39 +112,43 @@
 		supportedFunctions.add("COALESCE"); //$NON-NLS-1$
 		return supportedFunctions;
 	}
-
+
 	@Override
-	public boolean supportsInlineViews() {
-		return true;
-	}
-
-	@Override
 	public boolean supportsFunctionsInGroupBy() {
 		return true;
 	}
 
 	@Override
-	public boolean supportsRowLimit() {
+	public boolean supportsAggregatesEnhancedNumeric() {
 		return true;
 	}
-
+	
 	@Override
-	public boolean supportsExcept() {
+	public boolean supportsCommonTableExpressions() {
 		return true;
 	}
-
+	
 	@Override
-	public boolean supportsIntersect() {
+	public boolean supportsRowLimit() {
 		return true;
 	}
 	
 	@Override
-	public boolean supportsAggregatesEnhancedNumeric() {
-		return true;
+	public boolean supportsElementaryOlapOperations() {
+		return getDatabaseVersion().compareTo(NINE_1) >= 0;
 	}
 	
 	@Override
-	public boolean supportsCommonTableExpressions() {
-		return true;
-	}
+	public void start() throws TranslatorException {
+		super.start();
+		registerFunctionModifier(SourceSystemFunctions.TRIM, new FunctionModifier() {
+			
+			@Override
+			public List<?> translate(Function function) {
+				List<Expression> p = function.getParameters();
+				return Arrays.asList("STRIP(", p.get(2), ", ", ((Literal)p.get(0)).getValue(), ", ", p.get(1), ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			}
+		});
+	}
+	
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/derby/DerbyExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,17 +29,18 @@
 import org.teiid.translator.Translator;
 import org.teiid.translator.TranslatorException;
 import org.teiid.translator.jdbc.EscapeSyntaxModifier;
-import org.teiid.translator.jdbc.db2.DB2ExecutionFactory;
+import org.teiid.translator.jdbc.db2.BaseDB2ExecutionFactory;
 import org.teiid.translator.jdbc.oracle.LeftOrRightFunctionModifier;
 
 /** 
  * @since 4.3
  */
 @Translator(name="derby", description="A translator for Apache Derby Database")
-public class DerbyExecutionFactory extends DB2ExecutionFactory {
+public class DerbyExecutionFactory extends BaseDB2ExecutionFactory {
 	
 	public static final String TEN_1 = "10.1"; //$NON-NLS-1$
 	public static final String TEN_2 = "10.2"; //$NON-NLS-1$
+	public static final String TEN_3 = "10.3"; //$NON-NLS-1$
 	public static final String TEN_4 = "10.4"; //$NON-NLS-1$
 	public static final String TEN_5 = "10.5"; //$NON-NLS-1$
 	
@@ -130,6 +131,9 @@
         //supportedFunctions.add("RPAD"); //$NON-NLS-1$
         supportedFunctions.add("RTRIM"); //$NON-NLS-1$
         supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+        if (getDatabaseVersion().compareTo(TEN_3) >= 0) {
+        	supportedFunctions.add(SourceSystemFunctions.TRIM);
+        }
         supportedFunctions.add("UCASE"); //$NON-NLS-1$
         
         // These are executed within the server and never pushed down
@@ -181,8 +185,4 @@
     	return this.getDatabaseVersion().compareTo(TEN_5) >= 0;
     }
     
-	@Override
-	public boolean supportsFunctionsInGroupBy() {
-		return false;
-	}
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/h2/H2ExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,9 +28,9 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
 import org.teiid.translator.TranslatorException;
-import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.jdbc.AliasModifier;
 import org.teiid.translator.jdbc.ConvertModifier;
 import org.teiid.translator.jdbc.FunctionModifier;
@@ -139,6 +139,7 @@
         supportedFunctions.add(SourceSystemFunctions.RPAD);
         supportedFunctions.add(SourceSystemFunctions.RTRIM);
         supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
+        supportedFunctions.add(SourceSystemFunctions.TRIM);
         supportedFunctions.add(SourceSystemFunctions.UCASE);
         supportedFunctions.add(SourceSystemFunctions.UNESCAPE);
         
@@ -199,4 +200,14 @@
     public boolean supportsAggregatesEnhancedNumeric() {
     	return true;
     }
+    
+    @Override
+    public boolean supportsLikeRegex() {
+    	return true;
+    }
+    
+    @Override
+    public String getLikeRegexString() {
+    	return "REGEXP"; //$NON-NLS-1$
+    }
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/hsql/HsqlExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,9 +28,9 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
 import org.teiid.translator.TranslatorException;
-import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.jdbc.ConvertModifier;
 import org.teiid.translator.jdbc.FunctionModifier;
 import org.teiid.translator.jdbc.JDBCExecutionFactory;
@@ -125,6 +125,7 @@
         supportedFunctions.add(SourceSystemFunctions.RPAD);
         supportedFunctions.add(SourceSystemFunctions.RTRIM);
         supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
+        supportedFunctions.add(SourceSystemFunctions.TRIM);
         supportedFunctions.add(SourceSystemFunctions.UCASE);
         
         supportedFunctions.add(SourceSystemFunctions.DAYNAME);

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/ingres/IngresExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,6 +21,8 @@
  */
 package org.teiid.translator.jdbc.ingres;
 
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
 import java.sql.Date;
 import java.sql.Time;
 import java.sql.Timestamp;
@@ -28,10 +30,7 @@
 import java.util.Arrays;
 import java.util.List;
 
-import org.teiid.core.types.DataTypeManager;
 import org.teiid.language.Limit;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
 import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
@@ -40,7 +39,6 @@
 import org.teiid.translator.jdbc.ConvertModifier;
 import org.teiid.translator.jdbc.FunctionModifier;
 import org.teiid.translator.jdbc.JDBCExecutionFactory;
-
 @Translator(name="ingres", description="A translator for Ingres Databases")
 public class IngresExecutionFactory extends JDBCExecutionFactory {
 	
@@ -78,7 +76,45 @@
         registerFunctionModifier(SourceSystemFunctions.RAND, new AliasModifier("random")); //$NON-NLS-1$
         registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("uppercase")); //$NON-NLS-1$
         registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new AliasModifier("day")); //$NON-NLS-1$
-        registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory())); 		
+        registerFunctionModifier(SourceSystemFunctions.LOCATE, new LocateFunctionModifier(getLanguageFactory())); 	
+        
+        addPushDownFunction(INGRES, "bit_add", INTEGER, INTEGER, INTEGER); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "bit_length", INTEGER, INTEGER); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "character_length", STRING, INTEGER); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "charextract", CHAR, STRING, INTEGER); //$NON-NLS-1$
+
+			// uses ingres date??
+			//supportedFunctions.add("date_trunc");		
+			//supportedFunctions.add("dow");		
+			//supportedFunctions.add("extract");
+        addPushDownFunction(INGRES, "gmt_timestamp", STRING, INTEGER); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "hash", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "hex", STRING, STRING); //$NON-NLS-1$
+
+        	// do not have byte[] type
+			//supportedFunctions.add("intextract");
+
+        addPushDownFunction(INGRES, "ln", DOUBLE, DOUBLE); //$NON-NLS-1$
+			
+			// see lowercase
+			// supportedFunctions.add("lower");
+			// supportedFunctions.add("upper");
+
+        addPushDownFunction(INGRES, "octet_length", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "randomf", FLOAT); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "session_user", STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "size", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "squeeze", STRING, STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "soundex", STRING, STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "unhex", STRING, STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "usercode", STRING); //$NON-NLS-1$
+        addPushDownFunction(INGRES, "username", STRING); //$NON-NLS-1$
+			// ignore
+			// supportedFunctions.add("uuid_create");
+			// supportedFunctions.add("uuid_compare");
+			// supportedFunctions.add("uuid_from_char");
+			// supportedFunctions.add("uuid_to_char");
+
 	}
 	
     @Override
@@ -123,122 +159,6 @@
     }
     
     @Override
-    public List<FunctionMethod> getPushDownFunctions(){
-    	List<FunctionMethod> pushdownFunctions = new ArrayList<FunctionMethod>();
-    
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "bit_add", "bit_add", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter[] {
-                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("integer2", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "bit_length", "bit_length", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    		
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "character_length", "character_length", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "charextract", "charextract", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-	                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.CHAR, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		// uses ingres date??
-		//supportedFunctions.add("date_trunc");		
-		//supportedFunctions.add("dow");		
-		//supportedFunctions.add("extract");
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "gmt_timestamp", "gmt_timestamp", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "hash", "hash", INGRES,//$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$				
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "hex", "hex", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    		
-
-		// do not have byte[] type
-		//supportedFunctions.add("intextract");
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "ln", "ln", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("float1", DataTypeManager.DefaultDataTypes.DOUBLE, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.DOUBLE, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		// see lowercase
-		// supportedFunctions.add("lower");
-		// supportedFunctions.add("upper");
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "octet_length", "octet_length", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "pad", "pad", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "pad", "pad", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-	                new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-	                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "randomf", "randomf", INGRES, null,//$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.FLOAT, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "session_user", "session_user", INGRES, null,//$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "size", "size", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "squeeze", "squeeze", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "soundex", "soundex", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "unhex", "unhex", INGRES, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    		
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "usercode", "usercode", INGRES, null,//$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-
-		pushdownFunctions.add(new FunctionMethod(INGRES + '.' + "username", "username", INGRES, null,//$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-		
-		// ignore
-		// supportedFunctions.add("uuid_create");
-		// supportedFunctions.add("uuid_compare");
-		// supportedFunctions.add("uuid_from_char");
-		// supportedFunctions.add("uuid_to_char");
-		
-    	return pushdownFunctions;
-    }
-
-    @Override
     public boolean supportsRowLimit() {
     	return true;
     }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/intersyscache/InterSystemsCacheExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,6 +21,8 @@
  */
 package org.teiid.translator.jdbc.intersyscache;
 
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
 import java.sql.Date;
 import java.sql.Time;
 import java.sql.Timestamp;
@@ -28,10 +30,7 @@
 import java.util.Arrays;
 import java.util.List;
 
-import org.teiid.core.types.DataTypeManager;
 import org.teiid.language.Function;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
 import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
 import org.teiid.translator.TranslatorException;
@@ -111,6 +110,18 @@
 				return null;
 			}
 		});
+        
+        addPushDownFunction(INTER_CACHE, "CHARACTER_LENGTH", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(INTER_CACHE, "CHAR_LENGTH", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(INTER_CACHE, "CHARINDEX", INTEGER, STRING, STRING); //$NON-NLS-1$
+        addPushDownFunction(INTER_CACHE, "CHARINDEX", INTEGER, STRING, STRING, INTEGER); //$NON-NLS-1$
+        addPushDownFunction(INTER_CACHE, "INSTR", INTEGER, STRING, STRING); //$NON-NLS-1$			
+        addPushDownFunction(INTER_CACHE, "INSTR", INTEGER, STRING, STRING, INTEGER); //$NON-NLS-1$
+        addPushDownFunction(INTER_CACHE, "IS_NUMERIC", INTEGER, STRING); //$NON-NLS-1$			
+        addPushDownFunction(INTER_CACHE, "REPLICATE", STRING, STRING, INTEGER); //$NON-NLS-1$					
+        addPushDownFunction(INTER_CACHE, "REVERSE", STRING, STRING); //$NON-NLS-1$			
+        addPushDownFunction(INTER_CACHE, "STUFF", STRING, STRING, STRING, INTEGER, STRING); //$NON-NLS-1$			
+        addPushDownFunction(INTER_CACHE, "TRIM", STRING, STRING); //$NON-NLS-1$			
 	}
 	
     @Override
@@ -179,80 +190,6 @@
     }
     
     @Override
-    public List<FunctionMethod> getPushDownFunctions(){
-    	        
-    	List<FunctionMethod> pushdownFunctions = new ArrayList<FunctionMethod>();
-    
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "CHARACTER_LENGTH", "CHARACTER_LENGTH", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "CHAR_LENGTH", "CHAR_LENGTH", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "CHARINDEX", "CHARINDEX", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "CHARINDEX", "CHARINDEX", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    		
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "INSTR", "INSTR", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "INSTR", "INSTR", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    		
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "IS_NUMERIC", "IS_NUMERIC", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-				
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "REPLICATE", "REPLICATE", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.INTEGER, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    		
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "REVERSE", "REVERSE", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "STUFF", "STUFF", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("integer1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("integer2", DataTypeManager.DefaultDataTypes.INTEGER, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("string2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  		
-		
-		pushdownFunctions.add(new FunctionMethod(INTER_CACHE + '.' + "TRIM", "TRIM", INTER_CACHE, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-    	return pushdownFunctions;
-    }
-
-    
-    @Override
     public String translateLiteralDate(Date dateValue) {
         return "to_date('" + formatDateValue(dateValue) + "', 'yyyy-mm-dd')"; //$NON-NLS-1$//$NON-NLS-2$
     }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/modeshape/ModeShapeExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,6 +22,8 @@
 
 package org.teiid.translator.jdbc.modeshape;
 
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
 import java.sql.Date;
 import java.sql.Time;
 import java.sql.Timestamp;
@@ -29,7 +31,6 @@
 import java.util.Arrays;
 import java.util.List;
 
-import org.teiid.core.types.DataTypeManager;
 import org.teiid.language.Comparison;
 import org.teiid.language.Function;
 import org.teiid.language.LanguageObject;
@@ -38,8 +39,6 @@
 import org.teiid.language.Comparison.Operator;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
 import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
@@ -47,7 +46,6 @@
 import org.teiid.translator.TypeFacility;
 import org.teiid.translator.jdbc.AliasModifier;
 import org.teiid.translator.jdbc.JDBCExecutionFactory;
-
 /** 
  * Translator class for accessing the ModeShape JCR repository.  
  */
@@ -79,6 +77,12 @@
 		registerFunctionModifier(JCR_REFERENCE, new IdentifierFunctionModifier()); 
 		registerFunctionModifier(JCR_CONTAINS, new IdentifierFunctionModifier());
 		
+		addPushDownFunction(JCR, JCR_ISCHILDNODE, BOOLEAN, STRING, STRING);
+		addPushDownFunction(JCR, JCR_ISDESCENDANTNODE, BOOLEAN, STRING, STRING);
+		addPushDownFunction(JCR, JCR_ISSAMENODE, BOOLEAN, STRING, STRING);
+		addPushDownFunction(JCR, JCR_CONTAINS, BOOLEAN, STRING, STRING);
+		addPushDownFunction(JCR, JCR_REFERENCE, BOOLEAN, STRING);
+		
     	LogManager.logTrace(LogConstants.CTX_CONNECTOR, "ModeShape Translator Started"); //$NON-NLS-1$
      }    
     
@@ -112,42 +116,7 @@
 		return supportedFunctions;
     }
     
-    
     @Override
-    public List<FunctionMethod> getPushDownFunctions(){
-    	List<FunctionMethod> pushdownFunctions = new ArrayList<FunctionMethod>();
-		pushdownFunctions.add(new FunctionMethod(JCR + '.' + JCR_ISCHILDNODE, JCR_ISCHILDNODE, JCR, 
-            new FunctionParameter[] {
-				new FunctionParameter("path1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("path2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(JCR + '.' + JCR_ISDESCENDANTNODE, JCR_ISDESCENDANTNODE, JCR, 
-                new FunctionParameter[] {
-				new FunctionParameter("path1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("path2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(JCR + '.' + JCR_ISSAMENODE, JCR_ISSAMENODE, JCR, 
-                new FunctionParameter[] {
-					new FunctionParameter("path1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("path2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(JCR + '.' + JCR_CONTAINS, JCR_CONTAINS, JCR, 
-                new FunctionParameter[] {
-                    new FunctionParameter("selectorOrProperty", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("searchExpr", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(JCR + '.' + JCR_REFERENCE, JCR_REFERENCE, JCR, 
-                new FunctionParameter[] {
-                    new FunctionParameter("selectorOrProperty", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    	return pushdownFunctions;    	
-    }    
-    
-    @Override
     public List<?> translate(LanguageObject obj, ExecutionContext context) {
     	if (obj instanceof Comparison) {
     		Comparison compare = (Comparison)obj;

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5ExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5ExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQL5ExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,9 +27,9 @@
 import java.util.List;
 
 import org.teiid.language.Function;
+import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
 import org.teiid.translator.TranslatorException;
-import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.jdbc.FunctionModifier;
 
 @Translator(name="mysql5", description="A translator for open source MySQL5 Database")
@@ -65,5 +65,15 @@
     public boolean supportsAggregatesEnhancedNumeric() {
     	return true;
     }
+    
+    @Override
+    public boolean supportsLikeRegex() {
+    	return true;
+    }
+    
+    @Override
+    public String getLikeRegexString() {
+    	return "REGEXP"; //$NON-NLS-1$
+    }
 	
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/mysql/MySQLExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -177,6 +177,7 @@
         supportedFunctions.add(SourceSystemFunctions.RPAD);
         supportedFunctions.add(SourceSystemFunctions.RTRIM);
         supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
+        supportedFunctions.add(SourceSystemFunctions.TRIM);
         supportedFunctions.add(SourceSystemFunctions.UCASE);
         
         // These are executed within the server and never pushed down

Deleted: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java
===================================================================
--- trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,382 +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 org.teiid.translator.jdbc.netezza;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.Limit;
-import org.teiid.translator.ExecutionContext;
-import org.teiid.translator.SourceSystemFunctions;
-import org.teiid.translator.Translator;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.jdbc.AliasModifier;
-import org.teiid.translator.jdbc.ConvertModifier;
-import org.teiid.translator.jdbc.ExtractFunctionModifier;
-import org.teiid.translator.jdbc.FunctionModifier;
-import org.teiid.translator.jdbc.JDBCExecutionFactory;
-import org.teiid.translator.jdbc.LocateFunctionModifier;
-
-
- at Translator(name = "netezza", description = "A translator for Netezza Database")
-public class NetezzaExecutionFactory extends JDBCExecutionFactory {
-
-	private static final String TIME_FORMAT = "HH24:MI:SS"; 
-	private static final String DATE_FORMAT = "YYYY-MM-DD"; 
-	private static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; 
-	private static final String TIMESTAMP_FORMAT = DATETIME_FORMAT + ".MS";  
-
-	public NetezzaExecutionFactory() {
-		setSupportsFullOuterJoins(true);
-		setSupportsOrderBy(true);
-		setSupportsOuterJoins(true);
-		setSupportsSelectDistinct(true);
-		setSupportsInnerJoins(true);
-	}
-
-	public void start() throws TranslatorException {
-		super.start();
-
-		//STRING FUNCTION MODIFIERS
-		////////////////////////////////////
-		registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr"));  
-		registerFunctionModifier(SourceSystemFunctions.LCASE,new AliasModifier("lower"));  
-		registerFunctionModifier(SourceSystemFunctions.UCASE,new AliasModifier("upper"));  
-		registerFunctionModifier(SourceSystemFunctions.LOCATE, new  LocateFunctionModifier(getLanguageFactory(), "INSTR", true));	  
-       	registerFunctionModifier(SourceSystemFunctions.CONCAT, new AliasModifier("||")); 
-		///NUMERIC FUNCTION MODIFIERS
-        ////////////////////////////////////
-		registerFunctionModifier(SourceSystemFunctions.CEILING,	new AliasModifier("ceil"));  
-		registerFunctionModifier(SourceSystemFunctions.POWER,	new AliasModifier("pow"));  
-		registerFunctionModifier(SourceSystemFunctions.LOG,	new AliasModifier("LN"));
-		///BIT FUNCTION MODIFIERS
-		////////////////////////////////////
-        registerFunctionModifier(SourceSystemFunctions.BITAND, new AliasModifier("intNand")); 
-        registerFunctionModifier(SourceSystemFunctions.BITNOT, new AliasModifier("intNnot")); 
-        registerFunctionModifier(SourceSystemFunctions.BITOR, new AliasModifier("intNor")); 
-        registerFunctionModifier(SourceSystemFunctions.BITXOR, new AliasModifier("intNxor")); 
-		//DATE FUNCTION MODIFIERS
-        //////////////////////////////////////////
-		 registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractFunctionModifier());
-		 registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new	ExtractModifier("DOY"));
-		 registerFunctionModifier(SourceSystemFunctions.QUARTER, new  ExtractFunctionModifier());
-		 registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractFunctionModifier());
-		 registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new  ExtractModifier("DAY"));
-		 registerFunctionModifier(SourceSystemFunctions.WEEK, new ExtractFunctionModifier());
-		 registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new  ExtractModifier("DOW"));
-         registerFunctionModifier(SourceSystemFunctions.HOUR, new	ExtractFunctionModifier());
-		 registerFunctionModifier(SourceSystemFunctions.MINUTE, new  ExtractFunctionModifier());
-		 registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractFunctionModifier());
-		 registerFunctionModifier(SourceSystemFunctions.CURDATE, new AliasModifier("CURRENT_DATE")); 
-		 registerFunctionModifier(SourceSystemFunctions.CURTIME, new AliasModifier("CURRENT_TIME")); 
-       //SYSTEM FUNCTIONS
-       ////////////////////////////////////
-		registerFunctionModifier(SourceSystemFunctions.IFNULL,new AliasModifier("NVL"));  
-        
-
-		// DATA TYPE CONVERSION
-		///////////////////////////////////////////
-		ConvertModifier convertModifier = new ConvertModifier();
-		convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); 
-		convertModifier.addTypeMapping("byteint", FunctionModifier.BYTE); 
-		convertModifier.addTypeMapping("smallint", FunctionModifier.SHORT); 
-		convertModifier.addTypeMapping("bigint", FunctionModifier.LONG); 
-    	convertModifier.addTypeMapping("numeric(38)", FunctionModifier.BIGINTEGER); 
-    	convertModifier.addTypeMapping("numeric(38,18)", FunctionModifier.BIGDECIMAL); 
-		convertModifier.addTypeMapping("varchar(4000)", FunctionModifier.STRING); 
-		//convertModifier.addTypeMapping("nvarchar(5)", FunctionModifier.BOOLEAN);
-
- 		///NO BOOLEAN, INTEGER, FLOAT, DATE, TIME, TIMESTAMP, as they are directly available in netezza
-		///NO NULL, CLOB, BLOB, OBJECT, XML
-		
-		
-		///BOOLEAN--BYTE, SHORT, INTEGER, LONG, FLOAT, DOUBLE, BIGINTEGER, BIGDECIMAL--AS IT DOESN'T WORK IMPLICITLY IN NETEZZA
-
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.INTEGER, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.BYTE, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.SHORT, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.LONG, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.FLOAT, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.DOUBLE, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.BIGINTEGER, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.BIGDECIMAL, new BooleanToNumericConversionModifier());
-		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.STRING, new BooleanToStringConversionModifier());
-    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.BOOLEAN, new FunctionModifier() {
-			@Override
-			public List<?> translate(Function function) {
-				Expression stringValue = function.getParameters().get(0);
-				return Arrays.asList("CASE WHEN ", stringValue, " IN ('false', '0') THEN '0' WHEN ", stringValue, " IS NOT NULL THEN '1' END"); 
-			}
-		});
-		convertModifier.addTypeConversion(new FunctionModifier() {
-			@Override
-			public List<?> translate(Function function) {
-				Expression stringValue = function.getParameters().get(0);
-				return Arrays.asList("CASE WHEN ", stringValue, " = 0 THEN '0' WHEN ", stringValue, " IS NOT NULL THEN '1' END"); 
-			}
-		}, FunctionModifier.BOOLEAN);
-		
-		
-		
-
-		////////STRING TO DATATYPE CONVERSION OTHER THAN DATE/TIME
-		convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.INTEGER, new CastModifier("integer")); 
-		convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new CastModifier("float"));
-    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DOUBLE, new CastModifier("double"));
-    	///// STRING --> CHAR, BYTE, SHORT, LONG, BIGI, BIGD, BOOLEAN is taken care by Type Mapping
-    	///// NO conversion support for NULL, CLOB, BLOB, OBJECT, XML
-		////STRING TO DATE/TIME CONVERSION////
-		//////////////////////////////////////
-    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DATE, new ConvertModifier.FormatModifier("to_date", DATE_FORMAT));  
-    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("to_timestamp", TIME_FORMAT));  
-    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("to_timestamp", TIMESTAMP_FORMAT));  
-		//////DATE/TIME INTERNAL CONVERSION/////////
-		convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new CastModifier("TIME")); 
-		convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE,  new CastModifier("DATE"));  
-		convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP,  new CastModifier("TIMESTAMP")); 
-		//convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new CastModifier("TIMESTAMP")); //TIME --> TIMESTAMP --DOESN't WORK IN NETEZZA-NO FUNCTION SUPPORT
-				
-		////DATE/TIME to STRING CONVERION////
-		/////////////////////////////////////
-    	convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", TIMESTAMP_FORMAT));
-    	///NO NETEZAA FUNCTION for DATE, TIME to STRING
-		
-
-		convertModifier.setWideningNumericImplicit(true);
-		registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
-	}
-
-	@Override
-	public List<String> getSupportedFunctions() {
-		List<String> supportedFunctions = new ArrayList<String>();
-		supportedFunctions.addAll(super.getSupportedFunctions());
-
-		////////////////////////////////////////////////////////////
-		//STRING FUNCTIONS
-		//////////////////////////////////////////////////////////
-		supportedFunctions.add(SourceSystemFunctions.ASCII);// taken care with alias function modifier
-		supportedFunctions.add(SourceSystemFunctions.CHAR);//ALIAS to use 'chr'
-		supportedFunctions.add(SourceSystemFunctions.CONCAT); // ALIAS ||
-		supportedFunctions.add(SourceSystemFunctions.INITCAP);
-		supportedFunctions.add(SourceSystemFunctions.LCASE);//ALIAS 'lower'
-		supportedFunctions.add(SourceSystemFunctions.LPAD);
-		supportedFunctions.add(SourceSystemFunctions.LENGTH);
-		supportedFunctions.add(SourceSystemFunctions.LOCATE); //LOCATE FUNCTIO MODIFIER
-		supportedFunctions.add(SourceSystemFunctions.LTRIM);
-		//supportedFunctions.add(SourceSystemFunctions.REPEAT);
-		supportedFunctions.add(SourceSystemFunctions.RPAD);
-		supportedFunctions.add(SourceSystemFunctions.RTRIM);
-		supportedFunctions.add(SourceSystemFunctions.SUBSTRING); //No Need of ALIAS as both substring and substr work in netezza
-		supportedFunctions.add(SourceSystemFunctions.UCASE); //ALIAS UPPER
-		// FUNCTION DIFFERENCE = "difference";  ///NO FUNCTION FOUND--DIFFERENCE 
-		//	FUNCTION INSERT = "insert"; 
-		// supportedFunctions.add(SourceSystemFunctions.LEFT); //is this available or is it simply for LEFT OUTER JOIN?
-		// FUNCTION REPLACE = "replace"; // NO REPLACE Function
-		// supportedFunctions.add(SourceSystemFunctions.RIGHT);--is this available or is it simply for RIGHT OUTER JOIN?
-		// FUNCTION SOUNDEX = "soundex";
-		//	FUNCTION TO_BYTES = "to_bytes"; 
-		//	FUNCTION TO_CHARS = "to_chars"; 
-		//////////	////////////////////////////////////////////////////////////////////
-		//NUMERIC FUNCTIONS////////////////////////////////////////////////////////////
-		//////////////////////////////////////////////////////////////////////////////
-		//supportedFunctions.add(SourceSystemFunctions.ABS);
-		supportedFunctions.add(SourceSystemFunctions.ACOS);
-		supportedFunctions.add(SourceSystemFunctions.ASIN);
-		supportedFunctions.add(SourceSystemFunctions.ATAN);
-		supportedFunctions.add(SourceSystemFunctions.ATAN2);
-		supportedFunctions.add(SourceSystemFunctions.CEILING);  ///ALIAS-ceil
-		supportedFunctions.add(SourceSystemFunctions.COS);
-		supportedFunctions.add(SourceSystemFunctions.COT);
-		supportedFunctions.add(SourceSystemFunctions.DEGREES);
-		//supportedFunctions.add(SourceSystemFunctions.EXP);
-		supportedFunctions.add(SourceSystemFunctions.FLOOR);
-		supportedFunctions.add(SourceSystemFunctions.LOG);
-		supportedFunctions.add(SourceSystemFunctions.MOD);
-		supportedFunctions.add(SourceSystemFunctions.PI);
-		supportedFunctions.add(SourceSystemFunctions.POWER);//	ALIAS-POW 
-		supportedFunctions.add(SourceSystemFunctions.RADIANS);
-		supportedFunctions.add(SourceSystemFunctions.ROUND);
-		supportedFunctions.add(SourceSystemFunctions.SIGN);	
-		supportedFunctions.add(SourceSystemFunctions.SIN);
-		supportedFunctions.add(SourceSystemFunctions.SQRT);
-		supportedFunctions.add(SourceSystemFunctions.TAN);
-		//		FUNCTION TRANSLATE = "translate"; 
-		//		FUNCTION TRUNCATE = "truncate"; 
-		//		FUNCTION FORMATINTEGER = "formatinteger"; 
-		//		FUNCTION FORMATLONG = "formatlong"; 
-		//		FUNCTION FORMATDOUBLE = "formatdouble"; 
-		//		FUNCTION FORMATFLOAT = "formatfloat"; 
-		//		FUNCTION FORMATBIGINTEGER = "formatbiginteger"; 
-		//		FUNCTION FORMATBIGDECIMAL = "formatbigdecimal"; 
-		//		FUNCTION LOG10 = "log10"; 
-		//		FUNCTION PARSEINTEGER = "parseinteger"; 
-		//		FUNCTION PARSELONG = "parselong"; 
-		//		FUNCTION PARSEDOUBLE = "parsedouble"; 
-		//		FUNCTION PARSEFLOAT = "parsefloat"; 
-		//		FUNCTION PARSEBIGINTEGER = "parsebiginteger"; 
-		//		FUNCTION PARSEBIGDECIMAL = "parsebigdecimal"; 
-		// supportedFunctions.add(SourceSystemFunctions.RAND); --Needs Alias--But, is it required to even have an alias???
-		/////////////////////////////////////////////////////////////////////
-		//BIT FUNCTIONS//////////////////////////////////////////////////////
-		//ALIAS FUNCTION MODIFIER IS APPLIED//////////////////////////////
-		supportedFunctions.add(SourceSystemFunctions.BITAND);
-		supportedFunctions.add(SourceSystemFunctions.BITOR);
-		supportedFunctions.add(SourceSystemFunctions.BITNOT);
-		supportedFunctions.add(SourceSystemFunctions.BITXOR);
-		// DATE FUNCTIONS
-		supportedFunctions.add(SourceSystemFunctions.CURDATE); 
-		supportedFunctions.add(SourceSystemFunctions.CURTIME); 
-		supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH); 
-		supportedFunctions.add(SourceSystemFunctions.DAYOFYEAR);
-		supportedFunctions.add(SourceSystemFunctions.DAYOFWEEK);
-		supportedFunctions.add(SourceSystemFunctions.HOUR); 
-		supportedFunctions.add(SourceSystemFunctions.MINUTE); 
-		supportedFunctions.add(SourceSystemFunctions.MONTH);
-		supportedFunctions.add(SourceSystemFunctions.QUARTER);
-		supportedFunctions.add(SourceSystemFunctions.SECOND);
-		supportedFunctions.add(SourceSystemFunctions.WEEK);
-		supportedFunctions.add(SourceSystemFunctions.YEAR);
-		//		FUNCTION DAYNAME = "dayname"; 
-		//		FUNCTION FORMATTIMESTAMP = "formattimestamp"; 
-		//		FUNCTION MODIFYTIMEZONE = "modifytimezone"; 
-		//		FUNCTION MONTHNAME = "monthname"; 
-		//		FUNCTION NOW = "now"; 
-		//		FUNCTION PARSETIMESTAMP = "parsetimestamp"; 
-		//		FUNCTION TIMESTAMPADD = "timestampadd"; 
-		//		FUNCTION TIMESTAMPCREATE = "timestampcreate"; 
-		//		FUNCTION TIMESTAMPDIFF = "timestampdiff"; 
-
-		
-		//SYSTEM FUNCTIONS
-		supportedFunctions.add(SourceSystemFunctions.IFNULL); //ALIAS-NVL
-		supportedFunctions.add(SourceSystemFunctions.COALESCE);
-		supportedFunctions.add(SourceSystemFunctions.NULLIF);
-		
-		
-		//CONVERSION functions
-		supportedFunctions.add(SourceSystemFunctions.CONVERT);
-		
-		
-		return supportedFunctions;
-	}
-	
-	public static class ExtractModifier extends FunctionModifier {
-    	private String type;
-    	public ExtractModifier(String type) {
-    		this.type = type;
-    	}
-		@Override
-		public List<?> translate(Function function) {
-			return Arrays.asList("extract(",this.type," from ",function.getParameters().get(0) ,")");    				
-		}
-	}
-
-	public static class BooleanToNumericConversionModifier extends FunctionModifier {
-		@Override
-		public List<?> translate(Function function) {
-			Expression booleanValue = function.getParameters().get(0);
-			if (booleanValue instanceof Function) {
-				Function nested = (Function)booleanValue;
-				if (nested.getName().equalsIgnoreCase("convert") && Number.class.isAssignableFrom(nested.getParameters().get(0).getType())) { 
-					booleanValue = nested.getParameters().get(0);
-				}
-			}
-			return Arrays.asList("(CASE WHEN ", booleanValue, " IN ( '0', 'FALSE') THEN 0 WHEN ", booleanValue, " IS NOT NULL THEN 1 END)");
-		}
-
-	}
-	public static class BooleanToStringConversionModifier extends FunctionModifier {
-		@Override
-		public List<?> translate(Function function) {
-			Expression booleanValue = function.getParameters().get(0);
-			if (booleanValue instanceof Function) {
-				Function nested = (Function)booleanValue;
-				if (nested.getName().equalsIgnoreCase("convert") && Number.class.isAssignableFrom(nested.getParameters().get(0).getType())) { 
-					booleanValue = nested.getParameters().get(0);
-				}
-			}
-			return Arrays.asList("CASE WHEN ", booleanValue, " = '0' THEN 'false' WHEN ", booleanValue, " IS NOT NULL THEN 'true' END"); 
-		}
-
-	}
-	
-	
-    public static class CastModifier extends FunctionModifier {
-    	private String target;
-    	public CastModifier(String target) {
-    		this.target = target;
-    	}
-		@Override
-		public List<?> translate(Function function) {
-			return Arrays.asList("cast(", function.getParameters().get(0), " AS "+this.target+")");   
-		}
-	}
-    
-    
-	@Override
-    public List<?> translateLimit(Limit limit, ExecutionContext context) {
-    	if (limit.getRowOffset() > 0) {
-    		return Arrays.asList("LIMIT ", limit.getRowLimit(), " OFFSET ", limit.getRowOffset());   
-    	}
-        return null;
-    }
-
-    @Override
-    public boolean supportsCorrelatedSubqueries() {
-        return false;
-    }
-
-	@Override
-    public boolean supportsIntersect() {
-    	return true;
-    }
-
-	@Override
-    public boolean supportsExcept() {
-    	return true;
-    }
-
-	@Override
-	public boolean supportsInlineViews() {
-		return true;
-	}
-
-	@Override
-	public boolean supportsRowLimit() {
-		return true;
-	}
-
-	@Override
-	public boolean supportsRowOffset() {
-		return true;
-	}
-
-	@Override
-	public boolean supportsAggregatesEnhancedNumeric() {
-		return true;
-	}
-	
-}

Copied: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java (from rev 3382, trunk/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/netezza/NetezzaExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,382 @@
+/*
+ * 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 org.teiid.translator.jdbc.netezza;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.Limit;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.SourceSystemFunctions;
+import org.teiid.translator.Translator;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.jdbc.AliasModifier;
+import org.teiid.translator.jdbc.ConvertModifier;
+import org.teiid.translator.jdbc.ExtractFunctionModifier;
+import org.teiid.translator.jdbc.FunctionModifier;
+import org.teiid.translator.jdbc.JDBCExecutionFactory;
+import org.teiid.translator.jdbc.LocateFunctionModifier;
+
+
+ at Translator(name = "netezza", description = "A translator for Netezza Database")
+public class NetezzaExecutionFactory extends JDBCExecutionFactory {
+
+	private static final String TIME_FORMAT = "HH24:MI:SS"; 
+	private static final String DATE_FORMAT = "YYYY-MM-DD"; 
+	private static final String DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT; 
+	private static final String TIMESTAMP_FORMAT = DATETIME_FORMAT + ".MS";  
+
+	public NetezzaExecutionFactory() {
+		setSupportsFullOuterJoins(true);
+		setSupportsOrderBy(true);
+		setSupportsOuterJoins(true);
+		setSupportsSelectDistinct(true);
+		setSupportsInnerJoins(true);
+	}
+
+	public void start() throws TranslatorException {
+		super.start();
+
+		//STRING FUNCTION MODIFIERS
+		////////////////////////////////////
+		registerFunctionModifier(SourceSystemFunctions.CHAR, new AliasModifier("chr"));  
+		registerFunctionModifier(SourceSystemFunctions.LCASE,new AliasModifier("lower"));  
+		registerFunctionModifier(SourceSystemFunctions.UCASE,new AliasModifier("upper"));  
+		registerFunctionModifier(SourceSystemFunctions.LOCATE, new  LocateFunctionModifier(getLanguageFactory(), "INSTR", true));	  
+       	registerFunctionModifier(SourceSystemFunctions.CONCAT, new AliasModifier("||")); 
+		///NUMERIC FUNCTION MODIFIERS
+        ////////////////////////////////////
+		registerFunctionModifier(SourceSystemFunctions.CEILING,	new AliasModifier("ceil"));  
+		registerFunctionModifier(SourceSystemFunctions.POWER,	new AliasModifier("pow"));  
+		registerFunctionModifier(SourceSystemFunctions.LOG,	new AliasModifier("LN"));
+		///BIT FUNCTION MODIFIERS
+		////////////////////////////////////
+        registerFunctionModifier(SourceSystemFunctions.BITAND, new AliasModifier("intNand")); 
+        registerFunctionModifier(SourceSystemFunctions.BITNOT, new AliasModifier("intNnot")); 
+        registerFunctionModifier(SourceSystemFunctions.BITOR, new AliasModifier("intNor")); 
+        registerFunctionModifier(SourceSystemFunctions.BITXOR, new AliasModifier("intNxor")); 
+		//DATE FUNCTION MODIFIERS
+        //////////////////////////////////////////
+		 registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractFunctionModifier());
+		 registerFunctionModifier(SourceSystemFunctions.DAYOFYEAR, new	ExtractModifier("DOY"));
+		 registerFunctionModifier(SourceSystemFunctions.QUARTER, new  ExtractFunctionModifier());
+		 registerFunctionModifier(SourceSystemFunctions.MONTH, new ExtractFunctionModifier());
+		 registerFunctionModifier(SourceSystemFunctions.DAYOFMONTH, new  ExtractModifier("DAY"));
+		 registerFunctionModifier(SourceSystemFunctions.WEEK, new ExtractFunctionModifier());
+		 registerFunctionModifier(SourceSystemFunctions.DAYOFWEEK, new  ExtractModifier("DOW"));
+         registerFunctionModifier(SourceSystemFunctions.HOUR, new	ExtractFunctionModifier());
+		 registerFunctionModifier(SourceSystemFunctions.MINUTE, new  ExtractFunctionModifier());
+		 registerFunctionModifier(SourceSystemFunctions.SECOND, new ExtractFunctionModifier());
+		 registerFunctionModifier(SourceSystemFunctions.CURDATE, new AliasModifier("CURRENT_DATE")); 
+		 registerFunctionModifier(SourceSystemFunctions.CURTIME, new AliasModifier("CURRENT_TIME")); 
+       //SYSTEM FUNCTIONS
+       ////////////////////////////////////
+		registerFunctionModifier(SourceSystemFunctions.IFNULL,new AliasModifier("NVL"));  
+        
+
+		// DATA TYPE CONVERSION
+		///////////////////////////////////////////
+		ConvertModifier convertModifier = new ConvertModifier();
+		convertModifier.addTypeMapping("char(1)", FunctionModifier.CHAR); 
+		convertModifier.addTypeMapping("byteint", FunctionModifier.BYTE); 
+		convertModifier.addTypeMapping("smallint", FunctionModifier.SHORT); 
+		convertModifier.addTypeMapping("bigint", FunctionModifier.LONG); 
+    	convertModifier.addTypeMapping("numeric(38)", FunctionModifier.BIGINTEGER); 
+    	convertModifier.addTypeMapping("numeric(38,18)", FunctionModifier.BIGDECIMAL); 
+		convertModifier.addTypeMapping("varchar(4000)", FunctionModifier.STRING); 
+		//convertModifier.addTypeMapping("nvarchar(5)", FunctionModifier.BOOLEAN);
+
+ 		///NO BOOLEAN, INTEGER, FLOAT, DATE, TIME, TIMESTAMP, as they are directly available in netezza
+		///NO NULL, CLOB, BLOB, OBJECT, XML
+		
+		
+		///BOOLEAN--BYTE, SHORT, INTEGER, LONG, FLOAT, DOUBLE, BIGINTEGER, BIGDECIMAL--AS IT DOESN'T WORK IMPLICITLY IN NETEZZA
+
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.INTEGER, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.BYTE, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.SHORT, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.LONG, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.FLOAT, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.DOUBLE, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.BIGINTEGER, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.BIGDECIMAL, new BooleanToNumericConversionModifier());
+		convertModifier.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.STRING, new BooleanToStringConversionModifier());
+    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.BOOLEAN, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				Expression stringValue = function.getParameters().get(0);
+				return Arrays.asList("CASE WHEN ", stringValue, " IN ('false', '0') THEN '0' WHEN ", stringValue, " IS NOT NULL THEN '1' END"); 
+			}
+		});
+		convertModifier.addTypeConversion(new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				Expression stringValue = function.getParameters().get(0);
+				return Arrays.asList("CASE WHEN ", stringValue, " = 0 THEN '0' WHEN ", stringValue, " IS NOT NULL THEN '1' END"); 
+			}
+		}, FunctionModifier.BOOLEAN);
+		
+		
+		
+
+		////////STRING TO DATATYPE CONVERSION OTHER THAN DATE/TIME
+		convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.INTEGER, new CastModifier("integer")); 
+		convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new CastModifier("float"));
+    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DOUBLE, new CastModifier("double"));
+    	///// STRING --> CHAR, BYTE, SHORT, LONG, BIGI, BIGD, BOOLEAN is taken care by Type Mapping
+    	///// NO conversion support for NULL, CLOB, BLOB, OBJECT, XML
+		////STRING TO DATE/TIME CONVERSION////
+		//////////////////////////////////////
+    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.DATE, new ConvertModifier.FormatModifier("to_date", DATE_FORMAT));  
+    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIME, new ConvertModifier.FormatModifier("to_timestamp", TIME_FORMAT));  
+    	convertModifier.addConvert(FunctionModifier.STRING, FunctionModifier.TIMESTAMP, new ConvertModifier.FormatModifier("to_timestamp", TIMESTAMP_FORMAT));  
+		//////DATE/TIME INTERNAL CONVERSION/////////
+		convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new CastModifier("TIME")); 
+		convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE,  new CastModifier("DATE"));  
+		convertModifier.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP,  new CastModifier("TIMESTAMP")); 
+		//convertModifier.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new CastModifier("TIMESTAMP")); //TIME --> TIMESTAMP --DOESN't WORK IN NETEZZA-NO FUNCTION SUPPORT
+				
+		////DATE/TIME to STRING CONVERION////
+		/////////////////////////////////////
+    	convertModifier.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING, new ConvertModifier.FormatModifier("to_char", TIMESTAMP_FORMAT));
+    	///NO NETEZAA FUNCTION for DATE, TIME to STRING
+		
+
+		convertModifier.setWideningNumericImplicit(true);
+		registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+	}
+
+	@Override
+	public List<String> getSupportedFunctions() {
+		List<String> supportedFunctions = new ArrayList<String>();
+		supportedFunctions.addAll(super.getSupportedFunctions());
+
+		////////////////////////////////////////////////////////////
+		//STRING FUNCTIONS
+		//////////////////////////////////////////////////////////
+		supportedFunctions.add(SourceSystemFunctions.ASCII);// taken care with alias function modifier
+		supportedFunctions.add(SourceSystemFunctions.CHAR);//ALIAS to use 'chr'
+		supportedFunctions.add(SourceSystemFunctions.CONCAT); // ALIAS ||
+		supportedFunctions.add(SourceSystemFunctions.INITCAP);
+		supportedFunctions.add(SourceSystemFunctions.LCASE);//ALIAS 'lower'
+		supportedFunctions.add(SourceSystemFunctions.LPAD);
+		supportedFunctions.add(SourceSystemFunctions.LENGTH);
+		supportedFunctions.add(SourceSystemFunctions.LOCATE); //LOCATE FUNCTIO MODIFIER
+		supportedFunctions.add(SourceSystemFunctions.LTRIM);
+		//supportedFunctions.add(SourceSystemFunctions.REPEAT);
+		supportedFunctions.add(SourceSystemFunctions.RPAD);
+		supportedFunctions.add(SourceSystemFunctions.RTRIM);
+		supportedFunctions.add(SourceSystemFunctions.SUBSTRING); //No Need of ALIAS as both substring and substr work in netezza
+		supportedFunctions.add(SourceSystemFunctions.UCASE); //ALIAS UPPER
+		// FUNCTION DIFFERENCE = "difference";  ///NO FUNCTION FOUND--DIFFERENCE 
+		//	FUNCTION INSERT = "insert"; 
+		// supportedFunctions.add(SourceSystemFunctions.LEFT); //is this available or is it simply for LEFT OUTER JOIN?
+		// FUNCTION REPLACE = "replace"; // NO REPLACE Function
+		// supportedFunctions.add(SourceSystemFunctions.RIGHT);--is this available or is it simply for RIGHT OUTER JOIN?
+		// FUNCTION SOUNDEX = "soundex";
+		//	FUNCTION TO_BYTES = "to_bytes"; 
+		//	FUNCTION TO_CHARS = "to_chars"; 
+		//////////	////////////////////////////////////////////////////////////////////
+		//NUMERIC FUNCTIONS////////////////////////////////////////////////////////////
+		//////////////////////////////////////////////////////////////////////////////
+		//supportedFunctions.add(SourceSystemFunctions.ABS);
+		supportedFunctions.add(SourceSystemFunctions.ACOS);
+		supportedFunctions.add(SourceSystemFunctions.ASIN);
+		supportedFunctions.add(SourceSystemFunctions.ATAN);
+		supportedFunctions.add(SourceSystemFunctions.ATAN2);
+		supportedFunctions.add(SourceSystemFunctions.CEILING);  ///ALIAS-ceil
+		supportedFunctions.add(SourceSystemFunctions.COS);
+		supportedFunctions.add(SourceSystemFunctions.COT);
+		supportedFunctions.add(SourceSystemFunctions.DEGREES);
+		//supportedFunctions.add(SourceSystemFunctions.EXP);
+		supportedFunctions.add(SourceSystemFunctions.FLOOR);
+		supportedFunctions.add(SourceSystemFunctions.LOG);
+		supportedFunctions.add(SourceSystemFunctions.MOD);
+		supportedFunctions.add(SourceSystemFunctions.PI);
+		supportedFunctions.add(SourceSystemFunctions.POWER);//	ALIAS-POW 
+		supportedFunctions.add(SourceSystemFunctions.RADIANS);
+		supportedFunctions.add(SourceSystemFunctions.ROUND);
+		supportedFunctions.add(SourceSystemFunctions.SIGN);	
+		supportedFunctions.add(SourceSystemFunctions.SIN);
+		supportedFunctions.add(SourceSystemFunctions.SQRT);
+		supportedFunctions.add(SourceSystemFunctions.TAN);
+		//		FUNCTION TRANSLATE = "translate"; 
+		//		FUNCTION TRUNCATE = "truncate"; 
+		//		FUNCTION FORMATINTEGER = "formatinteger"; 
+		//		FUNCTION FORMATLONG = "formatlong"; 
+		//		FUNCTION FORMATDOUBLE = "formatdouble"; 
+		//		FUNCTION FORMATFLOAT = "formatfloat"; 
+		//		FUNCTION FORMATBIGINTEGER = "formatbiginteger"; 
+		//		FUNCTION FORMATBIGDECIMAL = "formatbigdecimal"; 
+		//		FUNCTION LOG10 = "log10"; 
+		//		FUNCTION PARSEINTEGER = "parseinteger"; 
+		//		FUNCTION PARSELONG = "parselong"; 
+		//		FUNCTION PARSEDOUBLE = "parsedouble"; 
+		//		FUNCTION PARSEFLOAT = "parsefloat"; 
+		//		FUNCTION PARSEBIGINTEGER = "parsebiginteger"; 
+		//		FUNCTION PARSEBIGDECIMAL = "parsebigdecimal"; 
+		// supportedFunctions.add(SourceSystemFunctions.RAND); --Needs Alias--But, is it required to even have an alias???
+		/////////////////////////////////////////////////////////////////////
+		//BIT FUNCTIONS//////////////////////////////////////////////////////
+		//ALIAS FUNCTION MODIFIER IS APPLIED//////////////////////////////
+		supportedFunctions.add(SourceSystemFunctions.BITAND);
+		supportedFunctions.add(SourceSystemFunctions.BITOR);
+		supportedFunctions.add(SourceSystemFunctions.BITNOT);
+		supportedFunctions.add(SourceSystemFunctions.BITXOR);
+		// DATE FUNCTIONS
+		supportedFunctions.add(SourceSystemFunctions.CURDATE); 
+		supportedFunctions.add(SourceSystemFunctions.CURTIME); 
+		supportedFunctions.add(SourceSystemFunctions.DAYOFMONTH); 
+		supportedFunctions.add(SourceSystemFunctions.DAYOFYEAR);
+		supportedFunctions.add(SourceSystemFunctions.DAYOFWEEK);
+		supportedFunctions.add(SourceSystemFunctions.HOUR); 
+		supportedFunctions.add(SourceSystemFunctions.MINUTE); 
+		supportedFunctions.add(SourceSystemFunctions.MONTH);
+		supportedFunctions.add(SourceSystemFunctions.QUARTER);
+		supportedFunctions.add(SourceSystemFunctions.SECOND);
+		supportedFunctions.add(SourceSystemFunctions.WEEK);
+		supportedFunctions.add(SourceSystemFunctions.YEAR);
+		//		FUNCTION DAYNAME = "dayname"; 
+		//		FUNCTION FORMATTIMESTAMP = "formattimestamp"; 
+		//		FUNCTION MODIFYTIMEZONE = "modifytimezone"; 
+		//		FUNCTION MONTHNAME = "monthname"; 
+		//		FUNCTION NOW = "now"; 
+		//		FUNCTION PARSETIMESTAMP = "parsetimestamp"; 
+		//		FUNCTION TIMESTAMPADD = "timestampadd"; 
+		//		FUNCTION TIMESTAMPCREATE = "timestampcreate"; 
+		//		FUNCTION TIMESTAMPDIFF = "timestampdiff"; 
+
+		
+		//SYSTEM FUNCTIONS
+		supportedFunctions.add(SourceSystemFunctions.IFNULL); //ALIAS-NVL
+		supportedFunctions.add(SourceSystemFunctions.COALESCE);
+		supportedFunctions.add(SourceSystemFunctions.NULLIF);
+		
+		
+		//CONVERSION functions
+		supportedFunctions.add(SourceSystemFunctions.CONVERT);
+		
+		
+		return supportedFunctions;
+	}
+	
+	public static class ExtractModifier extends FunctionModifier {
+    	private String type;
+    	public ExtractModifier(String type) {
+    		this.type = type;
+    	}
+		@Override
+		public List<?> translate(Function function) {
+			return Arrays.asList("extract(",this.type," from ",function.getParameters().get(0) ,")");    				
+		}
+	}
+
+	public static class BooleanToNumericConversionModifier extends FunctionModifier {
+		@Override
+		public List<?> translate(Function function) {
+			Expression booleanValue = function.getParameters().get(0);
+			if (booleanValue instanceof Function) {
+				Function nested = (Function)booleanValue;
+				if (nested.getName().equalsIgnoreCase("convert") && Number.class.isAssignableFrom(nested.getParameters().get(0).getType())) { 
+					booleanValue = nested.getParameters().get(0);
+				}
+			}
+			return Arrays.asList("(CASE WHEN ", booleanValue, " IN ( '0', 'FALSE') THEN 0 WHEN ", booleanValue, " IS NOT NULL THEN 1 END)");
+		}
+
+	}
+	public static class BooleanToStringConversionModifier extends FunctionModifier {
+		@Override
+		public List<?> translate(Function function) {
+			Expression booleanValue = function.getParameters().get(0);
+			if (booleanValue instanceof Function) {
+				Function nested = (Function)booleanValue;
+				if (nested.getName().equalsIgnoreCase("convert") && Number.class.isAssignableFrom(nested.getParameters().get(0).getType())) { 
+					booleanValue = nested.getParameters().get(0);
+				}
+			}
+			return Arrays.asList("CASE WHEN ", booleanValue, " = '0' THEN 'false' WHEN ", booleanValue, " IS NOT NULL THEN 'true' END"); 
+		}
+
+	}
+	
+	
+    public static class CastModifier extends FunctionModifier {
+    	private String target;
+    	public CastModifier(String target) {
+    		this.target = target;
+    	}
+		@Override
+		public List<?> translate(Function function) {
+			return Arrays.asList("cast(", function.getParameters().get(0), " AS "+this.target+")");   
+		}
+	}
+    
+    
+	@Override
+    public List<?> translateLimit(Limit limit, ExecutionContext context) {
+    	if (limit.getRowOffset() > 0) {
+    		return Arrays.asList("LIMIT ", limit.getRowLimit(), " OFFSET ", limit.getRowOffset());   
+    	}
+        return null;
+    }
+
+    @Override
+    public boolean supportsCorrelatedSubqueries() {
+        return false;
+    }
+
+	@Override
+    public boolean supportsIntersect() {
+    	return true;
+    }
+
+	@Override
+    public boolean supportsExcept() {
+    	return true;
+    }
+
+	@Override
+	public boolean supportsInlineViews() {
+		return true;
+	}
+
+	@Override
+	public boolean supportsRowLimit() {
+		return true;
+	}
+
+	@Override
+	public boolean supportsRowOffset() {
+		return true;
+	}
+
+	@Override
+	public boolean supportsAggregatesEnhancedNumeric() {
+		return true;
+	}
+	
+}

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,8 +22,10 @@
 
 /*
  */
-package org.teiid.translator.jdbc.oracle;
+package org.teiid.translator.jdbc.oracle;
 
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
 import java.sql.PreparedStatement;
 import java.sql.SQLException;
 import java.sql.Timestamp;
@@ -49,7 +51,6 @@
 import org.teiid.language.SetQuery.Operation;
 import org.teiid.language.visitor.CollectorVisitor;
 import org.teiid.metadata.Column;
-import org.teiid.metadata.FunctionMethod;
 import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
@@ -75,6 +76,15 @@
     public final static String DUAL = "DUAL"; //$NON-NLS-1$
     public final static String ROWNUM = "ROWNUM"; //$NON-NLS-1$
     public final static String SEQUENCE = ":SEQUENCE="; //$NON-NLS-1$
+	/*
+	 * Spatial Functions
+	 */
+	public static final String RELATE = "sdo_relate"; //$NON-NLS-1$
+	public static final String NEAREST_NEIGHBOR = "sdo_nn"; //$NON-NLS-1$
+	public static final String FILTER = "sdo_filter"; //$NON-NLS-1$
+	public static final String WITHIN_DISTANCE = "sdo_within_distance"; //$NON-NLS-1$
+	public static final String NEAREST_NEIGHBOR_DISTANCE = "sdo_nn_distance"; //$NON-NLS-1$
+	public static final String ORACLE_SDO = "Oracle-SDO"; //$NON-NLS-1$
     
     public void start() throws TranslatorException {
         super.start();
@@ -112,10 +122,10 @@
 		});
         
         //spatial functions
-        registerFunctionModifier(OracleSpatialFunctions.RELATE, new OracleSpatialFunctionModifier());
-        registerFunctionModifier(OracleSpatialFunctions.NEAREST_NEIGHBOR, new OracleSpatialFunctionModifier());
-        registerFunctionModifier(OracleSpatialFunctions.FILTER, new OracleSpatialFunctionModifier());
-        registerFunctionModifier(OracleSpatialFunctions.WITHIN_DISTANCE, new OracleSpatialFunctionModifier());
+        registerFunctionModifier(OracleExecutionFactory.RELATE, new OracleSpatialFunctionModifier());
+        registerFunctionModifier(OracleExecutionFactory.NEAREST_NEIGHBOR, new OracleSpatialFunctionModifier());
+        registerFunctionModifier(OracleExecutionFactory.FILTER, new OracleSpatialFunctionModifier());
+        registerFunctionModifier(OracleExecutionFactory.WITHIN_DISTANCE, new OracleSpatialFunctionModifier());
         
         //add in type conversion
         ConvertModifier convertModifier = new ConvertModifier();
@@ -171,6 +181,21 @@
     	convertModifier.addNumericBooleanConversions();
     	convertModifier.setWideningNumericImplicit(true);
     	registerFunctionModifier(SourceSystemFunctions.CONVERT, convertModifier);
+    	
+    	addPushDownFunction(ORACLE_SDO, RELATE, STRING, STRING, STRING, STRING);
+    	addPushDownFunction(ORACLE_SDO, RELATE, STRING, OBJECT, OBJECT, STRING);
+    	addPushDownFunction(ORACLE_SDO, RELATE, STRING, STRING, OBJECT, STRING);
+    	addPushDownFunction(ORACLE_SDO, RELATE, STRING, OBJECT, STRING, STRING);
+    	addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, STRING, OBJECT, STRING, INTEGER);
+    	addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, OBJECT, OBJECT, STRING, INTEGER);
+    	addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR, STRING, OBJECT, STRING, STRING, INTEGER);
+    	addPushDownFunction(ORACLE_SDO, NEAREST_NEIGHBOR_DISTANCE, INTEGER, INTEGER);
+    	addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, OBJECT, OBJECT, STRING);
+    	addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, STRING, OBJECT, STRING);
+    	addPushDownFunction(ORACLE_SDO, WITHIN_DISTANCE, STRING, OBJECT, STRING, STRING);
+    	addPushDownFunction(ORACLE_SDO, FILTER, STRING, OBJECT, STRING, STRING);
+    	addPushDownFunction(ORACLE_SDO, FILTER, STRING, OBJECT, OBJECT, STRING);
+    	addPushDownFunction(ORACLE_SDO, FILTER, STRING, STRING, OBJECT, STRING);
     }
     
     public void handleInsertSequences(Insert insert) throws TranslatorException {
@@ -327,7 +352,7 @@
 	        // If so, the ORDERED hint is added, if not, it isn't
 	        Collection<Function> col = CollectorVisitor.collectObjects(Function.class, command);
 	        for (Function func : col) {
-	            if (func.getName().equalsIgnoreCase(OracleSpatialFunctions.RELATE)) {
+	            if (func.getName().equalsIgnoreCase(OracleExecutionFactory.RELATE)) {
 	                return comment + "/*+ ORDERED */ "; //$NON-NLS-1$
 	            }
 	        }
@@ -429,6 +454,7 @@
         supportedFunctions.add("RTRIM"); //$NON-NLS-1$
         supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
         supportedFunctions.add("TRANSLATE"); //$NON-NLS-1$
+        supportedFunctions.add(SourceSystemFunctions.TRIM);
         supportedFunctions.add("UCASE"); //$NON-NLS-1$
         supportedFunctions.add("UPPER"); //$NON-NLS-1$
         supportedFunctions.add("HOUR"); //$NON-NLS-1$
@@ -456,16 +482,15 @@
         supportedFunctions.add("IFNULL"); //$NON-NLS-1$
         supportedFunctions.add("NVL");      //$NON-NLS-1$ 
         supportedFunctions.add("COALESCE"); //$NON-NLS-1$
-        
+        supportedFunctions.add(RELATE);
+        supportedFunctions.add(NEAREST_NEIGHBOR);
+        supportedFunctions.add(NEAREST_NEIGHBOR_DISTANCE);
+        supportedFunctions.add(WITHIN_DISTANCE);
+        supportedFunctions.add(FILTER);
         return supportedFunctions;
     }
     
     @Override
-    public List<FunctionMethod> getPushDownFunctions(){
-    	return OracleSpatialFunctions.getOracleSpatialFunctions();
-    }
-    
-    @Override
     public String translateLiteralTimestamp(Timestamp timestampValue) {
     	if (timestampValue.getNanos() == 0) {
     		String val = formatDateValue(timestampValue);
@@ -508,4 +533,19 @@
     	return true;
     }
     
+    @Override
+    public boolean supportsElementaryOlapOperations() {
+    	return true;
+    }
+    
+    @Override
+    public boolean supportsLikeRegex() {
+    	return true;
+    }
+    
+    @Override
+    public String getLikeRegexString() {
+    	return "REGEXP_LIKE"; //$NON-NLS-1$
+    }
+    
 }

Deleted: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/oracle/OracleSpatialFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,149 +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 org.teiid.translator.jdbc.oracle;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
-
-public class OracleSpatialFunctions {
-	
-	/*
-	 * Spatial Functions
-	 */
-	public static final String RELATE = "sdo_relate"; //$NON-NLS-1$
-	public static final String NEAREST_NEIGHBOR = "sdo_nn"; //$NON-NLS-1$
-	public static final String FILTER = "sdo_filter"; //$NON-NLS-1$
-	public static final String WITHIN_DISTANCE = "sdo_within_distance"; //$NON-NLS-1$
-	public static final String NEAREST_NEIGHBOR_DISTANCE = "sdo_nn_distance"; //$NON-NLS-1$
-	public static final String ORACLE_SDO = "Oracle-SDO"; //$NON-NLS-1$
-	
-
-    public static List<FunctionMethod> getOracleSpatialFunctions(){
-    	    	
-    	List<FunctionMethod> spatialFuncs = new ArrayList<FunctionMethod>();
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + RELATE, RELATE, ORACLE_SDO,   
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + RELATE, RELATE, ORACLE_SDO, 
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + RELATE, RELATE, ORACLE_SDO,  
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + RELATE, RELATE, ORACLE_SDO, 
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + NEAREST_NEIGHBOR, NEAREST_NEIGHBOR, ORACLE_SDO,   
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("NUMBER", DataTypeManager.DefaultDataTypes.INTEGER, "") }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + NEAREST_NEIGHBOR, NEAREST_NEIGHBOR, ORACLE_SDO,  
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("NUMBER", DataTypeManager.DefaultDataTypes.INTEGER, "") }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    	
-
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + NEAREST_NEIGHBOR, NEAREST_NEIGHBOR, ORACLE_SDO,  
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("NUMBER", DataTypeManager.DefaultDataTypes.INTEGER, "") }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    	
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + NEAREST_NEIGHBOR_DISTANCE, NEAREST_NEIGHBOR_DISTANCE, ORACLE_SDO,  
-                new FunctionParameter[] {
-                    new FunctionParameter("NUMBER", DataTypeManager.DefaultDataTypes.INTEGER, "") }, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$  
-    	    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + WITHIN_DISTANCE, WITHIN_DISTANCE, ORACLE_SDO, 
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + WITHIN_DISTANCE, WITHIN_DISTANCE, ORACLE_SDO,   
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    	
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + WITHIN_DISTANCE, WITHIN_DISTANCE, ORACLE_SDO,  
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + FILTER, FILTER, ORACLE_SDO,   
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + FILTER, FILTER, ORACLE_SDO,  
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    
-    	
-    	spatialFuncs.add(new FunctionMethod(ORACLE_SDO + '.' + FILTER, FILTER, ORACLE_SDO,   
-                new FunctionParameter[] {
-                    new FunctionParameter("GEOM1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("GEOM2", DataTypeManager.DefaultDataTypes.OBJECT, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("PARAMS", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$      	
-    	
-    	return spatialFuncs;
-    }
-}

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/postgresql/PostgreSQLExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,8 +33,10 @@
 import org.teiid.language.Expression;
 import org.teiid.language.Function;
 import org.teiid.language.LanguageObject;
+import org.teiid.language.Like;
 import org.teiid.language.Limit;
 import org.teiid.language.Literal;
+import org.teiid.language.Like.MatchMode;
 import org.teiid.language.SQLConstants.NonReserved;
 import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.SourceSystemFunctions;
@@ -230,6 +232,11 @@
             		agg.setName("bool_or"); //$NON-NLS-1$
             	}
             }
+    	} else if (obj instanceof Like) {
+    		Like like = (Like)obj;
+    		if (like.getMode() == MatchMode.REGEX) {
+    			return Arrays.asList(like.getLeftExpression(), like.isNegated()?" !~ ":" ~ ", like.getRightExpression()); //$NON-NLS-1$ //$NON-NLS-2$
+    		}
     	}
     	return super.translate(obj, context);
     }
@@ -302,6 +309,7 @@
         supportedFunctions.add("RPAD"); //$NON-NLS-1$
         supportedFunctions.add("RTRIM"); //$NON-NLS-1$
         supportedFunctions.add("SUBSTRING"); //$NON-NLS-1$
+        supportedFunctions.add(SourceSystemFunctions.TRIM);
         supportedFunctions.add("UCASE"); //$NON-NLS-1$
         supportedFunctions.add("UPPER"); //$NON-NLS-1$
         
@@ -487,4 +495,24 @@
     	return getDatabaseVersion().compareTo(EIGHT_4) >= 0;
     }
     
+    @Override
+    public boolean supportsArrayAgg() {
+    	return getDatabaseVersion().compareTo(EIGHT_4) >= 0;
+    }
+    
+    @Override
+    public boolean supportsElementaryOlapOperations() {
+    	return getDatabaseVersion().compareTo(EIGHT_4) >= 0;
+    }
+    
+    @Override
+    public boolean supportsSimilarTo() {
+    	return true;
+    }
+    
+    @Override
+    public boolean supportsLikeRegex() {
+    	return true;
+    }
+    
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/sqlserver/SQLServerExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,6 +24,8 @@
  */
 package org.teiid.translator.jdbc.sqlserver;
 
+import java.sql.Date;
+import java.sql.Timestamp;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
@@ -203,8 +205,16 @@
     }
     
     @Override
+    public String translateLiteralDate(Date dateValue) {
+    	if (getDatabaseVersion().compareTo(V_2008) >= 0) {
+    		return super.translateLiteralDate(dateValue);
+    	}
+    	return super.translateLiteralTimestamp(new Timestamp(dateValue.getTime()));
+    }
+    
+    @Override
     public boolean hasTimeType() {
-    	return getDatabaseVersion().compareTo(V_2005) >= 0;
+    	return getDatabaseVersion().compareTo(V_2008) >= 0;
     }
     
     @Override
@@ -216,5 +226,15 @@
     protected boolean supportsCrossJoin() {
     	return true;
     }
+    
+    @Override
+    public boolean supportsElementaryOlapOperations() {
+    	return true;
+    }
+    
+    @Override
+    public boolean supportsWindowOrderByWithAggregates() {
+    	return false;
+    }
     
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teiid/TeiidExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -42,6 +42,7 @@
 	public static final String SEVEN_2 = "7.2"; //$NON-NLS-1$
 	public static final String SEVEN_3 = "7.3"; //$NON-NLS-1$
 	public static final String SEVEN_4 = "7.4"; //$NON-NLS-1$
+	public static final String SEVEN_5 = "7.5"; //$NON-NLS-1$
 	
 	public TeiidExecutionFactory() {
 		setDatabaseVersion(SEVEN_0);
@@ -144,14 +145,18 @@
         
         if (getDatabaseVersion().compareTo(SEVEN_3) >= 0) {
         	supportedFunctions.add(SourceSystemFunctions.UNESCAPE);
-        	
-            if (getDatabaseVersion().compareTo(SEVEN_4) >= 0) {
-            	supportedFunctions.add(SourceSystemFunctions.UUID);
-            	supportedFunctions.add(SourceSystemFunctions.ARRAY_GET);
-            	supportedFunctions.add(SourceSystemFunctions.ARRAY_LENGTH);
-            }
         }
         
+        if (getDatabaseVersion().compareTo(SEVEN_4) >= 0) {
+        	supportedFunctions.add(SourceSystemFunctions.UUID);
+        	supportedFunctions.add(SourceSystemFunctions.ARRAY_GET);
+        	supportedFunctions.add(SourceSystemFunctions.ARRAY_LENGTH);
+        }
+        
+        if (getDatabaseVersion().compareTo(SEVEN_5) >= 0) {
+        	supportedFunctions.add(SourceSystemFunctions.TRIM);
+        }
+        
         return supportedFunctions;
     }
     
@@ -201,4 +206,29 @@
     public boolean supportsCommonTableExpressions() {
     	return getDatabaseVersion().compareTo(SEVEN_2) >= 0;
     }
+    
+    @Override
+    public boolean supportsAdvancedOlapOperations() {
+    	return getDatabaseVersion().compareTo(SEVEN_5) >= 0;
+    }
+    
+    @Override
+    public boolean supportsElementaryOlapOperations() {
+    	return getDatabaseVersion().compareTo(SEVEN_5) >= 0;
+    }
+    
+    @Override
+    public boolean supportsArrayAgg() {
+    	return getDatabaseVersion().compareTo(SEVEN_5) >= 0;
+    }
+    
+    @Override
+    public boolean supportsLikeRegex() {
+    	return getDatabaseVersion().compareTo(SEVEN_5) >= 0;
+    }
+    
+    @Override
+    public boolean supportsSimilarTo() {
+    	return getDatabaseVersion().compareTo(SEVEN_5) >= 0;
+    }
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/java/org/teiid/translator/jdbc/teradata/TeradataExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,21 +22,28 @@
 
 package org.teiid.translator.jdbc.teradata;
 
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
 import java.sql.Date;
 import java.sql.Time;
 import java.sql.Timestamp;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
-import org.teiid.core.types.DataTypeManager;
 import org.teiid.language.ColumnReference;
+import org.teiid.language.Command;
+import org.teiid.language.DerivedColumn;
 import org.teiid.language.Expression;
 import org.teiid.language.Function;
 import org.teiid.language.LanguageFactory;
 import org.teiid.language.Literal;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
+import org.teiid.language.QueryExpression;
+import org.teiid.language.Select;
+import org.teiid.language.SortSpecification;
+import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.SourceSystemFunctions;
 import org.teiid.translator.Translator;
 import org.teiid.translator.TranslatorException;
@@ -69,33 +76,51 @@
 		convert.addTypeMapping("double precision", FunctionModifier.DOUBLE); //$NON-NLS-1$
 		convert.addTypeMapping("numeric(18,0)", FunctionModifier.BIGINTEGER); //$NON-NLS-1$
 		convert.addTypeMapping("char(1)", FunctionModifier.CHAR); //$NON-NLS-1$
-    	convert.addConvert(FunctionModifier.INTEGER, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.BIGDECIMAL, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.BIGINTEGER, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.FLOAT, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.BOOLEAN, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.LONG, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.SHORT, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.DOUBLE, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.BYTE, FunctionModifier.STRING, new ImplicitConvertModifier());
-    	convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new TimeModifier("TIME")); //$NON-NLS-1$
-    	convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE,  new TimeModifier("DATE")); //$NON-NLS-1$ 
-    	convert.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new TimeModifier("TIMESTAMP")); //$NON-NLS-1$
-    	convert.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP,  new TimeModifier("TIMESTAMP")); //$NON-NLS-1$
-    	convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING,  new TimeModifier("varchar(100)")); //$NON-NLS-1$
-    	convert.addConvert(FunctionModifier.TIME, FunctionModifier.STRING,  new TimeModifier("varchar(100)")); //$NON-NLS-1$
-    	convert.addConvert(FunctionModifier.DATE, FunctionModifier.STRING,  new TimeModifier("varchar(100)")); //$NON-NLS-1$
+
+    	convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.TIME, new CastModifier("TIME")); //$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.DATE,  new CastModifier("DATE")); //$NON-NLS-1$ 
+    	convert.addConvert(FunctionModifier.TIME, FunctionModifier.TIMESTAMP, new CastModifier("TIMESTAMP")); //$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.DATE, FunctionModifier.TIMESTAMP,  new CastModifier("TIMESTAMP")); //$NON-NLS-1$
+
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.INTEGER, new CastModifier("integer")); //$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.BIGDECIMAL, new CastModifier("decimal(37,5)"));//$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.BIGINTEGER, new CastModifier("numeric(18,0)"));//$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.FLOAT, new CastModifier("float"));//$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.BOOLEAN, new CastModifier("byteint"));//$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.LONG, new CastModifier("numeric(18,0)"));//$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.SHORT, new CastModifier("smallint"));//$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.DOUBLE, new CastModifier("double precision"));//$NON-NLS-1$
+    	convert.addConvert(FunctionModifier.STRING, FunctionModifier.BYTE, new CastModifier("byteint")); //$NON-NLS-1$
     	
+    	convert.addConvert(FunctionModifier.TIMESTAMP, FunctionModifier.STRING,  new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'Y4-MM-DDBHH:MI:SSDS(6)') AS VARCHAR(26))"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		}); 
+    	convert.addConvert(FunctionModifier.TIME, FunctionModifier.STRING,   new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'HH:MI:SS') AS VARCHAR(9))"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		}); 
+    	convert.addConvert(FunctionModifier.DATE, FunctionModifier.STRING,  new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("cast(cast(", function.getParameters().get(0), " AS FORMAT 'YYYY-MM-DD') AS VARCHAR(11))"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		}); 
+    	
     	convert.addTypeMapping("varchar(4000)", FunctionModifier.STRING); //$NON-NLS-1$
     	convert.addNumericBooleanConversions();
 		
 		registerFunctionModifier(SourceSystemFunctions.CONVERT, convert);
-		
+		registerFunctionModifier(SourceSystemFunctions.SUBSTRING, new AliasModifier("substr")); //$NON-NLS-1$	
 		registerFunctionModifier(SourceSystemFunctions.RAND, new AliasModifier("random")); //$NON-NLS-1$				
 		registerFunctionModifier(SourceSystemFunctions.LOG, new AliasModifier("LN")); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.LCASE, new UpperOrLowerModifier("LOWER", this.convert)); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.UCASE, new UpperOrLowerModifier("UPPER", this.convert)); //$NON-NLS-1$
-		registerFunctionModifier(SourceSystemFunctions.LENGTH, new AliasModifier("CHARACTER_LENGTH")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.LCASE, new AliasModifier("LOWER")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.UCASE, new AliasModifier("UPPER")); //$NON-NLS-1$
+		registerFunctionModifier(SourceSystemFunctions.LENGTH, new AliasModifier("character_length")); //$NON-NLS-1$
 		registerFunctionModifier(SourceSystemFunctions.CURDATE, new AliasModifier("CURRENT_DATE")); //$NON-NLS-1$
 		registerFunctionModifier(SourceSystemFunctions.CURTIME, new AliasModifier("CURRENT_TIME")); //$NON-NLS-1$
 		registerFunctionModifier(SourceSystemFunctions.YEAR, new ExtractModifier("YEAR")); //$NON-NLS-1$
@@ -117,13 +142,21 @@
         registerFunctionModifier(SourceSystemFunctions.LTRIM, new FunctionModifier() {
 			@Override
 			public List<?> translate(Function function) {
-				return Arrays.asList("TRIM(LEADING FROM ", expressionToString(function.getParameters().get(0), convert), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+				ArrayList<Object> target = new ArrayList<Object>();
+				target.add("TRIM(LEADING FROM ");//$NON-NLS-1$
+				target.add(function.getParameters().get(0));
+				target.add(")"); //$NON-NLS-1$				
+				return target; 
 			}
 		}); 
         registerFunctionModifier(SourceSystemFunctions.RTRIM, new FunctionModifier() {
 			@Override
 			public List<?> translate(Function function) {
-				return Arrays.asList("TRIM(TRAILING FROM ", expressionToString(function.getParameters().get(0), convert), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+				ArrayList<Object> target = new ArrayList<Object>();
+				target.add("TRIM(TRAILING FROM ");//$NON-NLS-1$
+				target.add(function.getParameters().get(0));
+				target.add(")"); //$NON-NLS-1$
+				return target; 
 			}
 		}); 
         registerFunctionModifier(SourceSystemFunctions.MOD, new FunctionModifier() {
@@ -131,7 +164,48 @@
 			public List<?> translate(Function function) {
 				return Arrays.asList(function.getParameters().get(0), " MOD ", function.getParameters().get(1)); //$NON-NLS-1$
 			}
+		});  
+        
+        addPushDownFunction(TERADATA, "COSH", FLOAT, FLOAT); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "TANH", FLOAT, FLOAT); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "ACOSH", FLOAT, FLOAT); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "ASINH", FLOAT, FLOAT); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "ATANH", FLOAT, FLOAT); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "CHAR2HEXINT", STRING, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "INDEX", INTEGER, STRING, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "BYTES", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "OCTET_LENGTH", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "HASHAMP", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "HASHBAKAMP", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "HASHBUCKET", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "HASHROW", INTEGER, STRING); //$NON-NLS-1$
+        addPushDownFunction(TERADATA, "NULLIFZERO", BIG_DECIMAL, BIG_DECIMAL); //$NON-NLS-1$        
+        addPushDownFunction(TERADATA, "ZEROIFNULL", BIG_DECIMAL, BIG_DECIMAL); //$NON-NLS-1$
+        registerFunctionModifier(SourceSystemFunctions.COT, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				function.setName(SourceSystemFunctions.TAN);
+				return Arrays.asList(getLanguageFactory().createFunction(SourceSystemFunctions.DIVIDE_OP, new Expression[] {new Literal(1, TypeFacility.RUNTIME_TYPES.INTEGER), function}, TypeFacility.RUNTIME_TYPES.DOUBLE));
+			}
 		});        
+        registerFunctionModifier(SourceSystemFunctions.LTRIM, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("TRIM(LEADING FROM ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		}); 
+        registerFunctionModifier(SourceSystemFunctions.RTRIM, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList("TRIM(TRAILING FROM ", function.getParameters().get(0), ")"); //$NON-NLS-1$ //$NON-NLS-2$
+			}
+		}); 
+        registerFunctionModifier(SourceSystemFunctions.MOD, new FunctionModifier() {
+			@Override
+			public List<?> translate(Function function) {
+				return Arrays.asList(function.getParameters().get(0), " MOD ", function.getParameters().get(1)); //$NON-NLS-1$
+			}
+		});        
 	}
 
 	@Override
@@ -141,7 +215,7 @@
 	
 	
     @Override
-    public List getSupportedFunctions() {
+    public List<String> getSupportedFunctions() {
         List<String> supportedFunctions = new ArrayList<String>();
         supportedFunctions.addAll(super.getSupportedFunctions());
 
@@ -163,7 +237,6 @@
         supportedFunctions.add(SourceSystemFunctions.LOCATE);
         supportedFunctions.add(SourceSystemFunctions.LOG);
         supportedFunctions.add(SourceSystemFunctions.LCASE);
-        supportedFunctions.add("lower");//$NON-NLS-1$
         supportedFunctions.add(SourceSystemFunctions.LTRIM);
         supportedFunctions.add(SourceSystemFunctions.LENGTH);
         supportedFunctions.add(SourceSystemFunctions.MINUTE);
@@ -178,106 +251,14 @@
         supportedFunctions.add(SourceSystemFunctions.SQRT);
         supportedFunctions.add(SourceSystemFunctions.SUBSTRING);
         supportedFunctions.add(SourceSystemFunctions.TAN);
-        supportedFunctions.add("||"); //$NON-NLS-1$
-        supportedFunctions.add("**"); //$NON-NLS-1$
+        supportedFunctions.add(SourceSystemFunctions.TRIM);
         supportedFunctions.add(SourceSystemFunctions.UCASE);
         supportedFunctions.add(SourceSystemFunctions.YEAR);
 
         return supportedFunctions;
     }
     
-    
     @Override
-    public List<FunctionMethod> getPushDownFunctions(){
-    	        
-    	List<FunctionMethod> pushdownFunctions = new ArrayList<FunctionMethod>();
-    
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "COSH", "COSH", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter[] {
-                new FunctionParameter("float", DataTypeManager.DefaultDataTypes.FLOAT, "Hyperbolic Cos")}, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.FLOAT, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "SINH", "SINH", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("float", DataTypeManager.DefaultDataTypes.FLOAT, "Hyperbolic Sin")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.FLOAT, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "TANH", "TANH", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("float", DataTypeManager.DefaultDataTypes.FLOAT, "Hyperbolic Tanh")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.FLOAT, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "ACOSH", "ACOSH", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("float", DataTypeManager.DefaultDataTypes.FLOAT, "Hyperbolic ArcCos")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.FLOAT, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "ASINH", "ASINH", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("float", DataTypeManager.DefaultDataTypes.FLOAT, "Hyperbolic ArcSin")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.FLOAT, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "ATANH", "ATANH", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("float", DataTypeManager.DefaultDataTypes.FLOAT, "Hyperbolic ArcTan")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.FLOAT, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-				
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "CHAR2HEXINT", "CHAR2HEXINT", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "INDEX", "INDEX", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("string1", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-	                new FunctionParameter("String2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "BYTES", "BYTES", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("String2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "OCTET_LENGTH", "OCTET_LENGTH", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("String2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "HASHAMP", "HASHAMP", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("String2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "HASHBAKAMP", "HASHBAKAMP", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("String2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "HASHBUCKET", "HASHBUCKET", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("String2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "HASHROW", "HASHROW", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("String2", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "NULLIFZERO", "NULLIFZERO", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("integer", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(TERADATA + '.' + "ZEROIFNULL", "ZEROIFNULL", TERADATA, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter[] {
-	                new FunctionParameter("integer", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-	            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BIG_DECIMAL, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$		
-		
-		return pushdownFunctions;		
-    }    
-    
-    
-    @Override
     public String translateLiteralDate(Date dateValue) {
         return "cast('" + formatDateValue(dateValue) + "' AS DATE FORMAT 'yyyy-mm-dd')"; //$NON-NLS-1$//$NON-NLS-2$
     }
@@ -336,8 +317,37 @@
     }
     
     @Override
-    public boolean supportsSetQueryOrderBy() {
-    	return false;
+    public List<?> translateCommand(Command command, ExecutionContext context) {
+    	if (command instanceof QueryExpression) {
+    		QueryExpression qe = (QueryExpression)command;
+    		//teradata prefers positional ordering
+    		if (qe.getOrderBy() != null) {
+    			Select select = qe.getProjectedQuery();
+    			List<DerivedColumn> derivedColumns = select.getDerivedColumns();
+    			Map<String, Integer> positions = new HashMap<String, Integer>();
+    			int i = 1;
+    			for (DerivedColumn derivedColumn : derivedColumns) {
+    				String name = derivedColumn.getAlias();
+    				if (name == null && derivedColumn.getExpression() instanceof ColumnReference) {
+    					ColumnReference cr = (ColumnReference)derivedColumn.getExpression();
+    					name = cr.toString();
+    				}
+					positions.put(name, i++);
+				}
+    			for (SortSpecification ss : qe.getOrderBy().getSortSpecifications()) {
+    				Expression ex = ss.getExpression();
+    				if (!(ex instanceof ColumnReference)) {
+    					continue;
+    				} 
+    				ColumnReference cr = (ColumnReference)ex;
+    				Integer position = positions.get(cr.toString());
+    				if (position != null) {
+    					ss.setExpression(new Literal(position, TypeFacility.RUNTIME_TYPES.INTEGER));
+    				}
+				}
+    		}
+    	}
+    	return super.translateCommand(command, context);
     }
     
     public static class LocateModifier extends FunctionModifier {
@@ -349,45 +359,31 @@
 		
     	@Override
 		public List<?> translate(Function function) {
+    		ArrayList<Object> target = new ArrayList<Object>();
     		Expression expr1 =  function.getParameters().get(0);
     		Expression expr2 =  function.getParameters().get(1);
-    		ArrayList target = new ArrayList();
-    		target.add("position("); //$NON-NLS-1$
-    		target.addAll(expressionToString(expr1, this.convertModifier));
-    		target.add( " in "); //$NON-NLS-1$
-    		target.addAll(expressionToString(expr2, this.convertModifier));
-    		target.add(")"); //$NON-NLS-1$
+    		if (function.getParameters().size() > 2) {
+    			Expression expr3 =  function.getParameters().get(2);
+	    		target.add("position("); //$NON-NLS-1$
+	    		target.add(expr1);
+	    		target.add( " in "); //$NON-NLS-1$
+	    		target.add("substr("); //$NON-NLS-1$
+	    		target.add(expr2);
+	    		target.add(","); //$NON-NLS-1$
+	    		target.add(expr3);
+	    		target.add("))"); //$NON-NLS-1$	    		
+    		}
+    		else {
+	    		target.add("position("); //$NON-NLS-1$
+	    		target.add(expr1);
+	    		target.add( " in "); //$NON-NLS-1$
+	    		target.add(expr2);
+	    		target.add(")"); //$NON-NLS-1$
+    		}
     		return target;
 		}
 	}
     
-    private static List<?> expressionToString(Expression expr, ConvertModifier modifier) {
-    	Class tgtType = expr.getType();
-		if (tgtType.equals(String.class) && (expr instanceof Literal)) {
-			return Arrays.asList(expr);  
-		}
-		else if (tgtType.equals(String.class) && (expr instanceof Function)) {
-			
-			Function func = (Function)expr;
-			if (func.getParameters().get(0) instanceof ColumnReference) {
-				ColumnReference ref = (ColumnReference)func.getParameters().get(0);
-				if(Number.class.isAssignableFrom(ref.getType())) {
-					ArrayList target = new ArrayList();
-					target.add("cast("); //$NON-NLS-1$
-					target.add(func.getParameters().get(0));
-					target.add(" AS varchar(100))"); //$NON-NLS-1$
-				}
-				else {
-					return modifier.translate(func);
-				}
-			}
-			else {
-				return modifier.translate(func);	
-			}
-		} 
-		return Arrays.asList("cast(" , expr, " AS varchar(100))"); //$NON-NLS-1$ //$NON-NLS-2$ 
-    }
-
 	public static class ExtractModifier extends FunctionModifier {
     	private String type;
     	public ExtractModifier(String type) {
@@ -399,17 +395,9 @@
 		}
 	}
     
-    public static class ImplicitConvertModifier extends FunctionModifier {
-		@Override
-		public List<?> translate(Function function) {
-			return Arrays.asList(function.getParameters().get(0));
-		}
-	}
-    
-    
-    public static class TimeModifier extends FunctionModifier {
+    public static class CastModifier extends FunctionModifier {
     	private String target;
-    	public TimeModifier(String target) {
+    	public CastModifier(String target) {
     		this.target = target;
     	}
 		@Override
@@ -418,25 +406,6 @@
 		}
 	}
     
-    public static class UpperOrLowerModifier extends FunctionModifier {
-    	String funcName;
-    	ConvertModifier convertModifier;
-    	public UpperOrLowerModifier(String name, ConvertModifier converModifier) {
-    		this.funcName = name;
-    		this.convertModifier = converModifier;
-    	}
-    	@Override
-		public List<?> translate(Function function) {
-			Expression expr = function.getParameters().get(0);
-			ArrayList target = new ArrayList();
-			target.add(this.funcName);
-			target.add("("); //$NON-NLS-1$
-			target.addAll(expressionToString(expr, this.convertModifier));
-			target.add(")"); //$NON-NLS-1$
-			return target;
-		}
-	}
-    
     public static class LeftOrRightFunctionModifier extends FunctionModifier {
         private LanguageFactory langFactory;
         ConvertModifier convertModifier;
@@ -449,26 +418,29 @@
         @Override
         public List<?> translate(Function function) {
             List<Expression> args = function.getParameters();
-            ArrayList target = new ArrayList();
+            ArrayList<Object> target = new ArrayList<Object>();
             if (function.getName().equalsIgnoreCase("left")) { //$NON-NLS-1$
             	//substr(string, 1, length)
             	target.add("substr("); //$NON-NLS-1$
-            	target.addAll(expressionToString(args.get(0), this.convertModifier));
+            	target.add(args.get(0));
+            	target.add(","); //$NON-NLS-1$
             	target.add(langFactory.createLiteral(Integer.valueOf(1), TypeFacility.RUNTIME_TYPES.INTEGER));
+            	target.add(","); //$NON-NLS-1$
             	target.add(args.get(1));
             	target.add(")"); //$NON-NLS-1$
             } else if (function.getName().equalsIgnoreCase("right")) { //$NON-NLS-1$
             	//substr(case_size, character_length(case_size) -4) 
             	target.add("substr("); //$NON-NLS-1$
-            	target.addAll(expressionToString(args.get(0), this.convertModifier));
+            	target.add(args.get(0));
             	
             	target.add(",(character_length("); //$NON-NLS-1$
-            	target.addAll(expressionToString(args.get(0), this.convertModifier));
+            	target.add(args.get(0));
             	target.add(")-"); //$NON-NLS-1$
             	target.add(args.get(1));
-            	target.add("))"); //$NON-NLS-1$
+            	target.add("+1))"); //$NON-NLS-1$ // offset for 1 based index
             }
             return target;
         }
     }    
+    
 }

Modified: branches/as7/connectors/translator-jdbc/src/main/resources/META-INF/services/org.teiid.translator.ExecutionFactory
===================================================================
--- branches/as7/connectors/translator-jdbc/src/main/resources/META-INF/services/org.teiid.translator.ExecutionFactory	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/main/resources/META-INF/services/org.teiid.translator.ExecutionFactory	2011-08-18 16:17:24 UTC (rev 3394)
@@ -6,17 +6,17 @@
 org.teiid.translator.jdbc.h2.H2ExecutionFactory #h2
 org.teiid.translator.jdbc.hsql.HsqlExecutionFactory #hsql
 org.teiid.translator.jdbc.informix.InformixExecutionFactory #informix
+org.teiid.translator.jdbc.ingres.IngresExecutionFactory #ingres
+org.teiid.translator.jdbc.ingres.Ingres93ExecutionFactory #ingres93
+org.teiid.translator.jdbc.intersyscache.InterSystemsCacheExecutionFactory #intersystems-cache
 org.teiid.translator.jdbc.mm.MetaMatrixExecutionFactory #metamatrix
+org.teiid.translator.jdbc.modeshape.ModeShapeExecutionFactory #modeshape
 org.teiid.translator.jdbc.mysql.MySQLExecutionFactory #mysql
 org.teiid.translator.jdbc.mysql.MySQL5ExecutionFactory #mysql5
+org.teiid.translator.jdbc.netezza.NetezzaExecutionFactory #netezza
 org.teiid.translator.jdbc.oracle.OracleExecutionFactory #oracle
 org.teiid.translator.jdbc.postgresql.PostgreSQLExecutionFactory #postgresql
 org.teiid.translator.jdbc.sqlserver.SQLServerExecutionFactory #sqlserver
 org.teiid.translator.jdbc.sybase.SybaseExecutionFactory #sybase
 org.teiid.translator.jdbc.teiid.TeiidExecutionFactory #teiid
 org.teiid.translator.jdbc.teradata.TeradataExecutionFactory #teradata
-org.teiid.translator.jdbc.modeshape.ModeShapeExecutionFactory #modeshape
-org.teiid.translator.jdbc.ingres.IngresExecutionFactory #ingres
-org.teiid.translator.jdbc.ingres.Ingres93ExecutionFactory #ingres93
-org.teiid.translator.jdbc.intersyscache.InterSystemsCacheExecutionFactory #intersystems-cache
-


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/FakeConnection.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,6 +36,7 @@
 import org.mockito.Mockito;
 import org.teiid.cdk.api.TranslationUtility;
 import org.teiid.cdk.unittest.FakeTranslationFactory;
+import org.teiid.core.CoreConstants;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.language.Command;
 import org.teiid.metadata.FunctionMethod;
@@ -56,7 +57,7 @@
     public static TranslationUtility getTranslationUtility(String vdbFileName, String udf) {
     	TranslationUtility util = null;
     	if (PARTS_VDB.equals(vdbFileName)) {
-    		util = new TranslationUtility(TranslationHelper.class.getResource(vdbFileName));
+    		util = new TranslationUtility("PartsSupplier.vdb", TranslationHelper.class.getResource(vdbFileName)); //$NON-NLS-1$
     	} else if (BQT_VDB.equals(vdbFileName)){
     		util = FakeTranslationFactory.getInstance().getBQTTranslationUtility();
     	} else {
@@ -72,7 +73,7 @@
 	public static void loadUDFs(String udf, TranslationUtility util) {
 		try {
 			Collection <FunctionMethod> methods = FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream());
-			util.setUDF(methods);
+			util.addUDF("foo", methods); //$NON-NLS-1$
 		} catch (IOException e) {
 			throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
 		} catch (JAXBException e) {
@@ -83,8 +84,11 @@
     public static Command helpTranslate(String vdbFileName, String udf, List<FunctionMethod> pushdowns, String sql) {
     	TranslationUtility util =  getTranslationUtility(vdbFileName, null);   
     	
-    	Collection <FunctionMethod> methods = new ArrayList<FunctionMethod>();
+    	if (pushdowns != null) {
+    		util.addUDF(CoreConstants.SYSTEM_MODEL, pushdowns);
+    	}
     	if (udf != null) {
+        	Collection <FunctionMethod> methods = new ArrayList<FunctionMethod>();
     		try {
 				methods.addAll(FunctionMetadataReader.loadFunctionMethods(TranslationHelper.class.getResource(udf).openStream()));
 			} catch (JAXBException e) {
@@ -92,11 +96,8 @@
 			} catch (IOException e) {
 				throw new TeiidRuntimeException("failed to load UDF"); //$NON-NLS-1$
 			}
+			util.addUDF("foo", methods); //$NON-NLS-1$
     	}
-    	if (pushdowns != null) {
-    		methods.addAll(pushdowns);
-    	}
-    	util.setUDF(methods);
     	return util.parseCommand(sql);
     }    
 


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/TranslationHelper.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/access
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2SqlTranslator.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2SqlTranslator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/db2/TestDB2SqlTranslator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -270,5 +270,14 @@
                 input, output, 
                 TRANSLATOR);
     }
+    
+    @Test public void testTrim() throws Exception {
+        String input = "SELECT trim(leading 'x' from stringnum) FROM BQT1.SMALLA"; //$NON-NLS-1$
+        String output = "SELECT STRIP(SmallA.StringNum, leading, 'x') FROM SmallA";  //$NON-NLS-1$
 
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+                input, output, 
+                TRANSLATOR);
+    }
+
 }


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbyCapabilities.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbyCapabilities.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/derby/TestDerbyCapabilities.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,9 +22,7 @@
 
 package org.teiid.translator.jdbc.derby;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.*;
 
 import org.junit.Test;
 
@@ -41,7 +39,7 @@
 		DerbyExecutionFactory derbyCapabilities = new DerbyExecutionFactory();
 		assertEquals(27, derbyCapabilities.getSupportedFunctions().size());
 		derbyCapabilities.setDatabaseVersion(DerbyExecutionFactory.TEN_4);
-		assertEquals(43, derbyCapabilities.getSupportedFunctions().size());
+		assertEquals(44, derbyCapabilities.getSupportedFunctions().size());
 	}
 
 }


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/mysql
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Deleted: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,509 +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 org.teiid.translator.jdbc.netezza;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.LanguageFactory;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.SQLConversionVisitor;
-
-
-/**
- */
-public class TestNetezzaConvertModifier extends TestCase {
-
-    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
-
-    public TestNetezzaConvertModifier(String name) {
-        super(name);
-    }
-
-    public String helpGetString(Expression expr) throws Exception {
-        NetezzaExecutionFactory trans = new NetezzaExecutionFactory();
-        trans.start();
-        SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor(); 
-        sqlVisitor.append(expr);  
-        
-        return sqlVisitor.toString();        
-    }
-
-    public void helpTest(Expression srcExpression, String tgtType, String expectedExpression) throws Exception {
-        Function func = LANG_FACTORY.createFunction("convert",  //$NON-NLS-1$
-            Arrays.asList( 
-                srcExpression,
-                LANG_FACTORY.createLiteral(tgtType, String.class)),
-            TypeFacility.getDataTypeClass(tgtType));
-        
-        assertEquals("Error converting from " + srcExpression.getType() + " to " + tgtType,  
-            expectedExpression, helpGetString(func)); 
-    }
-    
-    
-    
-
-    // Source = STRING
-    public void testStringToChar() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "char", "cast('5' AS char(1))"); 
-    }
-
-    public void testStringToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "boolean", "CASE WHEN '5' IN ('false', '0') THEN '0' WHEN '5' IS NOT NULL THEN '1' END"); 
-    }
-
-    public void testStringToByte() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "byte", "cast('5' AS byteint)"); 
-    }
-
-    public void testStringToShort() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "short", "cast('5' AS smallint)"); 
-    }
-
-    public void testStringToInteger() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "integer", "cast('5' AS integer)"); 
-    }
-
-    public void testStringToLong() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "long", "cast('5' AS bigint)"); 
-    }
-
-    public void testStringToBigInteger() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "biginteger", "cast('5' AS numeric(38))");  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    public void testStringToFloat() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "float", "cast('5' AS float)");
-    }
-
-    public void testStringToDouble() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "double", "cast('5' AS double)"); 
-    }
-
-    public void testStringToDate() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("2004-06-29", String.class), "date", "to_date('2004-06-29', 'YYYY-MM-DD')"); 
-    }
-
-    public void testStringToTime() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("23:59:59", String.class), "time", "to_timestamp('23:59:59', 'HH24:MI:SS')"); 
-    }
-
-    public void testStringToTimestamp() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("2004-06-29 23:59:59.987", String.class), "timestamp", "to_timestamp('2004-06-29 23:59:59.987', 'YYYY-MM-DD HH24:MI:SS.MS')"); 
-    }
-
-    public void testStringToBigDecimal() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral("5", String.class), "bigdecimal", "cast('5' AS numeric(38,18))"); 
-    }
-
-    // Source = CHAR
-    
-    public void testCharToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Character('5'), Character.class), "string", "'5'"); 
-    }
-
-    // Source = BOOLEAN
-    
-    public void testBooleanToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.TRUE, Boolean.class), "string", "CASE WHEN 1 = '0' THEN 'false' WHEN 1 IS NOT NULL THEN 'true' END"); 
-    }
-
-    public void testBooleanToByte() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "byte", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-
-    public void testBooleanToShort() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "short", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-
-    public void testBooleanToInteger() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "integer", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-
-    public void testBooleanToLong() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "long", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-
-    public void testBooleanToBigInteger() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "biginteger", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-
-    public void testBooleanToFloat() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "float", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-
-    public void testBooleanToDouble() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "double", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-
-    public void testBooleanToBigDecimal() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "bigdecimal", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
-    }
-    
-    // Source = BYTE
-    
-    public void testByteToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "string", "cast(1 AS varchar(4000))"); 
-    }
-
-    public void testByteToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testByteToShort() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "short", "1"); 
-//    }
-//
-//    public void testByteToInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "integer", "integer(1)"); 
-//    }
-//
-//    public void testByteToLong() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "long", "bigint(1)"); 
-//    }
-//
-//    public void testByteToBigInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "biginteger", "cast(1 AS numeric(31,0))"); 
-//    }
-//
-//    public void testByteToFloat() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "float", "cast(1 AS real)"); 
-//    }
-//
-//    public void testByteToDouble() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "double", "double(1)"); 
-//    }
-//
-//    public void testByteToBigDecimal() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
-//    }
-
-    // Source = SHORT
-    
-    public void testShortToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "string", "cast(1 AS varchar(4000))"); 
-    }
-
-    public void testShortToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testShortToByte() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "byte", "1"); 
-//    }
-//
-//    public void testShortToInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "integer", "integer(1)"); 
-//    }
-//
-//    public void testShortToLong() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "long", "bigint(1)"); 
-//    }
-//
-//    public void testShortToBigInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "biginteger", "cast(1 AS numeric(31,0))"); 
-//    }
-//
-//    public void testShortToFloat() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "float", "cast(1 AS real)"); 
-//    }
-//
-//    public void testShortToDouble() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "double", "double(1)"); 
-//    }
-//
-//    public void testShortToBigDecimal() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
-//    }
-
-    // Source = INTEGER
-    
-    public void testIntegerToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "string", "cast(1 AS varchar(4000))"); 
-    }
-
-    public void testIntegerToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testIntegerToByte() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "byte", "smallint(1)"); 
-//    }
-//
-//    public void testIntegerToShort() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "short", "smallint(1)"); 
-//    }
-//
-//    public void testIntegerToLong() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "long", "bigint(1)"); 
-//    }
-//
-//    public void testIntegerToBigInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "biginteger", "cast(1 AS numeric(31,0))"); 
-//    }
-//
-//    public void testIntegerToFloat() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "float", "cast(1 AS real)"); 
-//    }
-//
-//    public void testIntegerToDouble() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "double", "double(1)"); 
-//    }
-//
-//    public void testIntegerToBigDecimal() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
-//    }
-
-    // Source = LONG
-    
-    public void testLongToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "string", "cast(1 AS varchar(4000))"); 
-    }
-
-    public void testLongToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testLongToByte() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "byte", "smallint(1)"); 
-//    }
-//
-//    public void testLongToShort() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "short", "smallint(1)"); 
-//    }
-//
-//    public void testLongToInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "integer", "integer(1)"); 
-//    }
-//
-//    public void testLongToBigInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "biginteger", "cast(1 AS numeric(31,0))"); 
-//    }
-//
-//    public void testLongToFloat() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "float", "cast(1 AS real)"); 
-//    }
-//
-//    public void testLongToDouble() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "double", "double(1)"); 
-//    }
-//
-//    public void testLongToBigDecimal() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
-//    }
-
-    // Source = BIGINTEGER
-    
-    public void testBigIntegerToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "string", "cast(1 AS varchar(4000))"); 
-    }
-
-    public void testBigIntegerToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testBigIntegerToByte() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "byte", "smallint(1)"); 
-//    }
-//
-//    public void testBigIntegerToShort() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "short", "smallint(1)"); 
-//    }
-//
-//    public void testBigIntegerToInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "integer", "integer(1)"); 
-//    }
-//
-//    public void testBigIntegerToLong() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "long", "bigint(1)"); 
-//    }
-//
-//    public void testBigIntegerToFloat() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "float", "cast(1 AS real)"); 
-//    }
-//
-//    public void testBigIntegerToDouble() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "double", "double(1)"); 
-//    }
-//
-//    public void testBigIntegerToBigDecimal() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
-//    }
-
-    // Source = FLOAT
-    
-    public void testFloatToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "string", "cast(1.2 AS varchar(4000))"); 
-    }
-
-    public void testFloatToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "boolean", "CASE WHEN 1.2 = 0 THEN '0' WHEN 1.2 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testFloatToByte() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "byte", "smallint(1.2)"); 
-//    }
-//
-//    public void testFloatToShort() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "short", "smallint(1.2)"); 
-//    }
-//
-//    public void testFloatToInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "integer", "integer(1.2)"); 
-//    }
-//
-//    public void testFloatToLong() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "long", "bigint(1.2)"); 
-//    }
-//
-//    public void testFloatToBigInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "biginteger", "cast(1.2 AS numeric(31,0))"); 
-//    }
-//
-//    public void testFloatToDouble() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "double", "double(1.2)"); 
-//    }
-//
-//    public void testFloatToBigDecimal() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "bigdecimal", "cast(1.2 AS numeric(31,12))"); 
-//    }
-
-    // Source = DOUBLE
-    
-    public void testDoubleToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "string", "cast(1.2 AS varchar(4000))"); 
-    }
-
-    public void testDoubleToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "boolean", "CASE WHEN 1.2 = 0 THEN '0' WHEN 1.2 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testDoubleToByte() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "byte", "smallint(1.2)"); 
-//    }
-//
-//    public void testDoubleToShort() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "short", "smallint(1.2)"); 
-//    }
-//
-//    public void testDoubleToInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "integer", "integer(1.2)"); 
-//    }
-//
-//    public void testDoubleToLong() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "long", "bigint(1.2)"); 
-//    }
-//
-//    public void testDoubleToBigInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "biginteger", "cast(1.2 AS numeric(31,0))"); 
-//    }
-//
-//    public void testDoubleToFloat() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "float", "cast(1.2 AS real)"); 
-//    }
-//
-//    public void testDoubleToBigDecimal() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "bigdecimal", "cast(1.2 AS numeric(31,12))"); 
-//    }
-
-    // Source = BIGDECIMAL
-    
-    public void testBigDecimalToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "string", "cast(1.0 AS varchar(4000))"); 
-    }
-
-    public void testBigDecimalToBoolean() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "boolean", "CASE WHEN 1.0 = 0 THEN '0' WHEN 1.0 IS NOT NULL THEN '1' END"); 
-    }
-
-//    public void testBigDecimalToByte() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "byte", "smallint(1.0)"); 
-//    }
-//
-//    public void testBigDecimalToShort() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "short", "smallint(1.0)"); 
-//    }
-//
-//    public void testBigDecimalToInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "integer", "integer(1.0)"); 
-//    }
-//
-//    public void testBigDecimalToLong() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "long", "bigint(1.0)"); 
-//    }
-//
-//    public void testBigDecimalToBigInteger() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "biginteger", "cast(1.0 AS numeric(31,0))"); 
-//    }
-//
-//    public void testBigDecimalToFloat() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "float", "cast(1.0 AS real)"); 
-//    }
-//
-//    public void testBigDecimalToDouble() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "double", "double(1.0)"); 
-//    }
-
-//    // Source = DATE
-//
-//    public void testDateToString() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createDate(103, 10, 1), java.sql.Date.class), "string", "char({d '2003-11-01'})"); 
-//    }
-//
-//    public void testDateToTimestamp() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createDate(103, 10, 1), java.sql.Date.class), "timestamp", "timestamp({d '2003-11-01'}, '00:00:00')"); 
-//    }
-//
-//    // Source = TIME
-//
-//    public void testTimeToString() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createTime(23, 59, 59), java.sql.Time.class), "string", "char({t '23:59:59'})"); 
-//    }
-//
-//    public void testTimeToTimestamp() throws Exception {
-//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createTime(23, 59, 59), java.sql.Time.class), "timestamp", "timestamp('1970-01-01', {t '23:59:59'})"); 
-//    }
-//
-//    // Source = TIMESTAMP
-//    
-//    public void testTimestampToString() throws Exception {
-//        Timestamp ts = TimestampUtil.createTimestamp(103, 10, 1, 12, 5, 2, 0);        
-//        helpTest(LANG_FACTORY.createLiteral(ts, Timestamp.class), "string", "char({ts '2003-11-01 12:05:02.0'})"); 
-//    }
-//
-//    public void testTimestampToDate() throws Exception {
-//        Timestamp ts = TimestampUtil.createTimestamp(103, 10, 1, 12, 5, 2, 0);        
-//        helpTest(LANG_FACTORY.createLiteral(ts, Timestamp.class), "date", "date({ts '2003-11-01 12:05:02.0'})"); 
-//    }
-//
-//    public void testTimestampToTime() throws Exception {
-//        Timestamp ts = TimestampUtil.createTimestamp(103, 10, 1, 12, 5, 2, 0);        
-//        helpTest(LANG_FACTORY.createLiteral(ts, Timestamp.class), "time", "time({ts '2003-11-01 12:05:02.0'})"); 
-//    }
-    
-}

Copied: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java (from rev 3382, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaConvertModifier.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,509 @@
+/*
+ * 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 org.teiid.translator.jdbc.netezza;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.LanguageFactory;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+
+
+/**
+ */
+public class TestNetezzaConvertModifier extends TestCase {
+
+    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
+
+    public TestNetezzaConvertModifier(String name) {
+        super(name);
+    }
+
+    public String helpGetString(Expression expr) throws Exception {
+        NetezzaExecutionFactory trans = new NetezzaExecutionFactory();
+        trans.start();
+        SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor(); 
+        sqlVisitor.append(expr);  
+        
+        return sqlVisitor.toString();        
+    }
+
+    public void helpTest(Expression srcExpression, String tgtType, String expectedExpression) throws Exception {
+        Function func = LANG_FACTORY.createFunction("convert",  //$NON-NLS-1$
+            Arrays.asList( 
+                srcExpression,
+                LANG_FACTORY.createLiteral(tgtType, String.class)),
+            TypeFacility.getDataTypeClass(tgtType));
+        
+        assertEquals("Error converting from " + srcExpression.getType() + " to " + tgtType,  
+            expectedExpression, helpGetString(func)); 
+    }
+    
+    
+    
+
+    // Source = STRING
+    public void testStringToChar() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "char", "cast('5' AS char(1))"); 
+    }
+
+    public void testStringToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "boolean", "CASE WHEN '5' IN ('false', '0') THEN '0' WHEN '5' IS NOT NULL THEN '1' END"); 
+    }
+
+    public void testStringToByte() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "byte", "cast('5' AS byteint)"); 
+    }
+
+    public void testStringToShort() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "short", "cast('5' AS smallint)"); 
+    }
+
+    public void testStringToInteger() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "integer", "cast('5' AS integer)"); 
+    }
+
+    public void testStringToLong() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "long", "cast('5' AS bigint)"); 
+    }
+
+    public void testStringToBigInteger() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "biginteger", "cast('5' AS numeric(38))");  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
+    }
+
+    public void testStringToFloat() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "float", "cast('5' AS float)");
+    }
+
+    public void testStringToDouble() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "double", "cast('5' AS double)"); 
+    }
+
+    public void testStringToDate() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("2004-06-29", String.class), "date", "to_date('2004-06-29', 'YYYY-MM-DD')"); 
+    }
+
+    public void testStringToTime() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("23:59:59", String.class), "time", "to_timestamp('23:59:59', 'HH24:MI:SS')"); 
+    }
+
+    public void testStringToTimestamp() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("2004-06-29 23:59:59.987", String.class), "timestamp", "to_timestamp('2004-06-29 23:59:59.987', 'YYYY-MM-DD HH24:MI:SS.MS')"); 
+    }
+
+    public void testStringToBigDecimal() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("5", String.class), "bigdecimal", "cast('5' AS numeric(38,18))"); 
+    }
+
+    // Source = CHAR
+    
+    public void testCharToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Character('5'), Character.class), "string", "'5'"); 
+    }
+
+    // Source = BOOLEAN
+    
+    public void testBooleanToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.TRUE, Boolean.class), "string", "CASE WHEN 1 = '0' THEN 'false' WHEN 1 IS NOT NULL THEN 'true' END"); 
+    }
+
+    public void testBooleanToByte() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "byte", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+
+    public void testBooleanToShort() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "short", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+
+    public void testBooleanToInteger() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "integer", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+
+    public void testBooleanToLong() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "long", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+
+    public void testBooleanToBigInteger() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "biginteger", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+
+    public void testBooleanToFloat() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "float", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+
+    public void testBooleanToDouble() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "double", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+
+    public void testBooleanToBigDecimal() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(Boolean.FALSE, Boolean.class), "bigdecimal", "(CASE WHEN 0 IN ( '0', 'FALSE') THEN 0 WHEN 0 IS NOT NULL THEN 1 END)"); 
+    }
+    
+    // Source = BYTE
+    
+    public void testByteToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "string", "cast(1 AS varchar(4000))"); 
+    }
+
+    public void testByteToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testByteToShort() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "short", "1"); 
+//    }
+//
+//    public void testByteToInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "integer", "integer(1)"); 
+//    }
+//
+//    public void testByteToLong() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "long", "bigint(1)"); 
+//    }
+//
+//    public void testByteToBigInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "biginteger", "cast(1 AS numeric(31,0))"); 
+//    }
+//
+//    public void testByteToFloat() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "float", "cast(1 AS real)"); 
+//    }
+//
+//    public void testByteToDouble() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "double", "double(1)"); 
+//    }
+//
+//    public void testByteToBigDecimal() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
+//    }
+
+    // Source = SHORT
+    
+    public void testShortToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "string", "cast(1 AS varchar(4000))"); 
+    }
+
+    public void testShortToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testShortToByte() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "byte", "1"); 
+//    }
+//
+//    public void testShortToInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "integer", "integer(1)"); 
+//    }
+//
+//    public void testShortToLong() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "long", "bigint(1)"); 
+//    }
+//
+//    public void testShortToBigInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "biginteger", "cast(1 AS numeric(31,0))"); 
+//    }
+//
+//    public void testShortToFloat() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "float", "cast(1 AS real)"); 
+//    }
+//
+//    public void testShortToDouble() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "double", "double(1)"); 
+//    }
+//
+//    public void testShortToBigDecimal() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Short((short)1), Short.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
+//    }
+
+    // Source = INTEGER
+    
+    public void testIntegerToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "string", "cast(1 AS varchar(4000))"); 
+    }
+
+    public void testIntegerToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testIntegerToByte() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "byte", "smallint(1)"); 
+//    }
+//
+//    public void testIntegerToShort() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "short", "smallint(1)"); 
+//    }
+//
+//    public void testIntegerToLong() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "long", "bigint(1)"); 
+//    }
+//
+//    public void testIntegerToBigInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "biginteger", "cast(1 AS numeric(31,0))"); 
+//    }
+//
+//    public void testIntegerToFloat() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "float", "cast(1 AS real)"); 
+//    }
+//
+//    public void testIntegerToDouble() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "double", "double(1)"); 
+//    }
+//
+//    public void testIntegerToBigDecimal() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Integer(1), Integer.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
+//    }
+
+    // Source = LONG
+    
+    public void testLongToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "string", "cast(1 AS varchar(4000))"); 
+    }
+
+    public void testLongToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testLongToByte() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "byte", "smallint(1)"); 
+//    }
+//
+//    public void testLongToShort() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "short", "smallint(1)"); 
+//    }
+//
+//    public void testLongToInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "integer", "integer(1)"); 
+//    }
+//
+//    public void testLongToBigInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "biginteger", "cast(1 AS numeric(31,0))"); 
+//    }
+//
+//    public void testLongToFloat() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "float", "cast(1 AS real)"); 
+//    }
+//
+//    public void testLongToDouble() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "double", "double(1)"); 
+//    }
+//
+//    public void testLongToBigDecimal() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Long(1), Long.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
+//    }
+
+    // Source = BIGINTEGER
+    
+    public void testBigIntegerToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "string", "cast(1 AS varchar(4000))"); 
+    }
+
+    public void testBigIntegerToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "boolean", "CASE WHEN 1 = 0 THEN '0' WHEN 1 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testBigIntegerToByte() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "byte", "smallint(1)"); 
+//    }
+//
+//    public void testBigIntegerToShort() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "short", "smallint(1)"); 
+//    }
+//
+//    public void testBigIntegerToInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "integer", "integer(1)"); 
+//    }
+//
+//    public void testBigIntegerToLong() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "long", "bigint(1)"); 
+//    }
+//
+//    public void testBigIntegerToFloat() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "float", "cast(1 AS real)"); 
+//    }
+//
+//    public void testBigIntegerToDouble() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "double", "double(1)"); 
+//    }
+//
+//    public void testBigIntegerToBigDecimal() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigInteger("1"), BigInteger.class), "bigdecimal", "cast(1 AS numeric(31,12))"); 
+//    }
+
+    // Source = FLOAT
+    
+    public void testFloatToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "string", "cast(1.2 AS varchar(4000))"); 
+    }
+
+    public void testFloatToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "boolean", "CASE WHEN 1.2 = 0 THEN '0' WHEN 1.2 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testFloatToByte() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "byte", "smallint(1.2)"); 
+//    }
+//
+//    public void testFloatToShort() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "short", "smallint(1.2)"); 
+//    }
+//
+//    public void testFloatToInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "integer", "integer(1.2)"); 
+//    }
+//
+//    public void testFloatToLong() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "long", "bigint(1.2)"); 
+//    }
+//
+//    public void testFloatToBigInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "biginteger", "cast(1.2 AS numeric(31,0))"); 
+//    }
+//
+//    public void testFloatToDouble() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "double", "double(1.2)"); 
+//    }
+//
+//    public void testFloatToBigDecimal() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Float(1.2f), Float.class), "bigdecimal", "cast(1.2 AS numeric(31,12))"); 
+//    }
+
+    // Source = DOUBLE
+    
+    public void testDoubleToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "string", "cast(1.2 AS varchar(4000))"); 
+    }
+
+    public void testDoubleToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "boolean", "CASE WHEN 1.2 = 0 THEN '0' WHEN 1.2 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testDoubleToByte() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "byte", "smallint(1.2)"); 
+//    }
+//
+//    public void testDoubleToShort() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "short", "smallint(1.2)"); 
+//    }
+//
+//    public void testDoubleToInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "integer", "integer(1.2)"); 
+//    }
+//
+//    public void testDoubleToLong() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "long", "bigint(1.2)"); 
+//    }
+//
+//    public void testDoubleToBigInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "biginteger", "cast(1.2 AS numeric(31,0))"); 
+//    }
+//
+//    public void testDoubleToFloat() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "float", "cast(1.2 AS real)"); 
+//    }
+//
+//    public void testDoubleToBigDecimal() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new Double(1.2), Double.class), "bigdecimal", "cast(1.2 AS numeric(31,12))"); 
+//    }
+
+    // Source = BIGDECIMAL
+    
+    public void testBigDecimalToString() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "string", "cast(1.0 AS varchar(4000))"); 
+    }
+
+    public void testBigDecimalToBoolean() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "boolean", "CASE WHEN 1.0 = 0 THEN '0' WHEN 1.0 IS NOT NULL THEN '1' END"); 
+    }
+
+//    public void testBigDecimalToByte() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "byte", "smallint(1.0)"); 
+//    }
+//
+//    public void testBigDecimalToShort() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "short", "smallint(1.0)"); 
+//    }
+//
+//    public void testBigDecimalToInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "integer", "integer(1.0)"); 
+//    }
+//
+//    public void testBigDecimalToLong() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "long", "bigint(1.0)"); 
+//    }
+//
+//    public void testBigDecimalToBigInteger() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "biginteger", "cast(1.0 AS numeric(31,0))"); 
+//    }
+//
+//    public void testBigDecimalToFloat() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "float", "cast(1.0 AS real)"); 
+//    }
+//
+//    public void testBigDecimalToDouble() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(new BigDecimal("1.0"), BigDecimal.class), "double", "double(1.0)"); 
+//    }
+
+//    // Source = DATE
+//
+//    public void testDateToString() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createDate(103, 10, 1), java.sql.Date.class), "string", "char({d '2003-11-01'})"); 
+//    }
+//
+//    public void testDateToTimestamp() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createDate(103, 10, 1), java.sql.Date.class), "timestamp", "timestamp({d '2003-11-01'}, '00:00:00')"); 
+//    }
+//
+//    // Source = TIME
+//
+//    public void testTimeToString() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createTime(23, 59, 59), java.sql.Time.class), "string", "char({t '23:59:59'})"); 
+//    }
+//
+//    public void testTimeToTimestamp() throws Exception {
+//        helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createTime(23, 59, 59), java.sql.Time.class), "timestamp", "timestamp('1970-01-01', {t '23:59:59'})"); 
+//    }
+//
+//    // Source = TIMESTAMP
+//    
+//    public void testTimestampToString() throws Exception {
+//        Timestamp ts = TimestampUtil.createTimestamp(103, 10, 1, 12, 5, 2, 0);        
+//        helpTest(LANG_FACTORY.createLiteral(ts, Timestamp.class), "string", "char({ts '2003-11-01 12:05:02.0'})"); 
+//    }
+//
+//    public void testTimestampToDate() throws Exception {
+//        Timestamp ts = TimestampUtil.createTimestamp(103, 10, 1, 12, 5, 2, 0);        
+//        helpTest(LANG_FACTORY.createLiteral(ts, Timestamp.class), "date", "date({ts '2003-11-01 12:05:02.0'})"); 
+//    }
+//
+//    public void testTimestampToTime() throws Exception {
+//        Timestamp ts = TimestampUtil.createTimestamp(103, 10, 1, 12, 5, 2, 0);        
+//        helpTest(LANG_FACTORY.createLiteral(ts, Timestamp.class), "time", "time({ts '2003-11-01 12:05:02.0'})"); 
+//    }
+    
+}

Deleted: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,394 +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 org.teiid.translator.jdbc.netezza;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.teiid.cdk.unittest.FakeTranslationFactory;
-import org.teiid.dqp.internal.datamgr.FakeExecutionContextImpl;
-import org.teiid.language.Command;
-import org.teiid.translator.ExecutionContext;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.jdbc.TranslatedCommand;
-import org.teiid.translator.jdbc.TranslationHelper;
-
-public class TestNetezzaTranslatorCapabilities  extends TestCase {
-
-    private static NetezzaExecutionFactory TRANSLATOR;
-    private static ExecutionContext EMPTY_CONTEXT = new FakeExecutionContextImpl();
-
-    static {
-        try {
-            TRANSLATOR = new NetezzaExecutionFactory();        
-            TRANSLATOR.start();
-        } catch(TranslatorException e) {
-            e.printStackTrace();    
-        }
-    }
-
-    
-    private String getTestBQTVDB() {
-        return TranslationHelper.BQT_VDB; 
-    }
-    
-    public void helpTestVisitor(String input, String expectedOutput) throws TranslatorException {
-        // Convert from sql to objects
-        Command obj = FakeTranslationFactory.getInstance().getBQTTranslationUtility().parseCommand(input);
-        
-        TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), TRANSLATOR);
-        tc.translateCommand(obj);
-        
-        
-        // Check stuff
-        assertEquals("Did not get correct sql", expectedOutput, tc.getSql());             
-    }
-
-
-    /////////BASIC TEST CASES FOR CAPABILITIES/////////////
-    /////////////////////////////////////////////////
-    @Test
-    public void testRowLimit() throws Exception {
-        String input = "select intkey from bqt1.smalla limit 100"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA LIMIT 100";  
-
-        helpTestVisitor(
-            input, 
-            output);
-
-    }
-    @Test
-    public void testSelectDistinct() throws Exception {
-        String input = "select distinct intkey from bqt1.smalla limit 100"; 
-        String output = "SELECT DISTINCT SmallA.IntKey FROM SmallA LIMIT 100";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    @Test
-    public void testSelectExpression() throws Exception {
-        String input = "select  intkey, intkey + longnum / 2 as test from bqt1.smalla"; 
-        String output = "SELECT SmallA.IntKey, (SmallA.IntKey + (SmallA.LongNum / 2)) AS test FROM SmallA";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    
-    public void testBetweenCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where intnum BETWEEN 2 AND 10"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum >= 2 AND SmallA.IntNum <= 10";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    public void testCompareCriteriaEquals() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where intnum = 10"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum = 10";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    public void testCompareCriteriaOrdered() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where intnum < 10"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum < 10";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    public void testLikeCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where stringkey like '4%'"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey LIKE '4%'";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    public void testLikeWithEscapeCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where stringkey like '4\\%'"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey LIKE '4\\%'";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-
-    public void testInCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where stringkey IN ('10', '11', '12')"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey IN ('10', '11', '12')";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    public void testInCriteriaSubQuery() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where stringkey IN (select stringkey from bqt1.smalla where intkey < 10)"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey IN (SELECT SmallA.StringKey FROM SmallA WHERE SmallA.IntKey < 10)";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-
-    public void testIsNullCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where intnum IS NULL"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum IS NULL";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    public void testOrCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where intnum < 2 OR intnum > 10"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum < 2 OR SmallA.IntNum > 10";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    @Test public void testIsNotNullCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where intnum IS NOT NULL"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum IS NOT NULL";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-
-    @Test public void testExistsCriteria() throws Exception {
-        String input = "select  intkey, intnum from bqt1.smalla where exists (select intkey from bqt1.smallb)"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE EXISTS (SELECT SmallB.IntKey FROM SmallB LIMIT 1)";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    @Test public void testHavingClauseCriteria() throws Exception {
-        String input = "SELECT INTKEY FROM BQT1.SMALLA GROUP BY INTKEY HAVING INTKEY = (SELECT INTKEY FROM BQT1.SMALLA WHERE STRINGKEY = 20)"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA GROUP BY SmallA.IntKey HAVING SmallA.IntKey = (SELECT SmallA.IntKey FROM SmallA WHERE SmallA.StringKey = '20' LIMIT 2)";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    
-    @Test public void testScalarSubQuery() throws Exception {
-        String input = "select intkey, intnum from bqt1.smalla where intnum < (0.01 * (select sum(intnum) from bqt1.smalla ))"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum < (0.010000000000000 * (SELECT SUM(SmallA.IntNum) FROM SmallA))";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-
-    @Test public void testSimpleCaseExpression() throws Exception {
-        String input = "SELECT stringnum,  intnum,  CASE  BOOLEANVALUE  WHEN 'true'  then 'true' WHEN false THEN 'FALSE' ELSE 'GOOD' END    FROM bqt1.smalla;"; 
-        String output = "SELECT SmallA.StringNum, SmallA.IntNum, CASE WHEN SmallA.BooleanValue = 1 THEN 'true' WHEN SmallA.BooleanValue = 0 THEN 'FALSE' ELSE 'GOOD' END FROM SmallA";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-
-    @Test public void testSearchedCaseExpression() throws Exception {
-        String input = "SELECT AVG(CASE WHEN intnum > 10 THEN intnum ELSE intkey END) \"Average\" FROM bqt1.smalla"; 
-        String output = "SELECT AVG(CASE WHEN SmallA.IntNum > 10 THEN SmallA.IntNum ELSE SmallA.IntKey END) AS Average FROM SmallA";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
- 
-//    @Test public void testQuantifiedCompareSOMEorANY() throws Exception {
-//        String input = "SELECT INTKEY, BYTENUM FROM BQT1.SmallA WHERE BYTENUM = ANY (SELECT BYTENUM FROM BQT1.SmallA WHERE BYTENUM >= '-108')"; 
-//        String output = "SELECT SmallA.IntKey, SmallA.ByteNum FROM SmallA WHERE SmallA.ByteNum = SOME (SELECT SmallA.ByteNum FROM SmallA WHERE SmallA.ByteNum >= -108)";  
-//
-//        helpTestVisitor(
-//            input, 
-//            output);
-//    }
-      
-    @Test public void testQuantifiedCompareALL() throws Exception {
-        String input = "SELECT INTKEY, STRINGKEY FROM BQT1.SMALLA WHERE STRINGKEY = ALL (SELECT STRINGKEY FROM BQT1.SMALLA WHERE INTKEY = 40)"; 
-        String output = "SELECT SmallA.IntKey, SmallA.StringKey FROM SmallA WHERE SmallA.StringKey = ALL (SELECT SmallA.StringKey FROM SmallA WHERE SmallA.IntKey = 40)";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-    
-    @Test public void testSelfJoin() throws Exception {
-        String input = "SELECT x.intnum, y.intkey  FROM bqt1.smalla x, bqt1.smalla y   WHERE x.stringnum = y.intnum;"; 
-        String output = "SELECT x.IntNum, y.IntKey FROM SmallA AS x, SmallA AS y WHERE x.StringNum = cast(y.IntNum AS varchar(4000))";  
-
-        helpTestVisitor(
-            input, 
-            output);
-    }
-
-    @Test public void testLimitWithNestedInlineView() throws Exception {
-        String input = "select max(intkey), stringkey from (select intkey, stringkey from bqt1.smalla order by intkey limit 100) x group by stringkey"; 
-        String output = "SELECT MAX(x.intkey), x.stringkey FROM (SELECT SmallA.IntKey, SmallA.StringKey FROM SmallA ORDER BY SmallA.IntKey LIMIT 100) AS x GROUP BY x.stringkey"; 
-               
-        helpTestVisitor( input, output);   
-    }
-    
-    @Test public void testAggregatesAndEnhancedNumeric() throws Exception {
-        String input = "select count(*), min(intkey), max(intkey), sum(intkey), avg(intkey), count(intkey), STDDEV_SAMP(intkey), STDDEV_POP(intkey), VAR_SAMP(intkey), VAR_POP(intkey) from bqt1.smalla"; 
-        String output = "SELECT COUNT(*), MIN(SmallA.IntKey), MAX(SmallA.IntKey), SUM(SmallA.IntKey), AVG(SmallA.IntKey), COUNT(SmallA.IntKey), STDDEV_SAMP(SmallA.IntKey), STDDEV_POP(SmallA.IntKey), VAR_SAMP(SmallA.IntKey), VAR_POP(SmallA.IntKey) FROM SmallA"; 
-               
-        helpTestVisitor( input, output);   
-    }
-    @Test public void testAggregatesDistinct() throws Exception {
-        String input = "select avg(DISTINCT intnum) from bqt1.smalla"; 
-        String output = "SELECT AVG(DISTINCT SmallA.IntNum) FROM SmallA"; 
-               
-        helpTestVisitor( input, output);   
-    }
-
-    
-    @Test public void testExceptAsMinus() throws Exception {
-        String input = "select intkey, intnum from bqt1.smalla except select intnum, intkey from bqt1.smallb"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA EXCEPT SELECT SmallB.IntNum, SmallB.IntKey FROM SmallB"; 
-               
-        helpTestVisitor( input, output);   
-    }
-    
-    @Test public void testUnionAsPlus() throws Exception {
-        String input = "select intkey, intnum from bqt1.smalla union select intnum, intkey from bqt1.smallb"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA UNION SELECT SmallB.IntNum, SmallB.IntKey FROM SmallB"; 
-               
-        helpTestVisitor( input, output);   
-    }
-    @Test public void testUnionAllAsPlus() throws Exception {
-        String input = "select intkey, intnum from bqt1.smalla union all select intnum, intkey from bqt1.smallb"; 
-        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA UNION ALL SELECT SmallB.IntNum, SmallB.IntKey FROM SmallB"; 
-               
-        helpTestVisitor( input, output);   
-    }
-    
-    @Test public void testUnionAllAsPlusWithAggregates() throws Exception {
-        String input = "select intkey, Sum(intnum) from bqt1.smalla group by intkey union all select intnum, intkey from bqt1.smallb"; 
-        String output = "SELECT SmallA.IntKey, SUM(SmallA.IntNum) FROM SmallA GROUP BY SmallA.IntKey UNION ALL SELECT SmallB.IntNum, SmallB.IntKey AS IntKey FROM SmallB"; 
-               
-        helpTestVisitor( input, output);   
-    }
-
-
-    @Test public void testintersect() throws Exception {
-         String input = "select intkey from bqt1.smalla where intkey < 20 INTERSECT select intkey from bqt1.smalla where intkey > 10";
-         String output = "SELECT SmallA.IntKey FROM SmallA WHERE SmallA.IntKey < 20 INTERSECT SELECT SmallA.IntKey FROM SmallA WHERE SmallA.IntKey > 10"; 
-        
-        
-        helpTestVisitor( input, output);   
-    }
-
-   
-    @Test public void testUnionOrderBy() throws Exception {
-        String input = "(select intkey from bqt1.smalla) union select intnum from bqt1.smalla order by intkey"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA UNION SELECT SmallA.IntNum FROM SmallA ORDER BY intkey";
-               
-        helpTestVisitor( input, output);   
-
-    }
-
-    @Test public void testIntersectOrderBy() throws Exception {
-        String input = "(select intkey from bqt1.smalla) intersect select intnum from bqt1.smalla order by intkey"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA INTERSECT SELECT SmallA.IntNum FROM SmallA ORDER BY intkey";
-               
-        helpTestVisitor( input, output);   
-
-    }
-    
-    @Test public void testExceptOrderBy() throws Exception {
-        String input = "(select intkey from bqt1.smalla) except select intnum from bqt1.smalla order by intkey"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA EXCEPT SELECT SmallA.IntNum FROM SmallA ORDER BY intkey";
-               
-        helpTestVisitor( input, output);   
-
-    }
-
-    
-    @Test public void testRowLimitOFFSET() throws Exception {
-        String input = "select intkey from bqt1.smalla limit 20, 30"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA LIMIT 30 OFFSET 20"; 
-               
-        helpTestVisitor( input, output);        
-    }   
-    
-    
-    @Test public void testOrderByNullsFirstLast() throws Exception {
-        String input = "select intkey,  longnum from  bqt1.smalla order by longnum NULLS LAST"; 
-        String output = "SELECT SmallA.IntKey, SmallA.LongNum FROM SmallA ORDER BY SmallA.LongNum NULLS LAST"; 
-               
-        helpTestVisitor( input, output);        
-    }   
-
-    @Test public void testOrderByUnRelated() throws Exception {
-        String input = "select intkey,  longnum from  bqt1.smalla order by floatnum"; 
-        String output = "SELECT SmallA.IntKey, SmallA.LongNum FROM SmallA ORDER BY SmallA.FloatNum"; 
-               
-        helpTestVisitor( input, output);        
-    }   
-    
-    
-    @Test public void testInnerJoin() throws Exception {
-        String input = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.IntKey = BQT2.SmallB.IntKey AND BQT1.SmallA.IntKey >= 0 AND BQT2.SmallB.IntKey >= 0 ORDER BY BQT1.SmallA.IntKey"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA, SmallB WHERE SmallA.IntKey = SmallB.IntKey AND SmallA.IntKey >= 0 AND SmallB.IntKey >= 0 ORDER BY SmallA.IntKey"; 
-               
-        helpTestVisitor( input, output);        
-    }   
-
-    
-    @Test public void testOuterJoin() throws Exception {
-        String input = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.IntKey = BQT2.SmallB.IntKey AND BQT1.SmallA.IntKey >= 0 AND BQT2.SmallB.IntKey >= 0 ORDER BY BQT1.SmallA.IntKey"; 
-        String output = "SELECT SmallA.IntKey FROM SmallA, SmallB WHERE SmallA.IntKey = SmallB.IntKey AND SmallA.IntKey >= 0 AND SmallB.IntKey >= 0 ORDER BY SmallA.IntKey"; 
-               
-        helpTestVisitor( input, output);        
-    }   
-
-    @Test public void testFullOuterJoin() throws Exception {
-        String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.IntNum FROM BQT1.SmallA FULL OUTER JOIN BQT2.SmallB ON BQT1.SmallA.IntNum = BQT2.SmallB.IntNum ORDER BY BQT1.SmallA.IntNum"; 
-        String output = "SELECT SmallA.IntNum, SmallB.IntNum FROM SmallA FULL OUTER JOIN SmallB ON SmallA.IntNum = SmallB.IntNum ORDER BY SmallA.IntNum"; 
-               
-        helpTestVisitor( input, output);        
-    }   
-
-    @Test public void testRightOuterJoin() throws Exception {
-        String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.IntNum FROM BQT1.SmallA RIGHT OUTER JOIN BQT2.SmallB ON BQT1.SmallA.IntNum = BQT2.SmallB.IntNum ORDER BY BQT2.SmallB.IntNum";
-        String output= "SELECT SmallA.IntNum, SmallB.IntNum FROM SmallB LEFT OUTER JOIN SmallA ON SmallA.IntNum = SmallB.IntNum ORDER BY SmallB.IntNum";
-               
-        helpTestVisitor( input, output);        
-    }   
-    @Test public void testLeftOuterJoin() throws Exception {
-        String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.IntNum FROM BQT1.SmallA LEFT OUTER JOIN BQT2.SmallB ON BQT1.SmallA.IntNum = BQT2.SmallB.IntNum ORDER BY BQT1.SmallA.IntNum"; 
-        String output = "SELECT SmallA.IntNum, SmallB.IntNum FROM SmallA LEFT OUTER JOIN SmallB ON SmallA.IntNum = SmallB.IntNum ORDER BY SmallA.IntNum"; 
-               
-        helpTestVisitor( input, output);        
-    }   
-    
-}

Copied: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java (from rev 3382, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorCapabilities.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,394 @@
+/*
+ * 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 org.teiid.translator.jdbc.netezza;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.teiid.cdk.unittest.FakeTranslationFactory;
+import org.teiid.dqp.internal.datamgr.FakeExecutionContextImpl;
+import org.teiid.language.Command;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.jdbc.TranslatedCommand;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+public class TestNetezzaTranslatorCapabilities  extends TestCase {
+
+    private static NetezzaExecutionFactory TRANSLATOR;
+    private static ExecutionContext EMPTY_CONTEXT = new FakeExecutionContextImpl();
+
+    static {
+        try {
+            TRANSLATOR = new NetezzaExecutionFactory();        
+            TRANSLATOR.start();
+        } catch(TranslatorException e) {
+            e.printStackTrace();    
+        }
+    }
+
+    
+    private String getTestBQTVDB() {
+        return TranslationHelper.BQT_VDB; 
+    }
+    
+    public void helpTestVisitor(String input, String expectedOutput) throws TranslatorException {
+        // Convert from sql to objects
+        Command obj = FakeTranslationFactory.getInstance().getBQTTranslationUtility().parseCommand(input);
+        
+        TranslatedCommand tc = new TranslatedCommand(Mockito.mock(ExecutionContext.class), TRANSLATOR);
+        tc.translateCommand(obj);
+        
+        
+        // Check stuff
+        assertEquals("Did not get correct sql", expectedOutput, tc.getSql());             
+    }
+
+
+    /////////BASIC TEST CASES FOR CAPABILITIES/////////////
+    /////////////////////////////////////////////////
+    @Test
+    public void testRowLimit() throws Exception {
+        String input = "select intkey from bqt1.smalla limit 100"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA LIMIT 100";  
+
+        helpTestVisitor(
+            input, 
+            output);
+
+    }
+    @Test
+    public void testSelectDistinct() throws Exception {
+        String input = "select distinct intkey from bqt1.smalla limit 100"; 
+        String output = "SELECT DISTINCT SmallA.IntKey FROM SmallA LIMIT 100";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    @Test
+    public void testSelectExpression() throws Exception {
+        String input = "select  intkey, intkey + longnum / 2 as test from bqt1.smalla"; 
+        String output = "SELECT SmallA.IntKey, (SmallA.IntKey + (SmallA.LongNum / 2)) AS test FROM SmallA";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    
+    public void testBetweenCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where intnum BETWEEN 2 AND 10"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum >= 2 AND SmallA.IntNum <= 10";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    public void testCompareCriteriaEquals() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where intnum = 10"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum = 10";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    public void testCompareCriteriaOrdered() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where intnum < 10"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum < 10";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    public void testLikeCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where stringkey like '4%'"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey LIKE '4%'";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    public void testLikeWithEscapeCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where stringkey like '4\\%'"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey LIKE '4\\%'";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+
+    public void testInCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where stringkey IN ('10', '11', '12')"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey IN ('10', '11', '12')";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    public void testInCriteriaSubQuery() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where stringkey IN (select stringkey from bqt1.smalla where intkey < 10)"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.StringKey IN (SELECT SmallA.StringKey FROM SmallA WHERE SmallA.IntKey < 10)";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+
+    public void testIsNullCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where intnum IS NULL"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum IS NULL";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    public void testOrCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where intnum < 2 OR intnum > 10"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum < 2 OR SmallA.IntNum > 10";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    @Test public void testIsNotNullCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where intnum IS NOT NULL"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum IS NOT NULL";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+
+    @Test public void testExistsCriteria() throws Exception {
+        String input = "select  intkey, intnum from bqt1.smalla where exists (select intkey from bqt1.smallb)"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE EXISTS (SELECT SmallB.IntKey FROM SmallB LIMIT 1)";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    @Test public void testHavingClauseCriteria() throws Exception {
+        String input = "SELECT INTKEY FROM BQT1.SMALLA GROUP BY INTKEY HAVING INTKEY = (SELECT INTKEY FROM BQT1.SMALLA WHERE STRINGKEY = 20)"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA GROUP BY SmallA.IntKey HAVING SmallA.IntKey = (SELECT SmallA.IntKey FROM SmallA WHERE SmallA.StringKey = '20' LIMIT 2)";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    
+    @Test public void testScalarSubQuery() throws Exception {
+        String input = "select intkey, intnum from bqt1.smalla where intnum < (0.01 * (select sum(intnum) from bqt1.smalla ))"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA WHERE SmallA.IntNum < (0.010000000000000 * (SELECT SUM(SmallA.IntNum) FROM SmallA))";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+
+    @Test public void testSimpleCaseExpression() throws Exception {
+        String input = "SELECT stringnum,  intnum,  CASE  BOOLEANVALUE  WHEN 'true'  then 'true' WHEN false THEN 'FALSE' ELSE 'GOOD' END    FROM bqt1.smalla;"; 
+        String output = "SELECT SmallA.StringNum, SmallA.IntNum, CASE WHEN SmallA.BooleanValue = 1 THEN 'true' WHEN SmallA.BooleanValue = 0 THEN 'FALSE' ELSE 'GOOD' END FROM SmallA";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+
+    @Test public void testSearchedCaseExpression() throws Exception {
+        String input = "SELECT AVG(CASE WHEN intnum > 10 THEN intnum ELSE intkey END) \"Average\" FROM bqt1.smalla"; 
+        String output = "SELECT AVG(CASE WHEN SmallA.IntNum > 10 THEN SmallA.IntNum ELSE SmallA.IntKey END) AS Average FROM SmallA";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+ 
+//    @Test public void testQuantifiedCompareSOMEorANY() throws Exception {
+//        String input = "SELECT INTKEY, BYTENUM FROM BQT1.SmallA WHERE BYTENUM = ANY (SELECT BYTENUM FROM BQT1.SmallA WHERE BYTENUM >= '-108')"; 
+//        String output = "SELECT SmallA.IntKey, SmallA.ByteNum FROM SmallA WHERE SmallA.ByteNum = SOME (SELECT SmallA.ByteNum FROM SmallA WHERE SmallA.ByteNum >= -108)";  
+//
+//        helpTestVisitor(
+//            input, 
+//            output);
+//    }
+      
+    @Test public void testQuantifiedCompareALL() throws Exception {
+        String input = "SELECT INTKEY, STRINGKEY FROM BQT1.SMALLA WHERE STRINGKEY = ALL (SELECT STRINGKEY FROM BQT1.SMALLA WHERE INTKEY = 40)"; 
+        String output = "SELECT SmallA.IntKey, SmallA.StringKey FROM SmallA WHERE SmallA.StringKey = ALL (SELECT SmallA.StringKey FROM SmallA WHERE SmallA.IntKey = 40)";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+    
+    @Test public void testSelfJoin() throws Exception {
+        String input = "SELECT x.intnum, y.intkey  FROM bqt1.smalla x, bqt1.smalla y   WHERE x.stringnum = y.intnum;"; 
+        String output = "SELECT x.IntNum, y.IntKey FROM SmallA AS x, SmallA AS y WHERE x.StringNum = cast(y.IntNum AS varchar(4000))";  
+
+        helpTestVisitor(
+            input, 
+            output);
+    }
+
+    @Test public void testLimitWithNestedInlineView() throws Exception {
+        String input = "select max(intkey), stringkey from (select intkey, stringkey from bqt1.smalla order by intkey limit 100) x group by stringkey"; 
+        String output = "SELECT MAX(x.intkey), x.stringkey FROM (SELECT SmallA.IntKey, SmallA.StringKey FROM SmallA ORDER BY SmallA.IntKey LIMIT 100) AS x GROUP BY x.stringkey"; 
+               
+        helpTestVisitor( input, output);   
+    }
+    
+    @Test public void testAggregatesAndEnhancedNumeric() throws Exception {
+        String input = "select count(*), min(intkey), max(intkey), sum(intkey), avg(intkey), count(intkey), STDDEV_SAMP(intkey), STDDEV_POP(intkey), VAR_SAMP(intkey), VAR_POP(intkey) from bqt1.smalla"; 
+        String output = "SELECT COUNT(*), MIN(SmallA.IntKey), MAX(SmallA.IntKey), SUM(SmallA.IntKey), AVG(SmallA.IntKey), COUNT(SmallA.IntKey), STDDEV_SAMP(SmallA.IntKey), STDDEV_POP(SmallA.IntKey), VAR_SAMP(SmallA.IntKey), VAR_POP(SmallA.IntKey) FROM SmallA"; 
+               
+        helpTestVisitor( input, output);   
+    }
+    @Test public void testAggregatesDistinct() throws Exception {
+        String input = "select avg(DISTINCT intnum) from bqt1.smalla"; 
+        String output = "SELECT AVG(DISTINCT SmallA.IntNum) FROM SmallA"; 
+               
+        helpTestVisitor( input, output);   
+    }
+
+    
+    @Test public void testExceptAsMinus() throws Exception {
+        String input = "select intkey, intnum from bqt1.smalla except select intnum, intkey from bqt1.smallb"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA EXCEPT SELECT SmallB.IntNum, SmallB.IntKey FROM SmallB"; 
+               
+        helpTestVisitor( input, output);   
+    }
+    
+    @Test public void testUnionAsPlus() throws Exception {
+        String input = "select intkey, intnum from bqt1.smalla union select intnum, intkey from bqt1.smallb"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA UNION SELECT SmallB.IntNum, SmallB.IntKey FROM SmallB"; 
+               
+        helpTestVisitor( input, output);   
+    }
+    @Test public void testUnionAllAsPlus() throws Exception {
+        String input = "select intkey, intnum from bqt1.smalla union all select intnum, intkey from bqt1.smallb"; 
+        String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA UNION ALL SELECT SmallB.IntNum, SmallB.IntKey FROM SmallB"; 
+               
+        helpTestVisitor( input, output);   
+    }
+    
+    @Test public void testUnionAllAsPlusWithAggregates() throws Exception {
+        String input = "select intkey, Sum(intnum) from bqt1.smalla group by intkey union all select intnum, intkey from bqt1.smallb"; 
+        String output = "SELECT SmallA.IntKey, SUM(SmallA.IntNum) FROM SmallA GROUP BY SmallA.IntKey UNION ALL SELECT SmallB.IntNum, SmallB.IntKey AS IntKey FROM SmallB"; 
+               
+        helpTestVisitor( input, output);   
+    }
+
+
+    @Test public void testintersect() throws Exception {
+         String input = "select intkey from bqt1.smalla where intkey < 20 INTERSECT select intkey from bqt1.smalla where intkey > 10";
+         String output = "SELECT SmallA.IntKey FROM SmallA WHERE SmallA.IntKey < 20 INTERSECT SELECT SmallA.IntKey FROM SmallA WHERE SmallA.IntKey > 10"; 
+        
+        
+        helpTestVisitor( input, output);   
+    }
+
+   
+    @Test public void testUnionOrderBy() throws Exception {
+        String input = "(select intkey from bqt1.smalla) union select intnum from bqt1.smalla order by intkey"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA UNION SELECT SmallA.IntNum FROM SmallA ORDER BY intkey";
+               
+        helpTestVisitor( input, output);   
+
+    }
+
+    @Test public void testIntersectOrderBy() throws Exception {
+        String input = "(select intkey from bqt1.smalla) intersect select intnum from bqt1.smalla order by intkey"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA INTERSECT SELECT SmallA.IntNum FROM SmallA ORDER BY intkey";
+               
+        helpTestVisitor( input, output);   
+
+    }
+    
+    @Test public void testExceptOrderBy() throws Exception {
+        String input = "(select intkey from bqt1.smalla) except select intnum from bqt1.smalla order by intkey"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA EXCEPT SELECT SmallA.IntNum FROM SmallA ORDER BY intkey";
+               
+        helpTestVisitor( input, output);   
+
+    }
+
+    
+    @Test public void testRowLimitOFFSET() throws Exception {
+        String input = "select intkey from bqt1.smalla limit 20, 30"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA LIMIT 30 OFFSET 20"; 
+               
+        helpTestVisitor( input, output);        
+    }   
+    
+    
+    @Test public void testOrderByNullsFirstLast() throws Exception {
+        String input = "select intkey,  longnum from  bqt1.smalla order by longnum NULLS LAST"; 
+        String output = "SELECT SmallA.IntKey, SmallA.LongNum FROM SmallA ORDER BY SmallA.LongNum NULLS LAST"; 
+               
+        helpTestVisitor( input, output);        
+    }   
+
+    @Test public void testOrderByUnRelated() throws Exception {
+        String input = "select intkey,  longnum from  bqt1.smalla order by floatnum"; 
+        String output = "SELECT SmallA.IntKey, SmallA.LongNum FROM SmallA ORDER BY SmallA.FloatNum"; 
+               
+        helpTestVisitor( input, output);        
+    }   
+    
+    
+    @Test public void testInnerJoin() throws Exception {
+        String input = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.IntKey = BQT2.SmallB.IntKey AND BQT1.SmallA.IntKey >= 0 AND BQT2.SmallB.IntKey >= 0 ORDER BY BQT1.SmallA.IntKey"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA, SmallB WHERE SmallA.IntKey = SmallB.IntKey AND SmallA.IntKey >= 0 AND SmallB.IntKey >= 0 ORDER BY SmallA.IntKey"; 
+               
+        helpTestVisitor( input, output);        
+    }   
+
+    
+    @Test public void testOuterJoin() throws Exception {
+        String input = "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.IntKey = BQT2.SmallB.IntKey AND BQT1.SmallA.IntKey >= 0 AND BQT2.SmallB.IntKey >= 0 ORDER BY BQT1.SmallA.IntKey"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA, SmallB WHERE SmallA.IntKey = SmallB.IntKey AND SmallA.IntKey >= 0 AND SmallB.IntKey >= 0 ORDER BY SmallA.IntKey"; 
+               
+        helpTestVisitor( input, output);        
+    }   
+
+    @Test public void testFullOuterJoin() throws Exception {
+        String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.IntNum FROM BQT1.SmallA FULL OUTER JOIN BQT2.SmallB ON BQT1.SmallA.IntNum = BQT2.SmallB.IntNum ORDER BY BQT1.SmallA.IntNum"; 
+        String output = "SELECT SmallA.IntNum, SmallB.IntNum FROM SmallA FULL OUTER JOIN SmallB ON SmallA.IntNum = SmallB.IntNum ORDER BY SmallA.IntNum"; 
+               
+        helpTestVisitor( input, output);        
+    }   
+
+    @Test public void testRightOuterJoin() throws Exception {
+        String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.IntNum FROM BQT1.SmallA RIGHT OUTER JOIN BQT2.SmallB ON BQT1.SmallA.IntNum = BQT2.SmallB.IntNum ORDER BY BQT2.SmallB.IntNum";
+        String output= "SELECT SmallA.IntNum, SmallB.IntNum FROM SmallB LEFT OUTER JOIN SmallA ON SmallA.IntNum = SmallB.IntNum ORDER BY SmallB.IntNum";
+               
+        helpTestVisitor( input, output);        
+    }   
+    @Test public void testLeftOuterJoin() throws Exception {
+        String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.IntNum FROM BQT1.SmallA LEFT OUTER JOIN BQT2.SmallB ON BQT1.SmallA.IntNum = BQT2.SmallB.IntNum ORDER BY BQT1.SmallA.IntNum"; 
+        String output = "SELECT SmallA.IntNum, SmallB.IntNum FROM SmallA LEFT OUTER JOIN SmallB ON SmallA.IntNum = SmallB.IntNum ORDER BY SmallA.IntNum"; 
+               
+        helpTestVisitor( input, output);        
+    }   
+    
+}

Deleted: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,141 +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 org.teiid.translator.jdbc.netezza;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.LanguageFactory;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.SQLConversionVisitor;
-import org.teiid.translator.jdbc.TranslationHelper;
-
-/**
- */
-public class TestNetezzaTranslatorDatetimeConversion {
-
-    private static NetezzaExecutionFactory TRANSLATOR; 
-    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
-
-    @BeforeClass public static void oneTimeSetup() throws TranslatorException {
-        TRANSLATOR = new NetezzaExecutionFactory();       
-        TRANSLATOR.setUseBindVariables(false);
-        TRANSLATOR.start();
-        
-
-    }
-    
-    /////////////////UTILLITY FUNCTIONS/////////
-    ////////////////////////////////////////////
-
-    private String getTestVDB() {
-        //return TranslationHelper.NETEZZA_VDB;
-    	return TranslationHelper.PARTS_VDB;
-    }
-    
-    private String getTestBQTVDB() {
-        return TranslationHelper.BQT_VDB; 
-    }
-    
-    public void helpTest(Expression srcExpression, String tgtType, String expectedExpression) throws Exception {
-        Function func = LANG_FACTORY.createFunction("convert",  
-            Arrays.asList( srcExpression,LANG_FACTORY.createLiteral(tgtType, String.class)),TypeFacility.getDataTypeClass(tgtType));
-        
-        assertEquals("Error converting from " + srcExpression.getType() + " to " + tgtType, 
-            expectedExpression, helpGetString(func)); 
-    }    
-    public String helpGetString(Expression expr) throws Exception {
-        SQLConversionVisitor sqlVisitor = TRANSLATOR.getSQLConversionVisitor(); 
-        sqlVisitor.append(expr);  
-        
-        return sqlVisitor.toString();        
-    }  
-
-    
-     ///////////////DATE/TIME CONVERSION TESTCASES///////
-     ////////////////////////////////////////////////////
-     
-    @Test public void testdayofmonth() throws Exception {
-        String input = "SELECT dayofmonth(datevalue) FROM BQT1.SMALLA"; 
-        String output = "SELECT extract(DAY from SmallA.DateValue) FROM SmallA"; 
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
-    }
-
-
-     ///BEGIN--FROM TIMESTAMP->DATE, TIME, STRING////////
-     @Test public void testTimestampToDate() throws Exception {
-         String input = "SELECT convert(convert(TIMESTAMPVALUE, date), string) FROM BQT1.SMALLA"; 
-         String output = "SELECT cast(cast(SmallA.TimestampValue AS DATE) AS varchar(4000)) FROM SmallA";  
-
-         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
-     }
-     @Test public void testTimestampToTime() throws Exception {
-         String input = "SELECT convert(convert(TIMESTAMPVALUE, time), string) FROM BQT1.SMALLA"; 
-         String output = "SELECT cast(cast(SmallA.TimestampValue AS TIME) AS varchar(4000)) FROM SmallA";  
-
-         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
-     }
-
-     @Test public void testTimestampToString() throws Exception {
-		  String input = "SELECT convert(timestampvalue, string) FROM BQT1.SMALLA"; 
-		  String output = "SELECT to_char(SmallA.TimestampValue, 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";  
-		
-	      TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
-	  }
-     ///END--FROM TIMESTAMP->DATE, TIME, STRING////////
-
-     ///BEGIN--FROM DATE->TIMESTAMP////////
-     @Test public void testDateToTimestamp() throws Exception {
-         String input = "SELECT convert(convert(datevalue, timestamp), string) FROM BQT1.SMALLA"; 
-         String output = "SELECT to_char(cast(SmallA.DateValue AS TIMESTAMP), 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";  
-
-         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
-     }
-     ///END--FROM DATE->TIMESTAMP////////
-
-     ///BEGIN--FROM TIME->TIMESTAMP////////
-     @Test public void testTimeToTimestamp() throws Exception {
-         String input = "SELECT convert(convert(TIMEVALUE, timestamp), string) FROM BQT1.SMALLA"; 
-         //String output = "SELECT to_char(cast(SmallA.TimeValue AS timestamp), 'YYYY-MM-DD HH24:MI:SS.FF') FROM SmallA";
-         String output = "SELECT to_char(SmallA.TimeValue, 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";
-
-         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output,     TRANSLATOR);
-     }
-     ///END--FROM TIME->TIMESTAMP////////
-     
-     
-//     @Test public void testTimestampToTime() throws Exception {
-//      	helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createTimestamp(111, 4, 5, 9, 16, 34, 220000000), Timestamp.class), "TIME", "cast(cast('2011-05-05 09:16:34.22' AS TIMESTAMP(6)) AS TIME)");
-//      }
-
-     
-     
-    
-}

Copied: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java (from rev 3382, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorDatetimeConversion.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,141 @@
+/*
+ * 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 org.teiid.translator.jdbc.netezza;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.LanguageFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+/**
+ */
+public class TestNetezzaTranslatorDatetimeConversion {
+
+    private static NetezzaExecutionFactory TRANSLATOR; 
+    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
+
+    @BeforeClass public static void oneTimeSetup() throws TranslatorException {
+        TRANSLATOR = new NetezzaExecutionFactory();       
+        TRANSLATOR.setUseBindVariables(false);
+        TRANSLATOR.start();
+        
+
+    }
+    
+    /////////////////UTILLITY FUNCTIONS/////////
+    ////////////////////////////////////////////
+
+    private String getTestVDB() {
+        //return TranslationHelper.NETEZZA_VDB;
+    	return TranslationHelper.PARTS_VDB;
+    }
+    
+    private String getTestBQTVDB() {
+        return TranslationHelper.BQT_VDB; 
+    }
+    
+    public void helpTest(Expression srcExpression, String tgtType, String expectedExpression) throws Exception {
+        Function func = LANG_FACTORY.createFunction("convert",  
+            Arrays.asList( srcExpression,LANG_FACTORY.createLiteral(tgtType, String.class)),TypeFacility.getDataTypeClass(tgtType));
+        
+        assertEquals("Error converting from " + srcExpression.getType() + " to " + tgtType, 
+            expectedExpression, helpGetString(func)); 
+    }    
+    public String helpGetString(Expression expr) throws Exception {
+        SQLConversionVisitor sqlVisitor = TRANSLATOR.getSQLConversionVisitor(); 
+        sqlVisitor.append(expr);  
+        
+        return sqlVisitor.toString();        
+    }  
+
+    
+     ///////////////DATE/TIME CONVERSION TESTCASES///////
+     ////////////////////////////////////////////////////
+     
+    @Test public void testdayofmonth() throws Exception {
+        String input = "SELECT dayofmonth(datevalue) FROM BQT1.SMALLA"; 
+        String output = "SELECT extract(DAY from SmallA.DateValue) FROM SmallA"; 
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
+    }
+
+
+     ///BEGIN--FROM TIMESTAMP->DATE, TIME, STRING////////
+     @Test public void testTimestampToDate() throws Exception {
+         String input = "SELECT convert(convert(TIMESTAMPVALUE, date), string) FROM BQT1.SMALLA"; 
+         String output = "SELECT cast(cast(SmallA.TimestampValue AS DATE) AS varchar(4000)) FROM SmallA";  
+
+         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
+     }
+     @Test public void testTimestampToTime() throws Exception {
+         String input = "SELECT convert(convert(TIMESTAMPVALUE, time), string) FROM BQT1.SMALLA"; 
+         String output = "SELECT cast(cast(SmallA.TimestampValue AS TIME) AS varchar(4000)) FROM SmallA";  
+
+         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
+     }
+
+     @Test public void testTimestampToString() throws Exception {
+		  String input = "SELECT convert(timestampvalue, string) FROM BQT1.SMALLA"; 
+		  String output = "SELECT to_char(SmallA.TimestampValue, 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";  
+		
+	      TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
+	  }
+     ///END--FROM TIMESTAMP->DATE, TIME, STRING////////
+
+     ///BEGIN--FROM DATE->TIMESTAMP////////
+     @Test public void testDateToTimestamp() throws Exception {
+         String input = "SELECT convert(convert(datevalue, timestamp), string) FROM BQT1.SMALLA"; 
+         String output = "SELECT to_char(cast(SmallA.DateValue AS TIMESTAMP), 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";  
+
+         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
+     }
+     ///END--FROM DATE->TIMESTAMP////////
+
+     ///BEGIN--FROM TIME->TIMESTAMP////////
+     @Test public void testTimeToTimestamp() throws Exception {
+         String input = "SELECT convert(convert(TIMEVALUE, timestamp), string) FROM BQT1.SMALLA"; 
+         //String output = "SELECT to_char(cast(SmallA.TimeValue AS timestamp), 'YYYY-MM-DD HH24:MI:SS.FF') FROM SmallA";
+         String output = "SELECT to_char(SmallA.TimeValue, 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";
+
+         TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output,     TRANSLATOR);
+     }
+     ///END--FROM TIME->TIMESTAMP////////
+     
+     
+//     @Test public void testTimestampToTime() throws Exception {
+//      	helpTest(LANG_FACTORY.createLiteral(TimestampUtil.createTimestamp(111, 4, 5, 9, 16, 34, 220000000), Timestamp.class), "TIME", "cast(cast('2011-05-05 09:16:34.22' AS TIMESTAMP(6)) AS TIME)");
+//      }
+
+     
+     
+    
+}

Deleted: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,243 +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 org.teiid.translator.jdbc.netezza;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.language.LanguageFactory;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.jdbc.TranslationHelper;
-
-/**
- */
-public class TestNetezzaTranslatorSourceSystemFunctions {
-
-    private static NetezzaExecutionFactory TRANSLATOR; 
-    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
-
-    @BeforeClass public static void oneTimeSetup() throws TranslatorException {
-        TRANSLATOR = new NetezzaExecutionFactory();       
-        TRANSLATOR.setUseBindVariables(false);
-        TRANSLATOR.start();
-        
-        
-    }
-    
-    
-    /////////////////UTILLITY FUNCTIONS/////////
-    ////////////////////////////////////////////
-
-
-    private String getTestBQTVDB() {
-        return TranslationHelper.BQT_VDB; 
-    }
-    
-    
-    /////SOURCESYSTEM FUNCTION TESTCASES//////////////
-    ///////////////////////////////////////////////
-    
-    
-    //////////////////BEGIN---STRING FUNCTIONS TESTCASES///////////////////
-
-	@Test
-	public void testLcaseUcase() throws Exception {
-		String input = "select lcase(StringKey), ucase(StringKey) FROM BQT1.SmallA"; 
-		String output = "SELECT lower(SmallA.StringKey), upper(SmallA.StringKey) FROM SmallA"; 
-
-		TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output,TRANSLATOR);
-	}
-    @Test public void testPad() throws Exception {
-        String input = "select lpad(smalla.stringkey, 18), rpad(smalla.stringkey, 12) from bqt1.smalla"; //$NON-NLS-1$
-        String output = "SELECT lpad(SmallA.StringKey, 18), rpad(SmallA.StringKey, 12) FROM SmallA"; //$NON-NLS-1$
-          
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
-            input, 
-            output, TRANSLATOR);        
-    }
-
-	  @Test 
-	  public void testIFNull() throws Exception {
-	  String input = "SELECT ifnull(StringKey, 'otherString') FROM BQT1.SmallA"; 
-	  String output = "SELECT NVL(SmallA.StringKey, 'otherString') FROM SmallA";  
-	  //SELECT IFNULL(GL_ACTG_APPL_ID, 'otherString') FROM ACTG_UNIT_BAL_FACT
-	  //SELECT nvl(GL_ACTG_APPL_ID, 'otherString') FROM ACTG_UNIT_BAL_FACT
-	  
-	  TranslationHelper.helpTestVisitor(getTestBQTVDB(),  input, output, TRANSLATOR);
-	}
-
- 
-	  @Test public void testSubstring1() throws Exception {
-		  
-		  //////////BOTH SUBSTRING AND SUBSTR work in NETEZZA//
-		  //////////////////////////////////////////////////////
-				  String input = "SELECT substring(StringKey, 1) FROM BQT1.SmallA"; 
-				  String output = "SELECT substring(SmallA.StringKey, 1) FROM SmallA";  
-				//SELECT substring(FDL_PMF_ACCT, 3) FROM ACTG_UNIT_BAL_FACT
-				//SELECT substr(FDL_PMF_ACCT, 3) FROM ACTG_UNIT_BAL_FACT  
-				  TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
-	}
-	@Test public void testSubstring2() throws Exception {
-		
-		  //////////BOTH SUBSTRING AND SUBSTR work in NETEZZA//
-		  //////////////////////////////////////////////////////
-			  String input = "SELECT substring(StringKey, 1, 5) FROM BQT1.SmallA"; 
-			  String output = "SELECT substring(SmallA.StringKey, 1, 5) FROM SmallA";  
-			  TranslationHelper.helpTestVisitor(getTestBQTVDB(),  input, output, TRANSLATOR);
-	}
-     
-
-     
-    @Test public void testConcat_withLiteral() throws Exception {
-//        String sql = "select stringnum || '1' from BQT1.Smalla";        
-//        String expected = "SELECT CASE WHEN SmallA.StringNum IS NULL THEN NULL ELSE concat(SmallA.StringNum, '1') END FROM SmallA"; 
-//        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
-        String input = "select stringnum || '1' from BQT1.Smalla";        
-        String output = "SELECT (SmallA.StringNum || '1') FROM SmallA"; 
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),  input, output, TRANSLATOR);
-    }
-    
-    
- 
-    ////BEGIN-LOCATE FUNCTION
-    @Test public void testLocate() throws Exception {
-        String input = "SELECT locate(INTNUM, 'chimp', 1) FROM BQT1.SMALLA"; 
-        String output = "SELECT INSTR('chimp', cast(SmallA.IntNum AS varchar(4000)), 1) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, 
-                input, output, 
-                TRANSLATOR);
-    }
-
-    @Test public void testLocate2() throws Exception {
-        String input = "SELECT locate(STRINGNUM, 'chimp') FROM BQT1.SMALLA"; 
-        String output = "SELECT INSTR('chimp', SmallA.StringNum) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, 
-                input, output, 
-                TRANSLATOR);
-    }
-
-    @Test public void testLocate3() throws Exception {
-        String input = "SELECT locate(INTNUM, '234567890', 1) FROM BQT1.SMALLA WHERE INTKEY = 26"; 
-        String output = "SELECT INSTR('234567890', cast(SmallA.IntNum AS varchar(4000)), 1) FROM SmallA WHERE SmallA.IntKey = 26";  
-
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output,  TRANSLATOR);
-    }
-
-    @Test public void testLocate4() throws Exception {
-        String input = "SELECT locate('c', 'chimp', 1) FROM BQT1.SMALLA"; 
-        String output = "SELECT 1 FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
-    }
-
-    @Test public void testLocate5() throws Exception {
-        String input = "SELECT locate(STRINGNUM, 'chimp', -5) FROM BQT1.SMALLA"; 
-        String output = "SELECT INSTR('chimp', SmallA.StringNum, 1) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,  input, output, TRANSLATOR);
-    }
-
-     @Test public void testLocate6() throws Exception {
-        String input = "SELECT locate(STRINGNUM, 'chimp', INTNUM) FROM BQT1.SMALLA"; 
-        String output = "SELECT INSTR('chimp', SmallA.StringNum, CASE WHEN SmallA.IntNum < 1 THEN 1 ELSE SmallA.IntNum END) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
-    }
-
-    @Test public void testLocate7() throws Exception {
-        String input = "SELECT locate(STRINGNUM, 'chimp', LOCATE(STRINGNUM, 'chimp') + 1) FROM BQT1.SMALLA"; 
-        String output = "SELECT INSTR('chimp', SmallA.StringNum, CASE WHEN (INSTR('chimp', SmallA.StringNum) + 1) < 1 THEN 1 ELSE (INSTR('chimp', SmallA.StringNum) + 1) END) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
-    }
-    ////END-LOCATE FUNCTION
-    
-    
-    
-    
-    //////////////////BEGIN---NUMERIC FUNCTIONS TESTCASES///////////////////
-	@Test public void testCeil() throws Exception {
-		//select ceiling(sqrt(MEAS_PRD_ID)) from ACTG_UNIT_BAL_FACT
-		//select ceil(sqrt(MEAS_PRD_ID)) from ACTG_UNIT_BAL_FACT
-			  String input = "SELECT ceiling(sqrt(INTKEY)) FROM BQT1.SMALLA"; 
-			  String output = "SELECT ceil(sqrt(SmallA.IntKey)) FROM SmallA";  
-			  TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-			      input, 
-			      output, TRANSLATOR);
-	}
-
-	@Test public void testPower() throws Exception {
-		
-		//select power(MEAS_PRD_ID, 2) from ACTG_UNIT_BAL_FACT
-		//select pow(MEAS_PRD_ID, 2) from ACTG_UNIT_BAL_FACT
-			  String input = "SELECT power(INTKEY, 2) FROM BQT1.SMALLA"; 
-			  String output = "SELECT pow(SmallA.IntKey, 2) FROM SmallA";  
-			  TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-			      input, 
-			      output, TRANSLATOR);
-	}
-    //////////////////END---NUMERIC FUNCTIONS TESTCASES///////////////////
-   
-    
-    //////////////////BEGIN---BIT FUNCTIONS CONVERSION TESTCASES///////////////////
-    ///////////////////////////////////////////////////////////////////
-   
-   @Test public void testBitAnd() throws Exception {
-       String input = "select bitand(intkey, intnum) from bqt1.smalla"; 
-       String output = "SELECT intNand(SmallA.IntKey, SmallA.IntNum) FROM SmallA"; 
-              
-       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
-           input, 
-           output, TRANSLATOR);        
-   }
-   @Test public void testBitNot() throws Exception {
-       String input = "select bitnot(intkey) from bqt1.smalla"; 
-       String output = "SELECT intNnot(SmallA.IntKey) FROM SmallA"; 
-              
-       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
-           input, 
-           output, TRANSLATOR);        
-   }
-   @Test public void testBitOr() throws Exception {
-       String input = "select bitor(intkey, intnum) from bqt1.smalla"; 
-       String output = "SELECT intNor(SmallA.IntKey, SmallA.IntNum) FROM SmallA"; 
-              
-       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
-           input, 
-           output, TRANSLATOR);        
-   }
-   @Test public void testBitXor() throws Exception {
-       String input = "select bitxor(intkey, intnum) from bqt1.smalla"; 
-       String output = "SELECT intNxor(SmallA.IntKey, SmallA.IntNum) FROM SmallA"; 
-              
-       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
-           input, 
-           output, TRANSLATOR);        
-   }
-   //////////////////END---BIT FUNCTIONS CONVERSION TESTCASES///////////////////
-   /////////////////////////////////////////////////////////////////////////////
-
-
-}

Copied: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java (from rev 3382, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorSourceSystemFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,243 @@
+/*
+ * 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 org.teiid.translator.jdbc.netezza;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.language.LanguageFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+/**
+ */
+public class TestNetezzaTranslatorSourceSystemFunctions {
+
+    private static NetezzaExecutionFactory TRANSLATOR; 
+    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
+
+    @BeforeClass public static void oneTimeSetup() throws TranslatorException {
+        TRANSLATOR = new NetezzaExecutionFactory();       
+        TRANSLATOR.setUseBindVariables(false);
+        TRANSLATOR.start();
+        
+        
+    }
+    
+    
+    /////////////////UTILLITY FUNCTIONS/////////
+    ////////////////////////////////////////////
+
+
+    private String getTestBQTVDB() {
+        return TranslationHelper.BQT_VDB; 
+    }
+    
+    
+    /////SOURCESYSTEM FUNCTION TESTCASES//////////////
+    ///////////////////////////////////////////////
+    
+    
+    //////////////////BEGIN---STRING FUNCTIONS TESTCASES///////////////////
+
+	@Test
+	public void testLcaseUcase() throws Exception {
+		String input = "select lcase(StringKey), ucase(StringKey) FROM BQT1.SmallA"; 
+		String output = "SELECT lower(SmallA.StringKey), upper(SmallA.StringKey) FROM SmallA"; 
+
+		TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output,TRANSLATOR);
+	}
+    @Test public void testPad() throws Exception {
+        String input = "select lpad(smalla.stringkey, 18), rpad(smalla.stringkey, 12) from bqt1.smalla"; //$NON-NLS-1$
+        String output = "SELECT lpad(SmallA.StringKey, 18), rpad(SmallA.StringKey, 12) FROM SmallA"; //$NON-NLS-1$
+          
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+            input, 
+            output, TRANSLATOR);        
+    }
+
+	  @Test 
+	  public void testIFNull() throws Exception {
+	  String input = "SELECT ifnull(StringKey, 'otherString') FROM BQT1.SmallA"; 
+	  String output = "SELECT NVL(SmallA.StringKey, 'otherString') FROM SmallA";  
+	  //SELECT IFNULL(GL_ACTG_APPL_ID, 'otherString') FROM ACTG_UNIT_BAL_FACT
+	  //SELECT nvl(GL_ACTG_APPL_ID, 'otherString') FROM ACTG_UNIT_BAL_FACT
+	  
+	  TranslationHelper.helpTestVisitor(getTestBQTVDB(),  input, output, TRANSLATOR);
+	}
+
+ 
+	  @Test public void testSubstring1() throws Exception {
+		  
+		  //////////BOTH SUBSTRING AND SUBSTR work in NETEZZA//
+		  //////////////////////////////////////////////////////
+				  String input = "SELECT substring(StringKey, 1) FROM BQT1.SmallA"; 
+				  String output = "SELECT substring(SmallA.StringKey, 1) FROM SmallA";  
+				//SELECT substring(FDL_PMF_ACCT, 3) FROM ACTG_UNIT_BAL_FACT
+				//SELECT substr(FDL_PMF_ACCT, 3) FROM ACTG_UNIT_BAL_FACT  
+				  TranslationHelper.helpTestVisitor(getTestBQTVDB(), input, output, TRANSLATOR);
+	}
+	@Test public void testSubstring2() throws Exception {
+		
+		  //////////BOTH SUBSTRING AND SUBSTR work in NETEZZA//
+		  //////////////////////////////////////////////////////
+			  String input = "SELECT substring(StringKey, 1, 5) FROM BQT1.SmallA"; 
+			  String output = "SELECT substring(SmallA.StringKey, 1, 5) FROM SmallA";  
+			  TranslationHelper.helpTestVisitor(getTestBQTVDB(),  input, output, TRANSLATOR);
+	}
+     
+
+     
+    @Test public void testConcat_withLiteral() throws Exception {
+//        String sql = "select stringnum || '1' from BQT1.Smalla";        
+//        String expected = "SELECT CASE WHEN SmallA.StringNum IS NULL THEN NULL ELSE concat(SmallA.StringNum, '1') END FROM SmallA"; 
+//        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
+        String input = "select stringnum || '1' from BQT1.Smalla";        
+        String output = "SELECT (SmallA.StringNum || '1') FROM SmallA"; 
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),  input, output, TRANSLATOR);
+    }
+    
+    
+ 
+    ////BEGIN-LOCATE FUNCTION
+    @Test public void testLocate() throws Exception {
+        String input = "SELECT locate(INTNUM, 'chimp', 1) FROM BQT1.SMALLA"; 
+        String output = "SELECT INSTR('chimp', cast(SmallA.IntNum AS varchar(4000)), 1) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, 
+                input, output, 
+                TRANSLATOR);
+    }
+
+    @Test public void testLocate2() throws Exception {
+        String input = "SELECT locate(STRINGNUM, 'chimp') FROM BQT1.SMALLA"; 
+        String output = "SELECT INSTR('chimp', SmallA.StringNum) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, 
+                input, output, 
+                TRANSLATOR);
+    }
+
+    @Test public void testLocate3() throws Exception {
+        String input = "SELECT locate(INTNUM, '234567890', 1) FROM BQT1.SMALLA WHERE INTKEY = 26"; 
+        String output = "SELECT INSTR('234567890', cast(SmallA.IntNum AS varchar(4000)), 1) FROM SmallA WHERE SmallA.IntKey = 26";  
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output,  TRANSLATOR);
+    }
+
+    @Test public void testLocate4() throws Exception {
+        String input = "SELECT locate('c', 'chimp', 1) FROM BQT1.SMALLA"; 
+        String output = "SELECT 1 FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
+    }
+
+    @Test public void testLocate5() throws Exception {
+        String input = "SELECT locate(STRINGNUM, 'chimp', -5) FROM BQT1.SMALLA"; 
+        String output = "SELECT INSTR('chimp', SmallA.StringNum, 1) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,  input, output, TRANSLATOR);
+    }
+
+     @Test public void testLocate6() throws Exception {
+        String input = "SELECT locate(STRINGNUM, 'chimp', INTNUM) FROM BQT1.SMALLA"; 
+        String output = "SELECT INSTR('chimp', SmallA.StringNum, CASE WHEN SmallA.IntNum < 1 THEN 1 ELSE SmallA.IntNum END) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
+    }
+
+    @Test public void testLocate7() throws Exception {
+        String input = "SELECT locate(STRINGNUM, 'chimp', LOCATE(STRINGNUM, 'chimp') + 1) FROM BQT1.SMALLA"; 
+        String output = "SELECT INSTR('chimp', SmallA.StringNum, CASE WHEN (INSTR('chimp', SmallA.StringNum) + 1) < 1 THEN 1 ELSE (INSTR('chimp', SmallA.StringNum) + 1) END) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);
+    }
+    ////END-LOCATE FUNCTION
+    
+    
+    
+    
+    //////////////////BEGIN---NUMERIC FUNCTIONS TESTCASES///////////////////
+	@Test public void testCeil() throws Exception {
+		//select ceiling(sqrt(MEAS_PRD_ID)) from ACTG_UNIT_BAL_FACT
+		//select ceil(sqrt(MEAS_PRD_ID)) from ACTG_UNIT_BAL_FACT
+			  String input = "SELECT ceiling(sqrt(INTKEY)) FROM BQT1.SMALLA"; 
+			  String output = "SELECT ceil(sqrt(SmallA.IntKey)) FROM SmallA";  
+			  TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+			      input, 
+			      output, TRANSLATOR);
+	}
+
+	@Test public void testPower() throws Exception {
+		
+		//select power(MEAS_PRD_ID, 2) from ACTG_UNIT_BAL_FACT
+		//select pow(MEAS_PRD_ID, 2) from ACTG_UNIT_BAL_FACT
+			  String input = "SELECT power(INTKEY, 2) FROM BQT1.SMALLA"; 
+			  String output = "SELECT pow(SmallA.IntKey, 2) FROM SmallA";  
+			  TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+			      input, 
+			      output, TRANSLATOR);
+	}
+    //////////////////END---NUMERIC FUNCTIONS TESTCASES///////////////////
+   
+    
+    //////////////////BEGIN---BIT FUNCTIONS CONVERSION TESTCASES///////////////////
+    ///////////////////////////////////////////////////////////////////
+   
+   @Test public void testBitAnd() throws Exception {
+       String input = "select bitand(intkey, intnum) from bqt1.smalla"; 
+       String output = "SELECT intNand(SmallA.IntKey, SmallA.IntNum) FROM SmallA"; 
+              
+       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+           input, 
+           output, TRANSLATOR);        
+   }
+   @Test public void testBitNot() throws Exception {
+       String input = "select bitnot(intkey) from bqt1.smalla"; 
+       String output = "SELECT intNnot(SmallA.IntKey) FROM SmallA"; 
+              
+       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+           input, 
+           output, TRANSLATOR);        
+   }
+   @Test public void testBitOr() throws Exception {
+       String input = "select bitor(intkey, intnum) from bqt1.smalla"; 
+       String output = "SELECT intNor(SmallA.IntKey, SmallA.IntNum) FROM SmallA"; 
+              
+       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+           input, 
+           output, TRANSLATOR);        
+   }
+   @Test public void testBitXor() throws Exception {
+       String input = "select bitxor(intkey, intnum) from bqt1.smalla"; 
+       String output = "SELECT intNxor(SmallA.IntKey, SmallA.IntNum) FROM SmallA"; 
+              
+       TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+           input, 
+           output, TRANSLATOR);        
+   }
+   //////////////////END---BIT FUNCTIONS CONVERSION TESTCASES///////////////////
+   /////////////////////////////////////////////////////////////////////////////
+
+
+}

Deleted: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,246 +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 org.teiid.translator.jdbc.netezza;
-
-import static org.junit.Assert.assertEquals;
-
-import java.util.Arrays;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.LanguageFactory;
-import org.teiid.translator.TranslatorException;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.SQLConversionVisitor;
-import org.teiid.translator.jdbc.TranslationHelper;
-
-
-public class TestNetezzaTranslatorTypeMapping {
-
-    private static NetezzaExecutionFactory TRANSLATOR; 
-    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
-
-    @BeforeClass public static void oneTimeSetup() throws TranslatorException {
-        TRANSLATOR = new NetezzaExecutionFactory();       
-        TRANSLATOR.setUseBindVariables(false);
-        TRANSLATOR.start();
-        
-
-    }
-    
-    
-    /////////////////UTILLITY FUNCTIONS/////////
-    ////////////////////////////////////////////
-
-    private String getTestBQTVDB() {
-
-    	return TranslationHelper.BQT_VDB;
-    }
-    
-    
-    public void helpTest(Expression srcExpression, String tgtType, String expectedExpression) throws Exception {
-        Function func = LANG_FACTORY.createFunction("convert",  
-            Arrays.asList( srcExpression,LANG_FACTORY.createLiteral(tgtType, String.class)),TypeFacility.getDataTypeClass(tgtType));
-        
-        assertEquals("Error converting from " + srcExpression.getType() + " to " + tgtType, 
-            expectedExpression, helpGetString(func)); 
-    }    
-    public String helpGetString(Expression expr) throws Exception {
-        SQLConversionVisitor sqlVisitor = TRANSLATOR.getSQLConversionVisitor(); 
-        sqlVisitor.append(expr);  
-        
-        return sqlVisitor.toString();        
-    }  
-    
-    
-    /////////TYPE MAPPING TESTS/////////
-    ///////////////////////////////////
-    
-    @Test public void testCHARtoChar1() throws Exception {
-        String input = "SELECT convert(StringKey, CHAR) FROM BQT1.SmallA"; 
-        String output = "SELECT cast(SmallA.StringKey AS char(1)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-
-    @Test public void testLongToBigInt() throws Exception {
-        String input = "SELECT convert(convert(StringKey, long), string) FROM BQT1.SmallA"; 
-        String output = "SELECT cast(cast(SmallA.StringKey AS bigint) AS varchar(4000)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToByte() throws Exception {
-        String input = "SELECT char(convert(stringnum, byte) + 100) FROM BQT1.SMALLA"; 
-        String output = "SELECT chr((cast(SmallA.StringNum AS byteint) + 100)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToShort() throws Exception {
-        String input = "SELECT char(convert(stringnum, short) + 100) FROM BQT1.SMALLA"; 
-        String output = "SELECT chr((cast(SmallA.StringNum AS smallint) + 100)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToLong() throws Exception {
-//      String input = "SELECT char(convert(PART_WEIGHT, long) + 100) FROM PARTS"; 
-//      String output = "SELECT chr((cast(PARTS.PART_WEIGHT AS bigint) + 100)) FROM PARTS";  
-      String input = "SELECT convert(stringnum, long) FROM BQT1.SMALLA"; 
-      String output = "SELECT cast(SmallA.StringNum AS bigint) FROM SmallA";  
-
-      TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-          input, 
-          output, TRANSLATOR);
-  }
-    @Test public void testStringToBiginteger() throws Exception {
-        String input = "SELECT convert(stringnum, BIGINTEGER) FROM BQT1.SMALLA"; 
-        String output = "SELECT cast(SmallA.StringNum AS numeric(38)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-
-    @Test public void testStringToBigdecimal() throws Exception {
-        String input = "SELECT convert(stringnum, BIGDECIMAL) FROM BQT1.SMALLA"; 
-        String output = "SELECT cast(SmallA.StringNum AS numeric(38,18)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-
-    @Test public void testStringToVarchar() throws Exception {
-        String input = "SELECT convert(intkey, STRING) FROM BQT1.SMALLA"; 
-        String output = "SELECT cast(SmallA.IntKey AS varchar(4000)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    
-    
-    
- 
-    ////NON-MAPPED TYPES TEST/////////////
-    //////////////////////////////////////
-    
-    @Test public void testStringToInteger() throws Exception {
-        String input = "SELECT char(convert(stringnum, integer) + 100) FROM BQT1.SMALLA"; 
-        String output = "SELECT chr((cast(SmallA.StringNum AS integer) + 100)) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-   
-    @Test public void testStringToFloat() throws Exception {
-        String input = "SELECT convert(stringnum, float) FROM BQT1.SMALLA"; 
-        String output = "SELECT cast(SmallA.StringNum AS float) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToReal() throws Exception {
-        String input = "SELECT convert(stringnum, real) FROM BQT1.SMALLA"; 
-        String output = "SELECT cast(SmallA.StringNum AS float) FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToDouble() throws Exception {
-        String input = "SELECT convert(stringnum, double) FROM BQT1.SMALLA"; 
-        String output = "SELECT cast(SmallA.StringNum AS double) FROM SmallA";  
-       //SELECT cast(MEAS_PRD_ID AS DOUBLE) from ACTG_UNIT_BAL_FACT
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToBoolean() throws Exception {
-        String input = "SELECT convert(stringnum, boolean) FROM BQT1.SMALLA"; 
-        String output = "SELECT CASE WHEN SmallA.StringNum IN ('false', '0') THEN '0' WHEN SmallA.StringNum IS NOT NULL THEN '1' END FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToDate() throws Exception {
-        String input = "SELECT convert(stringnum, date) FROM BQT1.SMALLA"; 
-        String output = "SELECT to_date(SmallA.StringNum, 'YYYY-MM-DD') FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToTime() throws Exception {
-        String input = "SELECT convert(stringnum, time) FROM BQT1.SMALLA"; 
-        String output = "SELECT to_timestamp(SmallA.StringNum, 'HH24:MI:SS') FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-    @Test public void testStringToTimestamp() throws Exception {
-        String input = "SELECT convert(stringnum, timestamp) FROM BQT1.SMALLA"; 
-        String output = "SELECT to_timestamp(SmallA.StringNum, 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";  
-
-        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-            input, 
-            output, TRANSLATOR);
-    }
-
-
-    @Test public void testbooleanToIntegerConversion() throws Exception {
-		String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.BooleanValue FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.IntNum = convert(BQT2.SmallB.booleanvalue, integer)"; 
-		String output = "SELECT SmallA.IntNum, SmallB.BooleanValue FROM SmallA, SmallB WHERE SmallA.IntNum = (CASE WHEN SmallB.BooleanValue IN ( '0', 'FALSE') THEN 0 WHEN SmallB.BooleanValue IS NOT NULL THEN 1 END)";  
-		TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-	            input, 
-	            output, TRANSLATOR);
-
-   
-	 }
-    
-    @Test public void testIntegerToBooleanconversion() throws Exception {
-		String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.BooleanValue FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.booleanvalue = convert(BQT2.SmallB.IntNum, boolean) AND BQT1.SmallA.IntKey >= 0 AND BQT2.SmallB.IntKey >= 0 ORDER BY BQT1.SmallA.IntNum"; 
-		String output = "SELECT SmallA.IntNum, SmallB.BooleanValue FROM SmallA, SmallB WHERE SmallA.BooleanValue = CASE WHEN SmallB.IntNum = 0 THEN '0' WHEN SmallB.IntNum IS NOT NULL THEN '1' END AND SmallA.IntKey >= 0 AND SmallB.IntKey >= 0 ORDER BY SmallA.IntNum";  
-		TranslationHelper.helpTestVisitor(getTestBQTVDB(),
-	            input, 
-	            output, TRANSLATOR);
-
-   
-	 }
-    
-
-}

Copied: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java (from rev 3382, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestNetezzaTranslatorTypeMapping.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,246 @@
+/*
+ * 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 org.teiid.translator.jdbc.netezza;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.LanguageFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+import org.teiid.translator.jdbc.TranslationHelper;
+
+
+public class TestNetezzaTranslatorTypeMapping {
+
+    private static NetezzaExecutionFactory TRANSLATOR; 
+    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
+
+    @BeforeClass public static void oneTimeSetup() throws TranslatorException {
+        TRANSLATOR = new NetezzaExecutionFactory();       
+        TRANSLATOR.setUseBindVariables(false);
+        TRANSLATOR.start();
+        
+
+    }
+    
+    
+    /////////////////UTILLITY FUNCTIONS/////////
+    ////////////////////////////////////////////
+
+    private String getTestBQTVDB() {
+
+    	return TranslationHelper.BQT_VDB;
+    }
+    
+    
+    public void helpTest(Expression srcExpression, String tgtType, String expectedExpression) throws Exception {
+        Function func = LANG_FACTORY.createFunction("convert",  
+            Arrays.asList( srcExpression,LANG_FACTORY.createLiteral(tgtType, String.class)),TypeFacility.getDataTypeClass(tgtType));
+        
+        assertEquals("Error converting from " + srcExpression.getType() + " to " + tgtType, 
+            expectedExpression, helpGetString(func)); 
+    }    
+    public String helpGetString(Expression expr) throws Exception {
+        SQLConversionVisitor sqlVisitor = TRANSLATOR.getSQLConversionVisitor(); 
+        sqlVisitor.append(expr);  
+        
+        return sqlVisitor.toString();        
+    }  
+    
+    
+    /////////TYPE MAPPING TESTS/////////
+    ///////////////////////////////////
+    
+    @Test public void testCHARtoChar1() throws Exception {
+        String input = "SELECT convert(StringKey, CHAR) FROM BQT1.SmallA"; 
+        String output = "SELECT cast(SmallA.StringKey AS char(1)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+
+    @Test public void testLongToBigInt() throws Exception {
+        String input = "SELECT convert(convert(StringKey, long), string) FROM BQT1.SmallA"; 
+        String output = "SELECT cast(cast(SmallA.StringKey AS bigint) AS varchar(4000)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToByte() throws Exception {
+        String input = "SELECT char(convert(stringnum, byte) + 100) FROM BQT1.SMALLA"; 
+        String output = "SELECT chr((cast(SmallA.StringNum AS byteint) + 100)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToShort() throws Exception {
+        String input = "SELECT char(convert(stringnum, short) + 100) FROM BQT1.SMALLA"; 
+        String output = "SELECT chr((cast(SmallA.StringNum AS smallint) + 100)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToLong() throws Exception {
+//      String input = "SELECT char(convert(PART_WEIGHT, long) + 100) FROM PARTS"; 
+//      String output = "SELECT chr((cast(PARTS.PART_WEIGHT AS bigint) + 100)) FROM PARTS";  
+      String input = "SELECT convert(stringnum, long) FROM BQT1.SMALLA"; 
+      String output = "SELECT cast(SmallA.StringNum AS bigint) FROM SmallA";  
+
+      TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+          input, 
+          output, TRANSLATOR);
+  }
+    @Test public void testStringToBiginteger() throws Exception {
+        String input = "SELECT convert(stringnum, BIGINTEGER) FROM BQT1.SMALLA"; 
+        String output = "SELECT cast(SmallA.StringNum AS numeric(38)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+
+    @Test public void testStringToBigdecimal() throws Exception {
+        String input = "SELECT convert(stringnum, BIGDECIMAL) FROM BQT1.SMALLA"; 
+        String output = "SELECT cast(SmallA.StringNum AS numeric(38,18)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+
+    @Test public void testStringToVarchar() throws Exception {
+        String input = "SELECT convert(intkey, STRING) FROM BQT1.SMALLA"; 
+        String output = "SELECT cast(SmallA.IntKey AS varchar(4000)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    
+    
+    
+ 
+    ////NON-MAPPED TYPES TEST/////////////
+    //////////////////////////////////////
+    
+    @Test public void testStringToInteger() throws Exception {
+        String input = "SELECT char(convert(stringnum, integer) + 100) FROM BQT1.SMALLA"; 
+        String output = "SELECT chr((cast(SmallA.StringNum AS integer) + 100)) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+   
+    @Test public void testStringToFloat() throws Exception {
+        String input = "SELECT convert(stringnum, float) FROM BQT1.SMALLA"; 
+        String output = "SELECT cast(SmallA.StringNum AS float) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToReal() throws Exception {
+        String input = "SELECT convert(stringnum, real) FROM BQT1.SMALLA"; 
+        String output = "SELECT cast(SmallA.StringNum AS float) FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToDouble() throws Exception {
+        String input = "SELECT convert(stringnum, double) FROM BQT1.SMALLA"; 
+        String output = "SELECT cast(SmallA.StringNum AS double) FROM SmallA";  
+       //SELECT cast(MEAS_PRD_ID AS DOUBLE) from ACTG_UNIT_BAL_FACT
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToBoolean() throws Exception {
+        String input = "SELECT convert(stringnum, boolean) FROM BQT1.SMALLA"; 
+        String output = "SELECT CASE WHEN SmallA.StringNum IN ('false', '0') THEN '0' WHEN SmallA.StringNum IS NOT NULL THEN '1' END FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToDate() throws Exception {
+        String input = "SELECT convert(stringnum, date) FROM BQT1.SMALLA"; 
+        String output = "SELECT to_date(SmallA.StringNum, 'YYYY-MM-DD') FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToTime() throws Exception {
+        String input = "SELECT convert(stringnum, time) FROM BQT1.SMALLA"; 
+        String output = "SELECT to_timestamp(SmallA.StringNum, 'HH24:MI:SS') FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+    @Test public void testStringToTimestamp() throws Exception {
+        String input = "SELECT convert(stringnum, timestamp) FROM BQT1.SMALLA"; 
+        String output = "SELECT to_timestamp(SmallA.StringNum, 'YYYY-MM-DD HH24:MI:SS.MS') FROM SmallA";  
+
+        TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+            input, 
+            output, TRANSLATOR);
+    }
+
+
+    @Test public void testbooleanToIntegerConversion() throws Exception {
+		String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.BooleanValue FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.IntNum = convert(BQT2.SmallB.booleanvalue, integer)"; 
+		String output = "SELECT SmallA.IntNum, SmallB.BooleanValue FROM SmallA, SmallB WHERE SmallA.IntNum = (CASE WHEN SmallB.BooleanValue IN ( '0', 'FALSE') THEN 0 WHEN SmallB.BooleanValue IS NOT NULL THEN 1 END)";  
+		TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+	            input, 
+	            output, TRANSLATOR);
+
+   
+	 }
+    
+    @Test public void testIntegerToBooleanconversion() throws Exception {
+		String input = "SELECT BQT1.SmallA.IntNum, BQT2.SmallB.BooleanValue FROM BQT1.SmallA, BQT2.SmallB WHERE BQT1.SmallA.booleanvalue = convert(BQT2.SmallB.IntNum, boolean) AND BQT1.SmallA.IntKey >= 0 AND BQT2.SmallB.IntKey >= 0 ORDER BY BQT1.SmallA.IntNum"; 
+		String output = "SELECT SmallA.IntNum, SmallB.BooleanValue FROM SmallA, SmallB WHERE SmallA.BooleanValue = CASE WHEN SmallB.IntNum = 0 THEN '0' WHEN SmallB.IntNum IS NOT NULL THEN '1' END AND SmallA.IntKey >= 0 AND SmallB.IntKey >= 0 ORDER BY SmallA.IntNum";  
+		TranslationHelper.helpTestVisitor(getTestBQTVDB(),
+	            input, 
+	            output, TRANSLATOR);
+
+   
+	 }
+    
+
+}

Deleted: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java
===================================================================
--- trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,98 +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 org.teiid.translator.jdbc.netezza;
-
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-import org.teiid.language.Expression;
-import org.teiid.language.Function;
-import org.teiid.language.LanguageFactory;
-import org.teiid.translator.TypeFacility;
-import org.teiid.translator.jdbc.SQLConversionVisitor;
-
-/**
- */
-public class TestSubstringFunctionModifier extends TestCase {
-
-    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
-
-
-    /**
-     * Constructor for TestSubstringFunctionModifier.
-     * @param name
-     */
-    public TestSubstringFunctionModifier(String name) {
-        super(name);
-    }
-
-    public void helpTestMod(Expression[] args, String expectedStr) throws Exception {
-        Function func = LANG_FACTORY.createFunction("substring",  
-            Arrays.asList(args), TypeFacility.RUNTIME_TYPES.STRING);
-        
-        NetezzaExecutionFactory trans = new NetezzaExecutionFactory();
-        trans.start();
-
-        SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor(); 
-        sqlVisitor.append(func);  
-        
-        assertEquals(expectedStr, sqlVisitor.toString());
-    }
-
-    public void testTwoArgs() throws Exception {
-        Expression[] args = new Expression[] {
-            LANG_FACTORY.createLiteral("a.b.c", String.class), 
-            LANG_FACTORY.createLiteral(new Integer(1), Integer.class)           
-        }; 
-        helpTestMod(args, "substring('a.b.c', 1)"); 
-    }
-
-    public void testThreeArgsWithConstant() throws Exception {
-        Expression[] args = new Expression[] {
-            LANG_FACTORY.createLiteral("a.b.c", String.class), 
-            LANG_FACTORY.createLiteral(new Integer(3), Integer.class),
-            LANG_FACTORY.createLiteral(new Integer(1), Integer.class) 
-        }; 
-        helpTestMod(args, "substring('a.b.c', 3, 1)"); 
-    }
-
-    public void testThreeArgsWithElement() throws Exception {
-        Expression[] args = new Expression[] {
-            LANG_FACTORY.createLiteral("a.b.c", String.class), 
-            LANG_FACTORY.createColumnReference("e1", null, null, Integer.class), 
-            LANG_FACTORY.createLiteral(new Integer(1), Integer.class) 
-        }; 
-        helpTestMod(args, "substring('a.b.c', e1, 1)"); 
-    }
-
-    public void testThreeArgsWithNull() throws Exception {
-        Expression[] args = new Expression[] {
-            LANG_FACTORY.createLiteral("a.b.c", String.class), 
-            LANG_FACTORY.createLiteral(null, Integer.class),
-            LANG_FACTORY.createLiteral(new Integer(5), Integer.class) 
-        }; 
-        helpTestMod(args, "substring('a.b.c', NULL, 5)"); 
-    }
-
-}

Copied: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java (from rev 3382, trunk/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java)
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java	                        (rev 0)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/netezza/TestSubstringFunctionModifier.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,98 @@
+/*
+ * 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 org.teiid.translator.jdbc.netezza;
+
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+import org.teiid.language.Expression;
+import org.teiid.language.Function;
+import org.teiid.language.LanguageFactory;
+import org.teiid.translator.TypeFacility;
+import org.teiid.translator.jdbc.SQLConversionVisitor;
+
+/**
+ */
+public class TestSubstringFunctionModifier extends TestCase {
+
+    private static final LanguageFactory LANG_FACTORY = new LanguageFactory();
+
+
+    /**
+     * Constructor for TestSubstringFunctionModifier.
+     * @param name
+     */
+    public TestSubstringFunctionModifier(String name) {
+        super(name);
+    }
+
+    public void helpTestMod(Expression[] args, String expectedStr) throws Exception {
+        Function func = LANG_FACTORY.createFunction("substring",  
+            Arrays.asList(args), TypeFacility.RUNTIME_TYPES.STRING);
+        
+        NetezzaExecutionFactory trans = new NetezzaExecutionFactory();
+        trans.start();
+
+        SQLConversionVisitor sqlVisitor = trans.getSQLConversionVisitor(); 
+        sqlVisitor.append(func);  
+        
+        assertEquals(expectedStr, sqlVisitor.toString());
+    }
+
+    public void testTwoArgs() throws Exception {
+        Expression[] args = new Expression[] {
+            LANG_FACTORY.createLiteral("a.b.c", String.class), 
+            LANG_FACTORY.createLiteral(new Integer(1), Integer.class)           
+        }; 
+        helpTestMod(args, "substring('a.b.c', 1)"); 
+    }
+
+    public void testThreeArgsWithConstant() throws Exception {
+        Expression[] args = new Expression[] {
+            LANG_FACTORY.createLiteral("a.b.c", String.class), 
+            LANG_FACTORY.createLiteral(new Integer(3), Integer.class),
+            LANG_FACTORY.createLiteral(new Integer(1), Integer.class) 
+        }; 
+        helpTestMod(args, "substring('a.b.c', 3, 1)"); 
+    }
+
+    public void testThreeArgsWithElement() throws Exception {
+        Expression[] args = new Expression[] {
+            LANG_FACTORY.createLiteral("a.b.c", String.class), 
+            LANG_FACTORY.createColumnReference("e1", null, null, Integer.class), 
+            LANG_FACTORY.createLiteral(new Integer(1), Integer.class) 
+        }; 
+        helpTestMod(args, "substring('a.b.c', e1, 1)"); 
+    }
+
+    public void testThreeArgsWithNull() throws Exception {
+        Expression[] args = new Expression[] {
+            LANG_FACTORY.createLiteral("a.b.c", String.class), 
+            LANG_FACTORY.createLiteral(null, Integer.class),
+            LANG_FACTORY.createLiteral(new Integer(5), Integer.class) 
+        }; 
+        helpTestMod(args, "substring('a.b.c', NULL, 5)"); 
+    }
+
+}


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/oracle/TestOracleTranslator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,7 +22,7 @@
 
 package org.teiid.translator.jdbc.oracle;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.*;
 
 import java.util.List;
 
@@ -42,10 +42,9 @@
 import org.teiid.query.metadata.CompositeMetadataStore;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.TranslatorException;
-import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.jdbc.TranslatedCommand;
 import org.teiid.translator.jdbc.TranslationHelper;
 
@@ -395,7 +394,15 @@
                 input, output, 
                 TRANSLATOR);
     }
+    
+    @Test public void test_sdo_within_distance_pushdownfunction() throws Exception {
+        String input = "SELECT INTKEY FROM BQT1.SMALLA WHERE sdo_within_distance(OBJECTVALUE, 'SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL)', 'DISTANCE=25.0 UNIT=NAUT_MILE') = true"; //$NON-NLS-1$
+        String output = "SELECT SmallA.IntKey FROM SmallA WHERE sdo_within_distance(SmallA.ObjectValue, SDO_GEOMETRY(2001, 8307, MDSYS.SDO_POINT_TYPE(90.0, -45.0, NULL), NULL, NULL), 'DISTANCE=25.0 UNIT=NAUT_MILE') = 'true'";  //$NON-NLS-1$
 
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, 
+                TRANSLATOR);
+    }
+
     /**
      * Test a query which uses 
      * <code>sdo_within_distance(String literal, Object element, String literal) 
@@ -536,7 +543,7 @@
         String input = "SELECT ((CASE WHEN month(datevalue) < 10 THEN ('0' || convert(month(datevalue), string)) ELSE convert(month(datevalue), string) END || CASE WHEN dayofmonth(datevalue) < 10 THEN ('0' || convert(dayofmonth(datevalue), string)) ELSE convert(dayofmonth(datevalue), string) END) || convert(year(datevalue), string)), SUM(intkey) FROM bqt1.SMALLA GROUP BY datevalue"; //$NON-NLS-1$
         String output = "SELECT CASE WHEN CASE WHEN CASE WHEN EXTRACT(MONTH FROM SmallA.DateValue) < 10 THEN CASE WHEN to_char(EXTRACT(MONTH FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('0', to_char(EXTRACT(MONTH FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(MONTH FROM SmallA.DateValue)) END IS NULL OR CASE WHEN EXTRACT(DAY FROM SmallA.DateValue) < 10 THEN CASE WHEN to_char(EXTRACT(DAY FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('0', to_char(EXTRACT(DAY FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(DAY FROM SmallA.DateValue)) END IS NULL THEN NULL ELSE concat(CASE WHEN EXTRACT(MONTH FROM SmallA.DateValue) < 10 THEN CASE WHEN to_char(EXTRACT(MONTH FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('0', to_char(EXTRACT(MONTH FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(MONTH FROM SmallA.DateValue)) END, CASE WHEN EXTRACT(DAY FROM SmallA.DateValue) < 10 THEN CASE WHEN to_char(EXTRACT(DAY FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('!
 0', to_char(EXTRACT(DAY FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(DAY FROM SmallA.DateValue)) END) END IS NULL OR to_char(EXTRACT(YEAR FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat(CASE WHEN CASE WHEN EXTRACT(MONTH FROM SmallA.DateValue) < 10 THEN CASE WHEN to_char(EXTRACT(MONTH FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('0', to_char(EXTRACT(MONTH FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(MONTH FROM SmallA.DateValue)) END IS NULL OR CASE WHEN EXTRACT(DAY FROM SmallA.DateValue) < 10 THEN CASE WHEN to_char(EXTRACT(DAY FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('0', to_char(EXTRACT(DAY FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(DAY FROM SmallA.DateValue)) END IS NULL THEN NULL ELSE concat(CASE WHEN EXTRACT(MONTH FROM SmallA.DateValue) < 10 THEN CASE WHEN to_char(EXTRACT(MONTH FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('0', to_char(EXTRACT(MONTH FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(MONTH FROM SmallA.Da!
 teValue)) END, CASE WHEN EXTRACT(DAY FROM SmallA.DateValue) < !
 10 THEN 
CASE WHEN to_char(EXTRACT(DAY FROM SmallA.DateValue)) IS NULL THEN NULL ELSE concat('0', to_char(EXTRACT(DAY FROM SmallA.DateValue))) END ELSE to_char(EXTRACT(DAY FROM SmallA.DateValue)) END) END, to_char(EXTRACT(YEAR FROM SmallA.DateValue))) END, SUM(SmallA.IntKey) FROM SmallA GROUP BY SmallA.DateValue"; //$NON-NLS-1$
         
-        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(),
+        helpTestVisitor(RealMetadataFactory.exampleBQTCached(),
                         input, 
                         EMPTY_CONTEXT, null, output);
     }
@@ -603,7 +610,7 @@
         String input = "UPDATE bqt1.smalla SET intkey = intkey + 1"; //$NON-NLS-1$
         String output = "UPDATE SmallA SET IntKey = (SmallA.IntKey + 1)"; //$NON-NLS-1$
         
-        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(),
+        helpTestVisitor(RealMetadataFactory.exampleBQTCached(),
                 input, 
                 EMPTY_CONTEXT, null, output);
     }
@@ -722,7 +729,7 @@
         RealMetadataFactory.createElements(dual, new String[] {"something"}, new String[] {DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$
         
         CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
-        return new TransformationMetadata(null, store, null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+        return new TransformationMetadata(null, store, null, RealMetadataFactory.SFM.getSystemFunctions(), null);
     }
 
 	public void helpTestVisitor(String vdb, String input, String expectedOutput) throws TranslatorException {
@@ -733,7 +740,7 @@
         String input = "select max(intkey), stringkey from (select intkey, stringkey from bqt1.smalla order by intkey limit 100) x group by stringkey"; //$NON-NLS-1$
         String output = "SELECT MAX(x.intkey), x.stringkey FROM (SELECT * FROM (SELECT SmallA.IntKey, SmallA.StringKey FROM SmallA ORDER BY SmallA.IntKey) WHERE ROWNUM <= 100) x GROUP BY x.stringkey"; //$NON-NLS-1$
                
-        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(),
+        helpTestVisitor(RealMetadataFactory.exampleBQTCached(),
                 input, 
                 EMPTY_CONTEXT, null, output);        
     }
@@ -742,7 +749,7 @@
         String input = "select intkey, intnum from bqt1.smalla except select intnum, intkey from bqt1.smallb"; //$NON-NLS-1$
         String output = "SELECT SmallA.IntKey, SmallA.IntNum FROM SmallA MINUS SELECT SmallB.IntNum, SmallB.IntKey FROM SmallB"; //$NON-NLS-1$
                
-        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(),
+        helpTestVisitor(RealMetadataFactory.exampleBQTCached(),
                 input, 
                 EMPTY_CONTEXT, null, output);        
     }
@@ -750,20 +757,20 @@
     @Test public void testConcat() throws Exception {
         String sql = "select concat(stringnum, stringkey) from BQT1.Smalla"; //$NON-NLS-1$       
         String expected = "SELECT CASE WHEN SmallA.StringNum IS NULL OR SmallA.StringKey IS NULL THEN NULL ELSE concat(SmallA.StringNum, SmallA.StringKey) END FROM SmallA"; //$NON-NLS-1$
-        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
+        helpTestVisitor(RealMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
     }
     
     @Test public void testConcat_withLiteral() throws Exception {
         String sql = "select stringnum || '1' from BQT1.Smalla"; //$NON-NLS-1$       
         String expected = "SELECT CASE WHEN SmallA.StringNum IS NULL THEN NULL ELSE concat(SmallA.StringNum, '1') END FROM SmallA"; //$NON-NLS-1$
-        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
+        helpTestVisitor(RealMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
     }
     
     @Test public void testRowLimitWithUnionOrderBy() throws Exception {
         String input = "(select intkey from bqt1.smalla limit 50, 100) union select intnum from bqt1.smalla order by intkey"; //$NON-NLS-1$
         String output = "SELECT c_0 FROM (SELECT VIEW_FOR_LIMIT.*, ROWNUM ROWNUM_ FROM (SELECT g_1.IntKey AS c_0 FROM SmallA g_1) VIEW_FOR_LIMIT WHERE ROWNUM <= 150) WHERE ROWNUM_ > 50 UNION SELECT g_0.IntNum AS c_0 FROM SmallA g_0 ORDER BY c_0"; //$NON-NLS-1$
                
-		CommandBuilder commandBuilder = new CommandBuilder(FakeMetadataFactory.exampleBQTCached());
+		CommandBuilder commandBuilder = new CommandBuilder(RealMetadataFactory.exampleBQTCached());
         Command obj = commandBuilder.getCommand(input, true, true);
 		this.helpTestVisitor(obj, EMPTY_CONTEXT, null, output);
     }
@@ -771,7 +778,16 @@
     @Test public void testCot() throws Exception {
     	String sql = "select cot(doublenum) from BQT1.Smalla"; //$NON-NLS-1$       
         String expected = "SELECT (1 / tan(SmallA.DoubleNum)) FROM SmallA"; //$NON-NLS-1$
-        helpTestVisitor(FakeMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
+        helpTestVisitor(RealMetadataFactory.exampleBQTCached(), sql, EMPTY_CONTEXT, null, expected);
     }
+    
+    @Test public void testLikeRegex() throws Exception {
+        String input = "SELECT intkey FROM BQT1.SMALLA where stringkey like_regex 'ab.*c+' and stringkey not like_regex 'ab{3,5}c'"; //$NON-NLS-1$
+        String output = "SELECT SmallA.IntKey FROM SmallA WHERE SmallA.StringKey REGEXP_LIKE 'ab.*c+' AND SmallA.StringKey NOT REGEXP_LIKE 'ab{3,5}c'";  //$NON-NLS-1$
 
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+                input, output, 
+                TRANSLATOR);
+    }
+
 }


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/TestPostgreSQLTranslator.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/TestPostgreSQLTranslator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/postgresql/TestPostgreSQLTranslator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -544,5 +544,14 @@
                 input, output, 
                 TRANSLATOR);
     }
+    
+    @Test public void testLikeRegex() throws Exception {
+        String input = "SELECT intkey FROM BQT1.SMALLA where stringkey like_regex 'ab.*c+' and stringkey not like_regex 'ab{3,5}c'"; //$NON-NLS-1$
+        String output = "SELECT SmallA.IntKey FROM SmallA WHERE SmallA.StringKey ~ 'ab.*c+' AND SmallA.StringKey !~ 'ab{3,5}c'";  //$NON-NLS-1$
+
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB,
+                input, output, 
+                TRANSLATOR);
+    }
     
 }


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sqlserver/TestSqlServerConversionVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -37,7 +37,6 @@
 import org.teiid.query.metadata.CompositeMetadataStore;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.TranslatorException;
 import org.teiid.translator.jdbc.TranslationHelper;
@@ -50,9 +49,13 @@
     private static SQLServerExecutionFactory trans = new SQLServerExecutionFactory();
     
     @BeforeClass
-    public static void setup() throws TranslatorException {
+    public static void oneTimeSetup() throws TranslatorException {
         trans.start();
     }
+    
+    public void setUp() throws Exception {
+    	trans.setDatabaseVersion(SQLServerExecutionFactory.V_2005);
+    }
 
     public String getTestVDB() {
         return TranslationHelper.PARTS_VDB;
@@ -144,6 +147,25 @@
             output);        
     }
     
+    @Test public void testConvertDate() throws Exception {
+        String input = "select stringkey from bqt1.smalla where BQT1.SmallA.DateValue IN (convert('2000-01-12', date), convert('2000-02-02', date))"; //$NON-NLS-1$
+        String output = "SELECT SmallA.StringKey FROM SmallA WHERE SmallA.DateValue IN (CAST('2000-01-12 00:00:00.0' AS DATETIME), CAST('2000-02-02 00:00:00.0' AS DATETIME))"; //$NON-NLS-1$
+               
+        helpTestVisitor(getBQTVDB(),
+            input, 
+            output);        
+    }
+    
+    @Test public void testConvertDate2008() throws Exception {
+    	trans.setDatabaseVersion(SQLServerExecutionFactory.V_2008);
+        String input = "select stringkey from bqt1.smalla where BQT1.SmallA.DateValue IN (convert('2000-01-12', date), convert('2000-02-02', date))"; //$NON-NLS-1$
+        String output = "SELECT SmallA.StringKey FROM SmallA WHERE SmallA.DateValue IN (CAST('2000-01-12' AS DATE), CAST('2000-02-02' AS DATE))"; //$NON-NLS-1$
+               
+        helpTestVisitor(getBQTVDB(),
+            input, 
+            output);        
+    }
+    
     @Test public void testUniqueidentifier() throws Exception {
     	MetadataStore metadataStore = new MetadataStore();
     	Schema foo = RealMetadataFactory.createPhysicalModel("foo", metadataStore); //$NON-NLS-1$
@@ -160,7 +182,7 @@
         obj.setNativeType("uniqueidentifier"); //$NON-NLS-1$
         
         CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
-        QueryMetadataInterface metadata = new TransformationMetadata(null, store, null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+        QueryMetadataInterface metadata = new TransformationMetadata(null, store, null, RealMetadataFactory.SFM.getSystemFunctions(), null);
         
         TranslationUtility tu = new TranslationUtility(metadata);
         Command command = tu.parseCommand("select max(x) from bar"); //$NON-NLS-1$
@@ -174,7 +196,7 @@
         String input = "select intkey from (select intkey from bqt1.smalla) as x order by intkey limit 100"; //$NON-NLS-1$
         String output = "SELECT TOP 100 v_0.c_0 FROM (SELECT g_0.IntKey AS c_0 FROM SmallA g_0) v_0 ORDER BY v_0.c_0"; //$NON-NLS-1$
                
-		CommandBuilder commandBuilder = new CommandBuilder(FakeMetadataFactory.exampleBQTCached());
+		CommandBuilder commandBuilder = new CommandBuilder(RealMetadataFactory.exampleBQTCached());
         Command obj = commandBuilder.getCommand(input, true, true);
         TranslationHelper.helpTestVisitor(output, trans, obj);
     }


Property changes on: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/sybase
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java
===================================================================
--- branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-jdbc/src/test/java/org/teiid/translator/jdbc/teradata/TestTeradataTranslator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -31,6 +31,8 @@
 
 import org.junit.BeforeClass;
 import org.junit.Test;
+import org.teiid.cdk.api.TranslationUtility;
+import org.teiid.language.Command;
 import org.teiid.language.Expression;
 import org.teiid.language.Function;
 import org.teiid.language.In;
@@ -82,35 +84,77 @@
     
     @Test public void testIntegerToString() throws Exception {
         String input = "SELECT lcase(bigdecimalvalue) FROM BQT1.SMALLA"; 
-        String output = "SELECT LOWER(cast(SmallA.BigDecimalValue AS varchar(100))) FROM SmallA"; 
+        String output = "SELECT LOWER(cast(SmallA.BigDecimalValue AS varchar(4000))) FROM SmallA"; 
         TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);    	
     }    
     
+    @Test public void testSubString() throws Exception {
+        String input = "SELECT intkey FROM BQT1.SmallA WHERE SUBSTRING(BQT1.SmallA.IntKey, 1) = '1' ORDER BY intkey"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA WHERE substr(cast(SmallA.IntKey AS varchar(4000)), 1) = '1' ORDER BY 1"; 
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);    	
+    }  
+    
+    @Test public void testSubString2() throws Exception {
+        String input = "SELECT intkey FROM BQT1.SmallA WHERE SUBSTRING(BQT1.SmallA.IntKey, 1, 2) = '1' ORDER BY intkey"; 
+        String output = "SELECT SmallA.IntKey FROM SmallA WHERE substr(cast(SmallA.IntKey AS varchar(4000)), 1, 2) = '1' ORDER BY 1"; 
+        TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);    	
+    }     
+    
     @Test public void testDateToString() throws Exception {
         String input = "SELECT intkey, UPPER(timevalue) AS UPPER FROM BQT1.SmallA ORDER BY intkey"; 
-        String output = "SELECT SmallA.IntKey, UPPER(cast(SmallA.TimeValue AS varchar(100))) AS UPPER FROM SmallA ORDER BY SmallA.IntKey"; 
+        String output = "SELECT SmallA.IntKey, UPPER(cast(cast(SmallA.TimeValue AS FORMAT 'HH:MI:SS') AS VARCHAR(9))) AS UPPER FROM SmallA ORDER BY 1"; 
         TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);    	
     }    
     
     @Test public void testLocate() throws Exception {
         String input = "SELECT INTKEY, BIGDECIMALVALUE FROM BQT1.SmallA WHERE LOCATE('-', BIGDECIMALVALUE) = 1 ORDER BY intkey"; 
-        String output = "SELECT SmallA.IntKey, SmallA.BigDecimalValue FROM SmallA WHERE position('-' in cast(SmallA.BigDecimalValue AS varchar(100))) = 1 ORDER BY SmallA.IntKey"; 
+        String output = "SELECT SmallA.IntKey, SmallA.BigDecimalValue FROM SmallA WHERE position('-' in cast(SmallA.BigDecimalValue AS varchar(4000))) = 1 ORDER BY 1"; 
         TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, input, output, TRANSLATOR);    	
     }      
     
+    @Test public void testPositionalOrderBy() throws Exception {
+        String input = "SELECT INTKEY, BIGDECIMALVALUE FROM BQT1.SmallA ORDER BY intkey"; 
+        String output = "SELECT g_0.IntKey AS c_0, g_0.BigDecimalValue AS c_1 FROM SmallA AS g_0 ORDER BY 1"; 
+
+        TranslationUtility tu = TranslationHelper.getTranslationUtility(TranslationHelper.BQT_VDB, null);
+        Command command = tu.parseCommand(input, true, true);
+    	TranslationHelper.helpTestVisitor(output, TRANSLATOR, command);	
+    }
     
+    @Test public void testPositionalOrderByUnion() throws Exception {
+        String input = "SELECT a as b, b as a from (SELECT intkey as a, stringkey as b from BQT1.smalla union SELECT intkey as a, stringkey as b from BQT1.smalla) as x order by a"; 
+        String output = "SELECT v_0.c_0, v_0.c_1 FROM (SELECT g_1.IntKey AS c_0, g_1.StringKey AS c_1 FROM SmallA AS g_1 UNION SELECT g_0.IntKey AS c_0, g_0.StringKey AS c_1 FROM SmallA AS g_0) AS v_0 ORDER BY 2"; 
+
+        TranslationUtility tu = TranslationHelper.getTranslationUtility(TranslationHelper.BQT_VDB, null);
+        Command command = tu.parseCommand(input, true, true);
+    	TranslationHelper.helpTestVisitor(output, TRANSLATOR, command);	
+    }
+    
+    @Test public void testPositionalOrderByUnion1() throws Exception {
+        String input = "SELECT a as b from (SELECT intkey as a, stringkey as b from BQT1.smalla union SELECT intkey as a, stringkey as b from BQT1.smalla) as x order by x.b"; 
+        String output = "SELECT v_0.c_0 FROM (SELECT g_1.IntKey AS c_0, g_1.StringKey AS c_1 FROM SmallA AS g_1 UNION SELECT g_0.IntKey AS c_0, g_0.StringKey AS c_1 FROM SmallA AS g_0) AS v_0 ORDER BY v_0.c_1"; 
+
+        TranslationUtility tu = TranslationHelper.getTranslationUtility(TranslationHelper.BQT_VDB, null);
+        Command command = tu.parseCommand(input, true, true);
+    	TranslationHelper.helpTestVisitor(output, TRANSLATOR, command);	
+    }
+    
     @Test public void testByteToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "string", "1"); 
+        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)1), Byte.class), "string", "cast(1 AS varchar(4000))"); 
     }
     
     @Test public void testByte2ToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)-1), Byte.class), "string", "-1"); 
+        helpTest(LANG_FACTORY.createLiteral(new Byte((byte)-1), Byte.class), "string", "cast(-1 AS varchar(4000))"); 
     }
     
     @Test public void testDoubleToString() throws Exception {
-        helpTest(LANG_FACTORY.createLiteral(new Double(1.0), Double.class), "string", "1.0"); 
+        helpTest(LANG_FACTORY.createLiteral(new Double(1.0), Double.class), "string", "cast(1.0 AS varchar(4000))"); 
     }    
     
+    @Test public void testStringToDouble() throws Exception {
+        helpTest(LANG_FACTORY.createLiteral("1.0", String.class), "double", "cast('1.0' AS double precision)"); 
+    }      
+    
 	@Test public void testInDecompose() throws Exception {
     	Expression left = LANG_FACTORY.createLiteral("1", String.class);
     	List<Expression> right = new ArrayList<Expression>();
@@ -178,7 +222,13 @@
 	
 	@Test public void testRightFunction() throws Exception {
 		String input = "SELECT INTKEY, FLOATNUM FROM BQT1.SmallA WHERE right(FLOATNUM, 2) <> 0 ORDER BY INTKEY";
-		String out = "SELECT SmallA.IntKey, SmallA.FloatNum FROM SmallA WHERE substr(cast(SmallA.FloatNum AS varchar(100)),(character_length(cast(SmallA.FloatNum AS varchar(100)))-2)) <> '0' ORDER BY SmallA.IntKey";
+		String out = "SELECT SmallA.IntKey, SmallA.FloatNum FROM SmallA WHERE substr(cast(SmallA.FloatNum AS varchar(4000)),(character_length(cast(SmallA.FloatNum AS varchar(4000)))-2+1)) <> '0' ORDER BY 1";
 		TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);		
 	}
+	
+	@Test public void testLocateFunction() throws Exception {
+		String input = "SELECT INTKEY, STRINGKEY, SHORTVALUE FROM BQT1.SmallA WHERE (LOCATE(0, STRINGKEY) = 2) OR (LOCATE(2, SHORTVALUE, 4) = 6) ORDER BY intkey";
+		String out = "SELECT SmallA.IntKey, SmallA.StringKey, SmallA.ShortValue FROM SmallA WHERE position('0' in SmallA.StringKey) = 2 OR position('2' in substr(cast(SmallA.ShortValue AS varchar(4000)),4)) = 6 ORDER BY 1";
+		TranslationHelper.helpTestVisitor(TranslationHelper.BQT_VDB, null, input, out, TRANSLATOR);		
+	}	
 }

Modified: branches/as7/connectors/translator-ldap/pom.xml
===================================================================
--- branches/as7/connectors/translator-ldap/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-ldap/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <artifactId>connectors</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>translator-ldap</artifactId>

Modified: branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -53,6 +53,7 @@
 	private String searchDefaultBaseDN;
 	private boolean restrictToObjectClass;
 	private SearchDefaultScope searchDefaultScope = SearchDefaultScope.ONELEVEL_SCOPE;
+	private boolean usePagination;
 	
 	public LDAPExecutionFactory() {
 		this.setMaxInCriteriaSize(1000);
@@ -89,7 +90,7 @@
 	@Override
 	public ResultSetExecution createResultSetExecution(QueryExpression command,ExecutionContext executionContext, RuntimeMetadata metadata, LdapContext context)
 			throws TranslatorException {
-		return new LDAPSyncQueryExecution((Select)command, this, context);
+		return new LDAPSyncQueryExecution((Select)command, this, executionContext, context);
 	}
 	
 	@Override
@@ -142,5 +143,15 @@
 	@Override
 	public boolean supportsNotCriteria() {
 		return true;
+	}
+
+	@TranslatorProperty(display="Use Pagination", description="Use a PagedResultsControl to page through large results.  This is not supported by all directory servers.")
+	public boolean usePagination() {
+		return usePagination;
 	}	
+	
+	public void setUsePagination(boolean usePagination) {
+		this.usePagination = usePagination;
+	}
+	
 }

Modified: branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPSyncQueryExecution.java
===================================================================
--- branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPSyncQueryExecution.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-ldap/src/main/java/org/teiid/translator/ldap/LDAPSyncQueryExecution.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -91,6 +91,8 @@
 import javax.naming.directory.SearchResult;
 import javax.naming.ldap.Control;
 import javax.naming.ldap.LdapContext;
+import javax.naming.ldap.PagedResultsControl;
+import javax.naming.ldap.PagedResultsResponseControl;
 import javax.naming.ldap.SortControl;
 import javax.naming.ldap.SortKey;
 
@@ -98,6 +100,7 @@
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.metadata.Column;
+import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.ResultSetExecution;
 import org.teiid.translator.TranslatorException;
 import org.teiid.translator.TypeFacility;
@@ -119,6 +122,8 @@
 	private IQueryToLdapSearchParser parser;
 	private Select query;
 	private LDAPExecutionFactory executionFactory;
+	private ExecutionContext executionContext;
+	private SearchControls ctrls;
 
 	/** 
 	 * Constructor
@@ -127,10 +132,11 @@
 	 * @param logger the ConnectorLogger
 	 * @param ldapCtx the LDAP Context
 	 */
-	public LDAPSyncQueryExecution(Select query, LDAPExecutionFactory factory, LdapContext ldapCtx) {
+	public LDAPSyncQueryExecution(Select query, LDAPExecutionFactory factory, ExecutionContext context, LdapContext ldapCtx) {
 		this.ldapConnection = ldapCtx;
 		this.query = query;
 		this.executionFactory = factory;
+		this.executionContext = context;
 	}
 
 	/** 
@@ -146,31 +152,40 @@
 
 		// Create and configure the new search context.
 		createSearchContext();
-		SearchControls ctrls = setSearchControls();
-		setStandardRequestControls();
+		ctrls = setSearchControls();
+		String ctxName = searchDetails.getContextName();
+		String filter = searchDetails.getContextFilter();
+		if (ctxName == null || filter == null || ctrls == null) {
+			throw new TranslatorException(LogConstants.CTX_CONNECTOR, "Search context, filter, or controls were null. Cannot execute search."); //$NON-NLS-1$
+		}
+		setRequestControls(null);
 		// Execute the search.
-		executeSearch(ctrls);
+		executeSearch();
 	}
 
 	/** 
 	 * Set the standard request controls
 	 */
-	private void setStandardRequestControls() throws TranslatorException {
-		Control[] sortCtrl = new Control[1];
+	private void setRequestControls(byte[] cookie) throws TranslatorException {
+		List<Control> ctrl = new ArrayList<Control>();
 		SortKey[] keys = searchDetails.getSortKeys();
-		if (keys != null) {
-			try {
-				sortCtrl[0] = new SortControl(keys, Control.NONCRITICAL);
-				this.ldapCtx.setRequestControls(sortCtrl);
-				LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Sort ordering was requested, and sort control was created successfully."); //$NON-NLS-1$
-			} catch (NamingException ne) {
-	            final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError") +  //$NON-NLS-1$
-	            " : "+ne.getExplanation(); //$NON-NLS-1$
-				throw new TranslatorException(msg);
-			} catch(IOException e) {
-	            final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError"); //$NON-NLS-1$
-				throw new TranslatorException(e,msg);
+		try {			
+			if (keys != null) {
+				ctrl.add(new SortControl(keys, Control.NONCRITICAL));
 			}
+			if (this.executionFactory.usePagination()) {
+				ctrl.add(new PagedResultsControl(this.executionContext.getBatchSize(), cookie, Control.CRITICAL));
+			}
+			if (!ctrl.isEmpty()) {
+				this.ldapCtx.setRequestControls(ctrl.toArray(new Control[ctrl.size()]));
+				LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Sort/pagination controls were created successfully."); //$NON-NLS-1$
+			}
+		} catch (NamingException ne) {
+            final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.setControlsError") +  //$NON-NLS-1$
+            " : "+ne.getExplanation(); //$NON-NLS-1$
+			throw new TranslatorException(ne, msg);
+		} catch(IOException e) {
+			throw new TranslatorException(e);
 		}
 	}
 
@@ -219,22 +234,14 @@
 	 * Perform the LDAP search against the subcontext, using the filter and 
 	 * search controls appropriate to the query and model metadata.
 	 */
-	private void executeSearch(SearchControls ctrls) throws TranslatorException {
-		String ctxName = searchDetails.getContextName();
+	private void executeSearch() throws TranslatorException {
 		String filter = searchDetails.getContextFilter();
-		if (ctxName == null || filter == null || ctrls == null) {
-			LogManager.logError(LogConstants.CTX_CONNECTOR, "Search context, filter, or controls were null. Cannot execute search."); //$NON-NLS-1$
-		}
 		try {
 			searchEnumeration = this.ldapCtx.search("", filter, ctrls); //$NON-NLS-1$
 		} catch (NamingException ne) {
-			LogManager.logError(LogConstants.CTX_CONNECTOR, "LDAP search failed. Attempted to search context " //$NON-NLS-1$
-					+ ctxName + " using filter " + filter); //$NON-NLS-1$
             final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.execSearchError"); //$NON-NLS-1$
-			throw new TranslatorException(msg + " : " + ne.getExplanation());  //$NON-NLS-1$ 
+			throw new TranslatorException(ne, msg + " : " + ne.getExplanation());  //$NON-NLS-1$ 
 		} catch(Exception e) {
-			LogManager.logError(LogConstants.CTX_CONNECTOR, "LDAP search failed. Attempted to search context " //$NON-NLS-1$
-					+ ctxName + " using filter " + filter); //$NON-NLS-1$
             final String msg = LDAPPlugin.Util.getString("LDAPSyncQueryExecution.execSearchError"); //$NON-NLS-1$
 			throw new TranslatorException(e, msg); 
 		}
@@ -294,6 +301,27 @@
 				SearchResult searchResult = (SearchResult) searchEnumeration.next();
 				result = getRow(searchResult);
 			}
+			
+			if (result == null && this.executionFactory.usePagination()) {
+			    byte[] cookie = null;
+				Control[] controls = ldapCtx.getResponseControls();
+		        if (controls != null) {
+		        	for (int i = 0; i < controls.length; i++) {
+		        		if (controls[i] instanceof PagedResultsResponseControl) {
+		        			PagedResultsResponseControl prrc = (PagedResultsResponseControl)controls[i];
+		                    cookie = prrc.getCookie();
+		        		}
+		        	}
+		        }
+		        
+		        if (cookie == null) {
+		        	return null;
+		        }
+	
+		        setRequestControls(cookie);
+		        executeSearch();
+		        return next();
+			}
 
 			return result;
 		} catch (SizeLimitExceededException e) {
@@ -451,22 +479,4 @@
 		}
 	}
 	
-
-	/**
-	 * Active Directory and OpenLDAP supports PagedResultsControls, so I left
-	 * this method in here in case we decide to extend support for this control
-	 * in the future.
-	 */
-//	private void setADRequestControls(int maxBatchSize) {
-//		try {
-//			ldapCtx.setRequestControls(new Control[] { new PagedResultsControl(
-//					maxBatchSize, Control.CRITICAL) });
-//		} catch (NamingException ne) {
-//			logger.logError("Failed to set page size for LDAP results. Please ensure that paged results controls are supported by the LDAP server implementation."); //$NON-NLS-1$
-//			ne.printStackTrace();
-//		} catch (IOException ioe) {
-//			logger.logError("IO Exception while setting paged results control."); //$NON-NLS-1$
-//			ioe.printStackTrace();
-//		}
-//	}
 }

Modified: branches/as7/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java
===================================================================
--- branches/as7/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-ldap/src/test/java/org/teiid/translator/ldap/TestIQueryToLdapSearchParser.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -47,7 +47,6 @@
 import org.teiid.query.metadata.CompositeMetadataStore;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.TranslatorException;
 import org.teiid.translator.ldap.IQueryToLdapSearchParser;
@@ -304,7 +303,7 @@
         }
         
         // Create the facade from the store
-        return new TransformationMetadata(null, new CompositeMetadataStore(metadataStore), null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+        return new TransformationMetadata(null, new CompositeMetadataStore(metadataStore), null, RealMetadataFactory.SFM.getSystemFunctions(), null);
     }    
 }
 

Modified: branches/as7/connectors/translator-loopback/pom.xml
===================================================================
--- branches/as7/connectors/translator-loopback/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-loopback/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>translator-loopback</artifactId>

Modified: branches/as7/connectors/translator-olap/pom.xml
===================================================================
--- branches/as7/connectors/translator-olap/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-olap/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>translator-olap</artifactId>

Modified: branches/as7/connectors/translator-olap/src/main/java/org/teiid/translator/olap/OlapQueryExecution.java
===================================================================
--- branches/as7/connectors/translator-olap/src/main/java/org/teiid/translator/olap/OlapQueryExecution.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-olap/src/main/java/org/teiid/translator/olap/OlapQueryExecution.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -54,9 +54,9 @@
     protected OlapExecutionFactory executionFactory;
     private OlapStatement stmt;
     private CellSet cellSet;
-    private CellSetAxis cols;
+    private CellSetAxis columnsAxis;
     private int colWidth;
-    private ListIterator<Position> iterator;
+    private ListIterator<Position> rowPositionIterator;
     
 	public OlapQueryExecution(Command command, OlapConnection connection, ExecutionContext context, OlapExecutionFactory executionFactory) {
 		this.command = command;
@@ -74,10 +74,10 @@
 			stmt = this.connection.createStatement();
 			
 			cellSet = stmt.executeOlapQuery(mdxQuery);
-			CellSetAxis rows = this.cellSet.getAxes().get(Axis.ROWS.axisOrdinal());
-			iterator = rows.iterator();
-			cols = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());
-	    	colWidth = rows.getAxisMetaData().getHierarchies().size() + this.cols.getPositions().size();
+			CellSetAxis rowAxis = this.cellSet.getAxes().get(Axis.ROWS.axisOrdinal());
+			rowPositionIterator = rowAxis.iterator();
+			columnsAxis = cellSet.getAxes().get(Axis.COLUMNS.axisOrdinal());
+	    	colWidth = rowAxis.getAxisMetaData().getHierarchies().size() + this.columnsAxis.getPositions().size();
 		} catch (SQLException e) {
 			throw new TranslatorException(e);
 		} 
@@ -109,22 +109,22 @@
 	
     @Override
     public List<?> next() throws TranslatorException {
-    	if (!iterator.hasNext()) {
+    	if (!rowPositionIterator.hasNext()) {
     		return null;
     	}
-    	Position nextRow = iterator.next();
+    	Position rowPosition = rowPositionIterator.next();
     	Object[] result = new Object[colWidth];
     	int i = 0;
     	// add in rows axis
-		List<Member> members = nextRow.getMembers();
+		List<Member> members = rowPosition.getMembers();
 		for (Member member:members) {
-			String columnName = member.getHierarchy().getName();
+			String columnName = member.getName();
 			result[i++] = columnName;
 		}
 
 		// add col axis
-		for (Position colPos : cols) {
-			Cell cell = cellSet.getCell(colPos, nextRow);
+		for (Position colPos : columnsAxis) {
+			Cell cell = cellSet.getCell(colPos, rowPosition);
 			result[i++] = cell.getValue();
 		}	
 		ArrayList<Object[]> results = new ArrayList<Object[]>();

Modified: branches/as7/connectors/translator-salesforce/pom.xml
===================================================================
--- branches/as7/connectors/translator-salesforce/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-salesforce/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>connectors</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>translator-salesforce</artifactId>

Modified: branches/as7/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java
===================================================================
--- branches/as7/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-salesforce/src/main/java/org/teiid/translator/salesforce/SalesForceExecutionFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,20 +22,18 @@
 
 package org.teiid.translator.salesforce;
 
-import java.util.ArrayList;
-import java.util.Collections;
+import static org.teiid.translator.TypeFacility.RUNTIME_NAMES.*;
+
+import java.util.Arrays;
 import java.util.List;
 
 import javax.resource.cci.ConnectionFactory;
 
-import org.teiid.core.types.DataTypeManager;
 import org.teiid.language.Call;
 import org.teiid.language.Command;
 import org.teiid.language.QueryExpression;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
 import org.teiid.metadata.MetadataFactory;
 import org.teiid.metadata.RuntimeMetadata;
 import org.teiid.translator.ExecutionContext;
@@ -88,7 +86,9 @@
 	@Override
 	public void start() throws TranslatorException {
 		super.start();
-		LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Started"); //$NON-NLS-1$
+		addPushDownFunction(SALESFORCE, INCLUDES, BOOLEAN, STRING, STRING);
+		addPushDownFunction(SALESFORCE, EXCLUDES, BOOLEAN, STRING, STRING);
+		LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Salesforce ExecutionFactory Started"); //$NON-NLS-1$
 	}
 
 
@@ -124,28 +124,11 @@
 	}	
 	
     @Override
-    public List getSupportedFunctions() {
-        return Collections.EMPTY_LIST;
+    public List<String> getSupportedFunctions() {
+        return Arrays.asList(INCLUDES, EXCLUDES);
     }
     
     @Override
-    public List<FunctionMethod> getPushDownFunctions(){
-    	List<FunctionMethod> pushdownFunctions = new ArrayList<FunctionMethod>();
-		pushdownFunctions.add(new FunctionMethod(SALESFORCE + '.' +INCLUDES, INCLUDES, SALESFORCE, 
-            new FunctionParameter[] {
-                new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("param", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-            new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$
-		
-		pushdownFunctions.add(new FunctionMethod(SALESFORCE + '.' + EXCLUDES, EXCLUDES, SALESFORCE, 
-                new FunctionParameter[] {
-                    new FunctionParameter("columnName", DataTypeManager.DefaultDataTypes.STRING, ""), //$NON-NLS-1$ //$NON-NLS-2$
-                    new FunctionParameter("param", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.BOOLEAN, "") ) ); //$NON-NLS-1$ //$NON-NLS-2$    		
-    	return pushdownFunctions;    	
-    }
-
-    @Override
     public boolean supportsCompareCriteriaEquals() {
         return true;
     }

Modified: branches/as7/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java
===================================================================
--- branches/as7/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-salesforce/src/test/java/org/teiid/translator/salesforce/execution/visitors/TestVisitors.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -44,7 +44,6 @@
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.TypeFacility;
@@ -113,10 +112,10 @@
         params.add(RealMetadataFactory.createParameter("start", SPParameter.IN, TypeFacility.RUNTIME_NAMES.TIMESTAMP));
         params.add(RealMetadataFactory.createParameter("end", SPParameter.IN, TypeFacility.RUNTIME_NAMES.TIMESTAMP));
         
-        Procedure getUpdated = RealMetadataFactory.createStoredProcedure("GetUpdated", salesforceModel, params, "GetUpdated");
+        Procedure getUpdated = RealMetadataFactory.createStoredProcedure("GetUpdated", salesforceModel, params);
         getUpdated.setResultSet(RealMetadataFactory.createResultSet("rs", new String[] {"updated"}, new String[] {TypeFacility.RUNTIME_NAMES.STRING}));
         
-        return new TransformationMetadata(null, new CompositeMetadataStore(store), null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+        return new TransformationMetadata(null, new CompositeMetadataStore(store), null, RealMetadataFactory.SFM.getSystemFunctions(), null);
     }    
 
 	private static TranslationUtility translationUtility = new TranslationUtility(exampleSalesforce());

Modified: branches/as7/connectors/translator-ws/pom.xml
===================================================================
--- branches/as7/connectors/translator-ws/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/connectors/translator-ws/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
     <parent>
         <artifactId>connectors</artifactId>
         <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
+        <version>7.6.0.Alpha1-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
     <artifactId>translator-ws</artifactId>

Modified: branches/as7/console/pom.xml
===================================================================
--- branches/as7/console/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/console/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 
 	<modelVersion>4.0.0</modelVersion>

Modified: branches/as7/console/src/main/resources/META-INF/rhq-plugin.xml
===================================================================
--- branches/as7/console/src/main/resources/META-INF/rhq-plugin.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/console/src/main/resources/META-INF/rhq-plugin.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -387,16 +387,16 @@
 					displayName="Connector Batch Size"
 					description="The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024)"
 					required="false" readOnly="false" />
-				<c:simple-property name="BufferService.maxProcessingBatchesColumns"
-					displayName="Max Processing Batches Columns"
-					description="The number of batch columns guarenteed to a processing operation.  Set this value lower if the workload typically processes larger numbers of concurrent queries with large intermediate results from operations such as sorting, grouping, etc. (default 128)"
+				<c:simple-property name="BufferService.maxProcessingKb"
+					displayName="Max Processing Memory"
+					description="The approximate amount of buffer memory in kilobytes allowable for a single processing operation (sort, grouping, etc.) regardless of existing memory commitments. -1 means to automatically calculate a value (default -1)."
 					required="false" readOnly="false" />
 				<c:simple-property name="BufferService.maxFileSize" displayName="Max File Size"
 					description="Max file size for buffer files (default 2GB)"
 					required="false" readOnly="false" />
-				<c:simple-property name="BufferService.maxReserveBatchColumns"
-					displayName="Max Reserve Batch Columns"
-					description="The number of batch columns to allow in memory (default 16384).  This value should be set lower or higher depending on the available memory to Teiid in the VM.  16384 is considered a good default for a dedicated 32-bit VM running Teiid with a 1 gig heap."
+				<c:simple-property name="BufferService.maxReserveKb"
+					displayName="Max Reserve Memory"
+					description="The approximate amount of memory in kilobytes allowed to be held by the buffer manager. -1 means to automatically calculate a value (default -1)."
 					required="false" readOnly="false" />
 			</c:group>
 			<c:group name="JdbcSocketConfiguration"	displayName="Jdbc Socket Configuration Properties" hiddenByDefault="false">

Modified: branches/as7/documentation/admin-guide/pom.xml
===================================================================
--- branches/as7/documentation/admin-guide/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/admin-guide/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <groupId>org.jboss.teiid</groupId>
     <artifactId>documentation</artifactId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>admin-guide</artifactId>

Modified: branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/admin-console.xml
===================================================================
--- branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/admin-console.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/admin-console.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,92 +1,199 @@
-<?xml version="1.0" encoding="UTF-8"?>
+<?xml version='1.0'?>
 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
 <chapter id="admin-console">
-   <title>Teiid Admin Console</title>
-   <para>The Teiid Admin Console is a web based administrative and monitoring tool for Teiid. 
-   Teiid's Admin Console is built using the <ulink url="http://www.jboss.org/embjopr">Embedded JOPR</ulink> library and adds a additional plugin into the Embeeded JOPR program already available in the 
-   <ulink url="http://www.jboss.org/jbossas">JBoss AS</ulink>.</para>
-
-    <mediaobject>
-      <imageobject>
-        <imagedata scalefit="1" fileref="../images/admin_console.png"/>
-      </imageobject>
-    </mediaobject>
-    
-   <section>
-     <title>What can be monitored and/or configured?</title>
-     <para>Here are the steps to follow to install Teiid</para>
-
-     <orderedlist>
-        <listitem> <para><emphasis>The Teiid Runtime Engine</emphasis> (Data Services node in the tree)</para> </listitem>
-        <listitem> <para><emphasis>VDBs</emphasis> - Virtual databases</para> 
+  <title>Teiid Admin Console</title>
+  <para>The Teiid Admin Console is a web based administrative and 
+  monitoring tool for Teiid. Teiid&apos;s Admin Console is built using 
+  the <ulink url="http://www.jboss.org/embjopr">Embedded JOPR</ulink> 
+  library and adds a additional plugin into the Embedded JOPR program 
+  already available in the <ulink url="http://www.jboss.org/jbossas">
+  JBoss AS</ulink>.</para>
+  <mediaobject><imageobject>
+  <imagedata fileref="../images/admin_console.png" scalefit="1"/></imageobject></mediaobject>
+  <section>
+    <title>What can be monitored and/or configured?</title>
+    <para>Here are the steps to follow to install Teiid</para>
+    <orderedlist>
+      <listitem>
+        <para><emphasis>The Teiid Runtime Engine</emphasis> (Data 
+        Services node in the tree)</para>
+      </listitem>
+      <listitem>
+        <para><emphasis>VDBs</emphasis> - Virtual databases</para>
+        <orderedlist>
+          <listitem>
+            <para><emphasis>Models</emphasis></para>
             <orderedlist>
-                <listitem> <para><emphasis>Models</emphasis></para> 
-                    <orderedlist>
-                        <listitem> <para><emphasis>Source</emphasis>- these are physical sources</para></listitem>
-                        <listitem> <para><emphasis>Multi-source</emphasis> - these are multiple sourced models</para></listitem>
-                        <listitem> <para><emphasis>Logical</emphasis> - these are virtual sources</para></listitem>
-                    </orderedlist>
-                </listitem>
-                <listitem> <para><emphasis>Translator instances</emphasis>- any Translator instances defined for use by this VDB</para> </listitem>
+              <listitem>
+                <para><emphasis>Source</emphasis>- these are physical 
+                sources</para>
+              </listitem>
+              <listitem>
+                <para><emphasis>Multi-source</emphasis> - these are 
+                multiple sourced models</para>
+              </listitem>
+              <listitem>
+                <para><emphasis>Logical</emphasis> - these are virtual 
+                sources</para>
+              </listitem>
             </orderedlist>
+          </listitem>
+          <listitem>
+            <para><emphasis>Translator instances</emphasis>- any 
+            Translator instances defined for use by this VDB</para>
+          </listitem>
+          <listitem>
+            <para><emphasis>Data Roles</emphasis>- any 
+            data roles defined for use by this VDB</para>
+          </listitem>
+        </orderedlist>
+      </listitem>
+      <listitem>
+        <para>Translators - These are the extensions to supported 
+        datasources that come with Teiid out-of-the-box.</para>
+      </listitem>
+    </orderedlist>
+    <note>
+      <para>The creation/modification of the datasource is managed by 
+      the JBossAS plugin.</para>
+    </note>
+    <section>
+      <title>Configuration</title>
+      <orderedlist>
+        <listitem>
+          <para>Settings for the Data Services plugin</para>
         </listitem>
-        <listitem> <para>Translators - These are the extensions to supported datasources that come with Teiid out-of-the-box.</para> </listitem>
-     </orderedlist>
-     
-     <note>
-        <para>The creation/modification of the datasource is managed by the JBossAS plugin.</para>
-     </note>    
-    
+        <listitem>
+          <para>Runtime Engine properties</para>
+        </listitem>
+        <listitem>
+          <para>Buffer Service</para>
+        </listitem>
+        <listitem>
+          <para>Jdbc Socket configuration</para>
+        </listitem>
+        <listitem>
+          <para>Session Service</para>
+        </listitem>
+      </orderedlist>
+    </section>
     <section>
-        <title>Configuration</title>
-        <orderedlist>
-            <listitem> <para>Runtime Engine properties</para> </listitem>
-            <listitem> <para>Buffer Service</para> </listitem>
-            <listitem> <para>Jdbc Socket configuration</para> </listitem>
-            <listitem> <para>Session Service</para> </listitem>
-        </orderedlist>
+      <title>Metrics</title>
+      <orderedlist>
+        <listitem>
+          <para>Long Running Query count</para>
+        </listitem>
+        <listitem>
+          <para>Active Query count</para>
+        </listitem>
+        <listitem>
+          <para>Active Session count</para>
+        </listitem>
+        <listitem>
+          <para>Prepared Plan Cache Hit Ratio %</para>
+        </listitem>
+        <listitem>
+          <para>Prepared Plan Cache Size</para>
+        </listitem>
+        <listitem>
+          <para>Prepared Plan Cache # of Requests</para>
+        </listitem>
+        <listitem>
+          <para>ResultSet Cache Hit Ratio %</para>
+        </listitem>
+        <listitem>
+          <para>ResultSet Cache Size</para>
+        </listitem>
+        <listitem>
+          <para>ResultSet Cache # of Requests</para>
+        </listitem>
+        <listitem>
+          <para>Used Buffer Space</para>
+        </listitem>
+      </orderedlist>
     </section>
-    
     <section>
-        <title>Metrics</title>
+      <title>Control (Operations)</title>
+      <listitem>
+        <para>Data Services Engine</para>
         <orderedlist>
-            <listitem> <para>Long Running Query count</para> </listitem>
-            <listitem> <para>Active Query count</para> </listitem>
-            <listitem> <para>Active Session count</para> </listitem>
+          <listitem>
+            <para>View Long Running Queries</para>
+          </listitem>
+          <listitem>
+            <para>View Current Sessions</para>
+          </listitem>
+          <listitem>
+            <para>Deploy a VDB via URL</para>
+          </listitem>
+          <listitem>
+            <para>Terminate Session</para>
+          </listitem>
+          <listitem>
+            <para>View Current Requests</para>
+          </listitem>
+          <listitem>
+            <para>Terminate requests</para>
+          </listitem>
+          <listitem>
+            <para>View Current Transactions</para>
+          </listitem>
+          <listitem>
+            <para>Terminate Transaction</para>
+          </listitem>
         </orderedlist>
-    </section>    
-   
-    <section>
-        <title>Control (Operations)</title>
+      </listitem>
+      <listitem>
+        <para>Virtual Database</para>
         <orderedlist>
-            <listitem> <para>View Long Running Queries</para> </listitem>
-            <listitem> <para>View Current Sessions</para> </listitem>
-            <listitem> <para>Terminate Session</para> </listitem>
-            <listitem> <para>View Current Requests</para> </listitem>
-            <listitem> <para>Terminate requests</para> </listitem>
-            <listitem> <para>View Current Transactions</para> </listitem>
-            <listitem> <para>Terminate Transaction</para> </listitem>
+          <listitem>
+            <para>View VDB Requests</para>
+          </listitem>
+          <listitem>
+            <para>View VDB Sessions</para>
+          </listitem>
+          <listitem>
+            <para>List Materialized View Info</para>
+          </listitem>
+          <listitem>
+            <para>Refresh a Materialized View</para>
+          </listitem>
+          <listitem>
+            <para>Clear Cache</para>
+          </listitem>
         </orderedlist>
+      </listitem>
     </section>
-    
     <section id="vdb_deploy">
-        <title>Deploying the VDB</title>
-        <para>VDB archive files created it the Designer Tool or Dynamic VDBs can be deployed into Teiid server using
-        the Admin Console.</para>
-        
-        <orderedlist>
-            <listitem> <para>Select the Virtual Database node in the Admin Console tree and click the Add New Resource button.</para> </listitem>
-            <listitem> <para>Select the VDB archive file from the file system and click continue.</para> </listitem>
-            <listitem> <para>The VDB will deploy if no fatal errors are found in the archive. The status of
-             the VDB will be UP if no errors are found with the models in the VDB.</para> </listitem>
-            <listitem> <para>If there are model errors, the VDB will be deployed with a status of DOWN and the errors will be 
-            listed on the configuration tab of the VDB. VDBs that are not UP will be marked with a red X in the tree.</para> </listitem>
-        </orderedlist>       
-        
-        <para>Only Model's "connection-jndi-name" can be modified using this tool by clicking on the "configuration" 
-        tab, all other proeprties are read-only.</para> 
-    </section>    
-        
-   </section>   
-   
-</chapter>
\ No newline at end of file
+      <title>Deploying the VDB</title>
+      <para>VDB archive files created it the Designer Tool or Dynamic 
+      VDBs can be deployed into Teiid server using the Admin 
+      Console.</para>
+      <orderedlist>
+        <listitem>
+          <para>Select the Virtual Database node in the Admin Console 
+          tree and click the Add New Resource button.</para>
+        </listitem>
+        <listitem>
+          <para>Select the VDB archive file from the file system and 
+          click continue.</para>
+        </listitem>
+        <listitem>
+          <para>The VDB will deploy if no fatal errors are found in the 
+          archive. The status of the VDB will be UP if no errors are 
+          found with the models in the VDB.</para>
+        </listitem>
+        <listitem>
+          <para>If there are model errors, the VDB will be deployed 
+          with a status of DOWN and the errors will be listed on the 
+          configuration tab of the VDB. VDBs that are not UP will be 
+          marked with a red X in the tree.</para>
+        </listitem>
+      </orderedlist>
+      <para>Only Model&apos;s &quot;connection-jndi-name&quot; can be 
+      modified using this tool by clicking on the 
+      &quot;configuration&quot; tab, all other properties are 
+      read-only.</para>
+    </section>
+  </section>
+</chapter>

Modified: branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/performance.xml
===================================================================
--- branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/performance.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/performance.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -18,12 +18,10 @@
 			accessing the Teiid server simultaneously.  
 		</para>
 		<para>
-			The <code>maxReserveBatchColumns</code>
-			setting determines the total size of batches that can be held by the BufferManager in memory.
-			This number does not include persistent batches held by soft (such as
+			The <code>maxReserveKb</code>
+			setting determines the total size in kilobytes of batches that can be held by the BufferManager in memory.
+			This number does not account for persistent batches held by soft (such as
 			index pages) or weak references. 
-			The value is treated internally as an approximation of bytes using the conversion
-			<code>maxReserveBatchColumns</code> * <code>processorBatchSize</code> * (64bytes per column value).
 			The default value of -1 will auto-calculate a typical max based upon the max heap available to the VM.  
 			The auto-calculated value assumes a 64bit architecture and will limit buffer usage to 50% of the first 
 			gigabyte of memory beyond the first 300 megabytes (which are assumed for use by the AS and other Teiid purposes) 
@@ -39,22 +37,21 @@
 		</para>
 		<note>
 			<para>Memory consumption can be significantly more or less than the nominal target
-	            depending upon actual column values and whether value caching is enabled.  Large strings, bigintegers, bigdecimals, or values typed as object can exceed their default size estimate.
-	            If an out of memory errors occur, then set a lower the maxReserveBatchColumns value.
+	            depending upon actual column values and whether value caching is enabled.  Large non built-in type objects can exceed their default size estimate.
+	            If an out of memory errors occur, then set a lower the maxReserveKb value.  Also note that source lob values are held by memory references that are not cleared when a batch is persisted.  
+	            With heavy lob usage you should ensure that buffers of other memory associated with lob references are appropiately sized.
 			</para>
 		</note>
 		<para>
-			The <code>maxProcessingBatchesColumns</code>
-			setting determines the total size of batches that can be used by active plans regardless of the memory held based on <code>maxReserveBatchColumns</code>.
-			The value is treated internally as an approximation of bytes using the conversion
-			<code>maxProcessingBatchesColumns</code> * <code>processorBatchSize</code> * (64bytes per column value).
+			The <code>maxProcessingKb</code>
+			setting determines the total size in kilobytes of batches that can be used by active plans regardless of the memory held based on <code>maxReserveKb</code>.
 			The default value of -1 will auto-calculate a typical max based upon the max heap available to the VM and max active plans.  
 			The auto-calculated value assumes a 64bit architecture and will limit processing batch usage to 10% of memory 
 			beyond the first 300 megabytes (which are assumed for use by the AS and other Teiid purposes).
 		</para>
 		<para>
-			In systems where large intermediate results are normal (scrolling cursors or sorting over millions of rows) you can consider increasing the <code>maxProcessingBatchColumns</code> and decreasing
-			the <code>maxReserveBatchColumns</code> so that each request has access to an effectively smaller buffer space.
+			In systems where large intermediate results are normal (scrolling cursors or sorting over millions of rows) you can consider increasing the <code>maxProcessingKb</code> and decreasing
+			the <code>maxReserveKb</code> so that each request has access to an effectively smaller buffer space.
 		</para>
 		<para>
 			Each intermediate result buffer, temporary LOB, and temporary table

Modified: branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/security.xml
===================================================================
--- branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/security.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/security.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -102,6 +102,115 @@
             If you want write your own Custom Login module, check out the Developer's Guide for instructions.
 	        </para>
 		</section>
+        
+        <section>
+            <title>Kerberos support through GSSAPI</title>
+            <para>Teiid supports kerberos authentication using GSSAPI, to be used with single sign-on applications.
+            This service ticket negotiation based authentication is supported through remote JDBC and ODBC drivers and as 
+            well as in LocalConnections. However, configuration is varies for local connections vs remote connections</para>
+            
+            <section>
+                <title>LocalConnection</title>
+                <para>For supporting kerberos through local connections, provide JDBC URL property <emphasis>PassthroughAuthentication</emphasis> 
+                as true and use the <ulink url="http://community.jboss.org/docs/DOC-10680">JBoss Negotiation</ulink> as 
+                authentication configure your web-application for kerberos. When the web application authenticates with the provided
+                kerberos token, the same subject authenticated will be used in Teiid. For details about configuration, check the 
+                JBoss Negotiation documentation.</para>
+            </section>
+            
+            <section>
+                <title>Remote JDBC Connection</title>
+                <para>Server: For supporting the kerberos through jdbc from a remote client application, follow the below configuration.
+                On the server, edit "{jboss-as}/server/{profile}/deploy/teiid/teiid-jboss-beans.xml" file, and make sure under 
+                "SessionService" bean definition the following properties are set.
+                <programlisting><![CDATA[   
+    <!-- Sets the authentication Type -->         
+    <property name="authenticationType">KRB5</property>
+    <!-- Security domain used for kerberos authentication -->
+    <property name="krb5SecurityDomain">teiid-krb5</property>    
+                ]]></programlisting>    
+                
+                Now we need to define security domain context for kerberos with name mentioned in above, and since the kerberos 
+                authorization can not define authorization roles, we need devise a way to define them using another login context. 
+                Given below is sample configuration to define roles using UserRolesLoginModule. 
+                Note that the below configuration replaces the default Teiid login configuration. Note to change the principal 
+                and key tab locations accordingly.
+                
+                <programlisting><![CDATA[   
+    <!--login module that negotiates the login conext for kerberos --> 
+    <application-policy xmlns="urn:jboss:security-beans:1.0" name="teiid-krb5">
+        <authentication>
+            <login-module code="com.sun.security.auth.module.Krb5LoginModule" flag="required">
+                <module-option name="storeKey">true</module-option>
+                <module-option name="useKeyTab">true</module-option>
+                <module-option  name="principal">demo at EXAMPLE.COM</module-option>
+                <module-option  name="keyTab">path/to/krb5.keytab</module-option>
+                <module-option name="doNotPrompt">true</module-option>
+                <module-option name="debug">false</module-option>
+            </login-module>  
+        </authentication>
+    </application-policy>      
+    
+    <!-- teiid's default security domain, replace this with your own if needs to be any other JAAS domain  -->
+    <application-policy xmlns="urn:jboss:security-beans:1.0" name="teiid-security">
+        <authentication>
+            <!-- This module assosiates kerberos user with this login set of login modules -->
+            <login-module code="org.teiid.jboss.AssosiateCallerIdentityLoginModule" flag="required"/>
+            <!-- Login module used for defining roles for user authencated using kerberos, keep the users file empty
+            but provide roles in the roles file for users -->
+            <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
+                <module-option name="password-stacking">useFirstPass</module-option>
+                <module-option name="usersProperties">props/teiid-security-users.properties</module-option>
+                <module-option name="rolesProperties">props/teiid-security-roles.properties</module-option>
+            </login-module>
+        </authentication>
+    </application-policy>    
+                ]]></programlisting>
+               Edit "run.conf" or "run.conf.bat"file depending upon the environment in "${jboss-as}/bin" directory 
+               and add the following JVM options to startup script (note to change the realm and KDC settings according to your environment)
+               <programlisting><![CDATA[   
+               JAVA_OPTS = "$JAVA_OPTS -Djava.security.krb5.realm=EXAMPLE.COM -Djava.security.krb5.kdc=kerberos.example.com -Djavax.security.auth.useSubjectCredsOnly=false"
+                ]]></programlisting>                                          
+            This finishes the configuration on the server side, restart the server and make sure that there were no errors during startup. 
+            </para>
+            
+            <para>Client: The following configuration needs to be done on the Teiid client application VM. For client VM, JAAS 
+            configuration for kerberos authentication needs to be written. A sample configuration file (client.conf) is show below
+            
+           <programlisting><![CDATA[   
+    Client {
+        com.sun.security.auth.module.Krb5LoginModule required
+        useTicketCache=true
+        storeKey=true
+        useKeyTab=true 
+        keyTab="/path/to/krb5.keytab" 
+        doNotPrompt=false 
+        debug=false
+        principal="demo at EXAMPLE.COM";
+    };
+            ]]></programlisting>                                          
+            
+            Add the following JVM options to your client's startup script, note the change Realm and KDC settings according to 
+            your environment
+           <programlisting><![CDATA[   
+        -Djava.security.krb5.realm=EXAMPLE.COM
+        -Djava.security.krb5.kdc=kerberos.example.com
+        -Djavax.security.auth.useSubjectCredsOnly=false
+        -Dsun.security.krb5.debug=false
+        -Djava.security.auth.login.config=/path/to/client.conf
+            ]]></programlisting>              
+            
+            Add the following URL connection properties to Teiid JDBC connection string
+            <programlisting><![CDATA[
+            authenticationType=KRB5;jaasName=Client;kerberosServicePrincipleName=demo at EXAMPLE.COM
+            ]]></programlisting>
+            There is no need to provide the user name and password, when the application is trying to make JDBC connection it
+            will authenticate locally and use the same user credetinals to neogitiate service token with server and grant the
+            connection. See Client Developer's guide for information on connection properties and how to configure data sources.
+            </para>
+            </section>
+
+        </section>        
 		
         <section>
             <title>Security at Data Source level</title>

Modified: branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/vdb-deployment.xml
===================================================================
--- branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/vdb-deployment.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/admin-guide/src/main/docbook/en-US/content/vdb-deployment.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -134,6 +134,17 @@
       <rar-name>teiid-connector-file.rar</rar-name>
       <connection-definition>javax.resource.cci.ConnectionFactory</connection-definition>      
       <config-property name="ParentDirectory">path-to-the-directory-of-data-file</config-property>
+      
+      <!-- Optional properties -->
+      
+      <!-- Set FileMapping to redirect specific relative paths (case sensitive) to alternative locations.
+           The string value specifies a map in the format key=value(,key=value)*
+           -->
+      <!-- <config-property name="FileMapping" type="java.lang.String">file1.txt=fileX.txt,file2.txt=fileY.txt</config-property> -->
+      
+      <!-- Set AllowParentPaths to false to disallow .. in paths.
+           This prevent requesting files that are not contained in the parent directory -->
+      <config-property name="AllowParentPaths" type="java.lang.Boolean">true</config-property>
    </no-tx-connection-factory>
 </connection-factories>]]></programlisting></example>             
         </section>

Modified: branches/as7/documentation/admin-guide/src/main/docbook/en-US/images/admin_console.png
===================================================================
(Binary files differ)

Modified: branches/as7/documentation/caching-guide/pom.xml
===================================================================
--- branches/as7/documentation/caching-guide/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/caching-guide/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <groupId>org.jboss.teiid</groupId>
     <artifactId>documentation</artifactId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>caching-guide</artifactId>

Modified: branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/codetable.xml
===================================================================
--- branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/codetable.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/codetable.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,7 +29,7 @@
 		<para>See the Reference for more information on use of the lookup function.</para>
 		<example>
 			<title>Country Code Lookup</title>
-			<programlisting>lookup(‘ISOCountryCodes, ‘CountryName’, ‘CountryCode’, ‘US’)</programlisting>
+			<programlisting>lookup('ISOCountryCodes', 'CountryName', 'CountryCode', 'US')</programlisting>
 		</example>
 	</section>
 	<section>
@@ -47,7 +47,12 @@
 	</section>
 	<section>
 		<title>Materialized View Alternative</title>
-		<para>The lookup function is a shortcut to create an internal materialized view.  In many situations, it may be better to directly create the analogous materialized view rather than to use a code table.</para>
+		<para>The lookup function is a shortcut to create an internal materialized view with an appropriate primary key.  In many situations, it may be better to directly create the analogous materialized view rather than to use a code table.</para>
+		<example>
+			<title>Country Code Lookup Against A Mat View</title>
+			<programlisting>SELECT (SELECT CountryCode From MatISOCountryCodes WHERE CountryName = tbl.CountryName) as cc FROM tbl</programlisting>
+			<para>Here MatISOCountryCodes is a view selecting from ISOCountryCodes that has been marked as materialized and has a primary key or index on CountryName.  The scalar subquery will use the index to lookup the country code for each country name in tbl.</para>
+		</example>
 		<itemizedlist>
 			<title>Reasons to use a materialized view:</title>
 			<listitem>
@@ -63,7 +68,7 @@
 				<para>The ability to use <link linkend="nocache">OPTION NOCACHE</link>.</para>
 			</listitem>
 			<listitem>
-				<para>Usage of a materialized view lookup as an uncorrelated subquery is no different than the use of the lookup function.</para>
+				<para>There is almost no performance difference.</para>
 			</listitem>
 		</itemizedlist>
 		<orderedlist>
@@ -72,7 +77,7 @@
 				<para>Create a view selecting the appropriate columns from the desired table.  In general, this view may have an arbitrarily complicated transformation query.</para>
 			</listitem>
 			<listitem>
-				<para>Designate the appropriate column(s) as the primary key.</para>
+				<para>Designate the appropriate column(s) as the primary key.  Additional indexes can be added if needed.</para>
 				</listitem>
 			<listitem>
 				<para>Set the materialized property to true.</para>

Modified: branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/matviews.xml
===================================================================
--- branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/matviews.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/caching-guide/src/main/docbook/en-US/content/matviews.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -120,6 +120,22 @@
 			subsequent refreshes performed with <code>refreshMatView</code> will use dependent materialized view tables if they exist.  Only one load may occur at a time.  If a load is already in progress when
 			the <code>SYSADMIN.refreshMatView</code> procedure is called, it will return -1 immediately rather than preempting the current load.
 			</para>
+            <para>
+            When Teiid is running clustered mode, after of loading of internal materialized view contents, an event will be sent to all
+            the other participating nodes in the cluster to refresh the contents from the original node in asynchronus fashion.
+            During this remote node loading process, if the node that is reading the contents gets a request from user to serve the
+            results of that view, then the current results in cache will be served. If no results were available at that node, then 
+            request will be blocked until load process is finished.
+            </para>
+            <para>
+            When a Teiid node joins the cluster, at the end of start-up cycle, an asynchronus job
+            will be started to fetch all the previously cached internal materialized views at other nodes
+            for the deployed VDBs. The query request behaviour during this load process is same as above. 
+            </para>  
+            <note><para>In the clustered mode, the "invalidate=true" flag in the "SYSADMIN.refreshMatView" procedure
+            will only apply to the node that is refreshing the contents from source. All other nodes, will still serve the 
+            old contents during the refresh process.</para>
+            </note>          
 			<section>
 		   		<title>TTL Snapshot Refresh</title>
 		   		<para>The <link linkend="cache-hint">cache hint</link> may be used to automatically trigger a full snapshot refresh after a specified time to live (ttl).  

Modified: branches/as7/documentation/client-developers-guide/pom.xml
===================================================================
--- branches/as7/documentation/client-developers-guide/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/client-developers-guide/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <groupId>org.jboss.teiid</groupId>
     <artifactId>documentation</artifactId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>client-developers-guide</artifactId>

Modified: branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml
===================================================================
--- branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-connection.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -223,7 +223,16 @@
                         to create session. Teiid also verifies that the same user is using this connection during the life of the connection.
                         if it finds a different security context on the calling thread, it switches the identity on the connection,
                         if the new user is also eligible to log in to Teiid otherwise connection fails to execute.</entry>
-                    </row>                     
+                    </row>
+                    <row id="useCallingThread">
+                        <entry>
+                            <code>useCallingThread</code>
+                        </entry>
+                        <entry>
+                            <code>boolean</code>
+                        </entry>
+                        <entry>Only applies to "local" connections. When this option is set to "true" (the default), then the calling thread will be used to process the query.  If false, then an engine thread will be used.</entry>
+                    </row>                        
                     <row>
                     	<entry>
                             <code>QueryTimeout</code>
@@ -233,6 +242,58 @@
                         </entry>
                         <entry>Default query timeout in seconds. Must be >= 0. 0 indicates no timeout. Can be overriden by <code>Statement.setQueryTimeout</code>. Default 0.</entry>
                     </row>
+                    <row>
+                        <entry>
+                            <code>useJDBC4ColumnNameAndLabelSemantics</code>
+                        </entry>
+                        <entry>
+                            <code>boolean</code>
+                        </entry>						
+                        <entry>
+                           <para>A change was made in JDBC4 to return unaliased column names as the ResultSetMetadata column name. 
+                            Prior to this, if a column alias were used it was returned as the column name.   Setting this property to false will enable
+							backwards compatibility when JDBC3 and older support is still required.  Defaults to true.
+							</para>
+                        </entry>
+                    </row>
+                    <row>
+                        <entry>
+                            <code>authenticationType</code>
+                        </entry>
+                        <entry>
+                            <code>String</code>
+                        </entry>                        
+                        <entry>
+                           <para>Type of authentication to use. Valid values are CLEARTEXT (default) and KRB5 (kerberos). See 
+                           Admin Guide for configuration required for kerberos
+                            </para>
+                        </entry>
+                    </row>                      
+                    <row>
+                        <entry>
+                            <code>jaasName</code>
+                        </entry>
+                        <entry>
+                            <code>String</code>
+                        </entry>                        
+                        <entry>
+                           <para>JAAS configuration name. Only applies when configuring a kerberos authentication.
+                           See Admin Guide for configuration required for kerberos</para>
+                        </entry>
+                    </row>                      
+                    <row>
+                        <entry>
+                            <code>kerberosServicePrincipleName</code>
+                        </entry>
+                        <entry>
+                            <code>String</code>
+                        </entry>                        
+                        <entry>
+                           <para>Kerberos authenticated principle name. Only applies when configuring a kerberos authentication.
+                           See Admin Guide for configuration required for kerberos</para>
+                        </entry>
+                    </row>                      
+                    						
                 </tbody>
             </tgroup>
         </table> 
@@ -458,7 +519,8 @@
            there is a way to make connections that by-pass making a socket based JDBC connection.
            You can use slightly modified data source configuration to make a "local" connection, where the JDBC API will lookup a local Teiid runtime in the same VM.</para>
            <warning><para>Since DataSources start before before Teiid VDBs are deployed, leave the min pool size of local connections as the default of 0.  Otherwise errors will occur on the startup of the Teiid DataSource.</para></warning>
-           <note><para>Local connections use their calling thread to perform processing operations rather than using an engine thread while the calling thread is blocked.</para></note>
+           <note><para>Be default local connections use their calling thread to perform processing operations rather than using an engine thread while the calling thread is blocked.
+            To disable this behavior set the connection property useCallingThreads=false.</para></note>
            <example>
            <title>Local data source</title>
            <programlisting><![CDATA[<datasources>
@@ -541,7 +603,7 @@
         	The Teiid driver/DataSource should then typically be configured to just use the single host/port of your load balancer.</para>
         </section>
     </section>
-    <section>
+    <section id="reauthentication">
     	<title>Reauthentication</title>
     	<para>Teiid connections (defined by the <code>org.teiid.jdbc.TeiidConnection</code> interface) support the changeUser method to reauthenticate a given connection.  
     	If the reauthentication is successful the current connection my be used with the given identity.  

Modified: branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml
===================================================================
--- branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/jdbc-extensions.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -170,6 +170,14 @@
                             <para>Same as the connection property.</para>
                         </entry>
                     </row>
+                    <row>
+                        <entry>
+                            <code>JDBC4COLUMNNAMEANDLABELSEMANTICS / useJDBC4ColumnNameAndLabelSemantics</code>
+                        </entry>
+                        <entry>
+                            <para>Same as the connection property.</para>
+                        </entry>
+                    </row>						
                  </tbody>
              </tgroup>
         </table>        
@@ -185,7 +193,7 @@
             <para>SET Syntax:
             </para>
             <listitem>
-                <para>SET parameter value
+                <para>SET (parameter|SESSION AUTHORIZATION) value
                 </para>
             </listitem>
         </itemizedlist>
@@ -193,10 +201,10 @@
             <para>Syntax Rules:
             </para>
             <listitem>
-                <para>Both parameter and value must be simple literals - they cannot contain spaces.</para>
+                <para>The parameter must be a non-quoted identifier - it cannot contain spaces.</para>
             </listitem>
             <listitem>
-                <para>The value is also not treated as an expression and will not be evaluated prior to being set as the parameter value.</para>
+                <para>The value may be either a non-quoted identifier or a quoted string literal value.</para>
             </listitem>
         </itemizedlist>
         <para>The SET statement is most commonly used to control planning and execution.</para>
@@ -208,7 +216,6 @@
                 <para>SET NOEXEC (ON|OFF)</para>
             </listitem>
         </itemizedlist>        
-        
         <example id="plan_debug">
         	<title>Enabling Plan Debug</title>
         	<programlisting>Statement s = connection.createStatement();
@@ -222,6 +229,16 @@
 String debugLog = planRs.getString("DEBUG_LOG"); 
         	</programlisting>
         </example>
+        <para>The SET statement may also be used to control authorization.  
+        A SET SESSION AUTHORIZATION statement will perform a <xref linkend="reauthentication"/> given the credentials currently set on the connection.
+        The connection credentials may be changed by issuing a SET PASSWORD statement.  A SET PASSWORD statement does not perform a reauthentication.</para>
+        <example>
+        	<title>Changing Session Authorization</title>
+        	<programlisting>Statement s = connection.createStatement();
+s.execute("SET PASSWORD 'someval'");
+s.execute("SET SESSION AUTHORIZATION 'newuser'");
+        	</programlisting>
+        </example>
        </section>
 
        <section id="show_statement">

Modified: branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml
===================================================================
--- branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/odbc.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,6 +23,11 @@
      <para>Before an application can use ODBC, you must first install the ODBC driver on same machine that 
      the application is running on and then create Data Source Name (DSN) that represents a connection profile for your Teiid VDB.
      </para>
+     
+     <warning><para>Teiid currently only supports plain text passward authentication for ODBC.  
+     If the client/server are not configured to use SSL, the password will be sent in plain text over the network.  
+     If you need secure passwords in transit and are not using SSL, then consider installing a security domain 
+     that will accept safe password values from the client (for example encrypted or hashed).</para></warning>
 
     <section id="install">
         <title>Installing the ODBC Driver Client</title>
@@ -145,7 +150,6 @@
                     listenes for ODBC requests on port 35432</para>
                     <para>In the <emphasis>User Name</emphasis> and <emphasis>Password</emphasis> edit boxes, supply the user name and password
                     for the Teiid runtime access.</para>
-                    <para>Leave <emphasis>SSL Mode</emphasis> to disabled. SSL connections are currently not supported.</para>
                     <para>Provide any description about the data source in the <emphasis>Description</emphasis> field.</para>
                 </listitem>
                 

Modified: branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml
===================================================================
--- branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/client-developers-guide/src/main/docbook/en-US/content/ssl.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -13,13 +13,13 @@
     <section id="default_security">
         <title>Default Security</title>
         
-        <para>If you are using a socket connection, then you may need to secure the channel more completely.</para>
-    
-        <para>By default all sensitive (non-data) messages between client and server 
+        <para>By default all JDBC/Admin sensitive (non-data) messages between client and server 
         are encrypted using a <ulink url="http://en.wikipedia.org/wiki/Diffie-Hellman_key_exchange">Diffy-Hellman</ulink> 
         key that is negotiated per connection. This 
         encryption is controlled by <code>clientEncryptionEnabled</code> property in <code>JdbcSslConfiguration</code> and 
         <code>AdminSslConfiguration</code> sections in the &jboss-beans; file.</para>
+        
+        <para>If you are using a socket connection, then you may need to secure the channel more completely - especially if using ODBC, which currently only supports plain text authentication.</para>
     </section>
     
     <section id="ssl_modes">

Modified: branches/as7/documentation/developer-guide/pom.xml
===================================================================
--- branches/as7/documentation/developer-guide/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/developer-guide/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <groupId>org.jboss.teiid</groupId>
     <artifactId>documentation</artifactId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>developer-guide</artifactId>

Modified: branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml
===================================================================
--- branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/logging.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,19 +33,67 @@
             <title>Command Logging API</title>
             <para>
                 If you want to build a custom appender for command logging that will have access to 
-                log4j "LoggingEvents" to the "COMMAND_LOG" context, it will have a message that is an instance of
-                <code>org.teiid.logging.CommandLogMessage</code> defined in the <code>teiid-api-&versionNumber;.jar</code> 
-                use these class in your development. The CommmdLogMessage include information about vdb, session, command-sql etc.
+                log4j "LoggingEvents" to the "COMMAND_LOG" context, the appender will receive a message that is an instance of
+                <code>org.teiid.logging.CommandLogMessage</code>.  The relevant Teiid classes are defined in the <code>teiid-api-&versionNumber;.jar</code>. 
+                The CommmdLogMessage includes information about vdb, session, command sql, etc.  CommandLogMessages are logged at the DEBUG level.
             </para>
+            <example>
+				<title>Sample CommandLogMessage Usage</title>
+				<programlisting language="Java" role="JAVA"><![CDATA[package org.something;
+import org.apache.log4j.AppenderSkeleton;
+import org.apache.log4j.spi.LoggingEvent;
+import org.teiid.logging.*;
+
+public class CustomAppender extends AppenderSkeleton 
+{
+  
+  protected void append(LoggingEvent event) {
+    if (event.getMessage() instanceof CommandLogMessage) {
+      CommandLogMessage clMessage = (CommandLogMessage)event.getMessage();
+      String sql = clMessage.getSql();
+      ...
+      //log to a database, trigger an email, etc.
+    }
+    ...
+  }
+  
+  ...
+  
+}]]></programlisting>
+			</example>
         </section>
         
         <section id="audit_logging">
             <title>Audit Logging API</title>
             <para>If you want to build a custom appender for command logging that will have access to 
-                log4j "LoggingEvents" to the "AUDIT_LOG" context, it will have a message that is an instance of
-                <code>org.teiid.logging.AuditMessage</code> defined in the <code>teiid-api-&versionNumber;.jar</code> 
-                use this class in your development. AuditMessage include  information about user, the action, and the
-                target(s) of the action.</para>                            
+                log4j "LoggingEvents" to the "org.teiid.AUDIT_LOG" context, the appender will receive a message that is an instance of
+                <code>org.teiid.logging.AuditMessage</code>.  The relevant Teiid classes are defined in the <code>teiid-api-&versionNumber;.jar</code>. The <code>AuditMessage</code> includes information about user, the action, and the
+                target(s) of the action.  AuditMessages are logged at the DEBUG level.
+            </para>                            
+            <example>
+				<title>Sample AuditMessage Usage</title>
+				<programlisting language="Java" role="JAVA"><![CDATA[package org.something;
+import org.apache.log4j.AppenderSkeleton;
+import org.apache.log4j.spi.LoggingEvent;
+import org.teiid.logging.*;
+
+public class CustomAppender extends AppenderSkeleton 
+{
+  
+  protected void append(LoggingEvent event) {
+    if (event.getMessage() instanceof AuditMessage) {
+      AuditMessage auditMessage = (AuditMessage)event.getMessage();
+      String activity = auditMessage.getActivity();
+      ...
+      //log to a database, trigger an email, etc.
+    }
+    ...
+  }
+  
+  ...
+  
+}]]></programlisting>
+			</example>
         </section>
 	</section>
 </chapter>
\ No newline at end of file

Modified: branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/security.xml
===================================================================
--- branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/security.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/security.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,6 +1,11 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
-<chapter id="custom_login_modules">
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+<!ENTITY % CustomDTD SYSTEM "../../../../../../docbook/custom.dtd">
+%CustomDTD;
+]>
+<chapter>
+<title>Custom Security</title>
+<section id="custom_login_modules">
     <title>Login Modules</title>
     <para>The Teiid system provides a range of built-in and extensible security features to enable the
         secure access of data.  For details about how to configure the available security features check out
@@ -92,4 +97,27 @@
             <para>If you are extending one of the built-in LoginModules, refer to  
             <ulink url="http://community.jboss.org/docs/DOC-9466"/>.</para>
 		</section>
+</section>
+<section>
+	<title>Custom Authorization</title>
+	<para>In situations where Teiid's built-in role mechanism is not sufficient, a custom 
+	<code>org.teiid.PolicyDecider</code> can be installed via the &jboss-beans; configuration file under the "AuthorizationValidator" bean.
+	<example>
+		<title>Example Configuration Snippet</title>
+		<programlisting role="XML" language="XML"><![CDATA[
+	<bean name="AuthorizationValidator" class="org.teiid.dqp.internal.process.DefaultAuthorizationValidator">
+        <property name="enabled">true</property>
+        <property name="policyDecider"><inject bean="PolicyDecider"/></property>
+    </bean>
+   
+    <bean name="PolicyDecider" class="com.company.CustomPolicyDecider">
+        <property name="someProperty">some value</property>
+    </bean>]]>
+		</programlisting>
+	</example>  
+	Your custom <code>PolicyDecider</code> should be installed in a jar that is made available to the same classloader as Teiid, typically the profile lib directory.  
+	A <code>PolicyDecider</code> may be consulted many times for a single user command, but it is only called to make decisions based upon resources that 
+	appear in user queries.  Any further access of resources through views or stored procedures, just as with data roles, is not checked against a <code>PolicyDecider.</code>
+	</para>
+</section>
 </chapter>
\ No newline at end of file

Modified: branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/translator-api.xml
===================================================================
--- branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/translator-api.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/translator-api.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -380,12 +380,18 @@
 	</listitem>
 	<listitem>
 		<para>
-			<code>Aggregate</code>
-			– represents an aggregate function which holds a single expression
+			<code>AggregateFunction</code>
+			– represents an aggregate function which can hold a single expression
 		</para>
 	</listitem>
 	<listitem>
 		<para>
+			<code>WindowFunction</code>
+			– represents an window function which holds an AggregateFunction (which is also used to represent analytical functions) and a WindowSpecification
+		</para>
+	</listitem>
+	<listitem>
+		<para>
 			<code>ScalarSubquery</code>
 			– represents a subquery that returns a single value
 		</para>
@@ -417,7 +423,7 @@
         <listitem><para><code>SubqueryIn</code> – represents an IN criteria that uses a subquery to produce the value set</para></listitem>
         <listitem><para><code>IsNull</code> – represents an IS NULL criteria</para></listitem>        
         <listitem><para><code>Exists</code> – represents an EXISTS criteria that determines whether a subquery will return any values</para></listitem>
-        <listitem><para><code>Like</code> – represents a LIKE criteria that compares string values</para></listitem>
+        <listitem><para><code>Like</code> – represents a LIKE/SIMILAR TO/LIKE_REGEX criteria that compares string values</para></listitem>
       </itemizedlist>                  
     </section>
     
@@ -873,6 +879,28 @@
               </row>
               <row>
                 <entry>
+                  <para>SimilarTo</para>
+                </entry>
+                <entry>
+                  <para/>
+                </entry>
+                <entry>
+                  <para>Translator can support SIMILAR TO criteria.</para>
+                </entry>
+              </row>
+              <row>
+                <entry>
+                  <para>LikeRegexCriteria</para>
+                </entry>
+                <entry>
+                  <para/>
+                </entry>
+                <entry>
+                  <para>Translator can support LIKE_REGEX criteria.</para>
+                </entry>
+              </row>
+              <row>
+                <entry>
                   <para>InCriteria</para>
                 </entry>
                 <entry>
@@ -1229,7 +1257,7 @@
                   <para>GroupBy</para>
                 </entry>
                 <entry>
-                  <para>Not currently used - non-element expressions in the group by create an inline view.</para>
+                  <para>Translator can support non-column reference grouping expressions.</para>
                 </entry>
               </row>
               <row>
@@ -1287,6 +1315,39 @@
                   <para>Translator supports the WITH clause.</para>
                 </entry>
               </row>
+              <row>
+                <entry>
+                  <para>ElementaryOlapOperations</para>
+                </entry>
+                <entry>
+                  <para/>
+                </entry>
+                <entry>
+                  <para>Translator supports window functions and analytic functions RANK, DENSE_RANK, and ROW_NUMBER.</para>
+                </entry>
+              </row>
+              <row>
+                <entry>
+                  <para>WindowOrderByWithAggregates</para>
+                </entry>
+                <entry>
+                  <para/>
+                </entry>
+                <entry>
+                  <para>Translator supports windowed aggregates with a window order by clause.</para>
+                </entry>
+              </row>
+              <row>
+                <entry>
+                  <para>AdvancedOlapOperations</para>
+                </entry>
+                <entry>
+                  <para/>
+                </entry>
+                <entry>
+                  <para>Translator supports aggregate conditions.</para>
+                </entry>
+              </row>
             </tbody>
           </tgroup>
         </table>

Modified: branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml
===================================================================
--- branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/developer-guide/src/main/docbook/en-US/content/udf.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -161,7 +161,7 @@
 				<para>Code Requirements</para>
 				<listitem>
 					<para>The java class containing the function method must be defined
-						public.
+						public.  <note><para>As many UDF methods as you want can be declared on the same class.</para></note>
             </para>
 				</listitem>
 				<listitem>
@@ -184,7 +184,7 @@
 			</itemizedlist>
 			<para>You may optionally add an additional <code>org.teiid.CommandContext</code> argument as the first parameter.  
 			The <code>CommandContext</code> interface provides access to information about the current command, such as the executing user, Subject, the vdb, the session id, etc.  
-			This <code>CommandContext</code> parameter does not need to be delared in the function metadata.</para>
+			This <code>CommandContext</code> parameter should not be delared in the function metadata.</para>
 			<example>
 				<title>Sample code</title>
 				<programlisting language="Java" role="JAVA"><![CDATA[package org.something;
@@ -207,6 +207,23 @@
    }
 }]]></programlisting>
 			</example>
+			<example>
+				<title>Sample CommandContext Usage</title>
+				<programlisting language="Java" role="JAVA"><![CDATA[package org.something;
+
+public class SessionInfo 
+{
+   /**
+   * @param context 
+   * @return the created Timestamp 
+   */
+   public static Timestamp sessionCreated(CommandContext context)
+   {
+      return new Timestamp(context.getSession().getCreatedTime());
+   }
+}]]></programlisting>
+            <para>The corresponding UDF would be declared as Timestamp sessionCreated().</para>
+			</example>
 		</section>
 		<section>
 			<title>Post Code Activities</title>

Modified: branches/as7/documentation/docbook/custom.dtd
===================================================================
--- branches/as7/documentation/docbook/custom.dtd	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/docbook/custom.dtd	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,4 +1,4 @@
-<!ENTITY versionNumber "7.5">
+<!ENTITY versionNumber "7.6">
 <!ENTITY copyrightYear "2011">
 <!ENTITY copyrightHolder "Red Hat, Inc.">
 <!ENTITY url "http://www.jboss.org/teiid/">

Modified: branches/as7/documentation/pom.xml
===================================================================
--- branches/as7/documentation/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <artifactId>teiid-parent</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.jboss.teiid</groupId>

Modified: branches/as7/documentation/quick-start-example/pom.xml
===================================================================
--- branches/as7/documentation/quick-start-example/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/quick-start-example/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <groupId>org.jboss.teiid</groupId>
     <artifactId>documentation</artifactId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>quick-start-example</artifactId>

Modified: branches/as7/documentation/reference/pom.xml
===================================================================
--- branches/as7/documentation/reference/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <groupId>org.jboss.teiid</groupId>
     <artifactId>documentation</artifactId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>reference</artifactId>

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/Reference.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/Reference.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/Reference.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -48,6 +48,7 @@
   <toc />
   <xi:include href="content/preface.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
   <xi:include href="content/sql_support.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
+  <xi:include href="content/sql_clauses.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
   <xi:include href="content/ddl_support.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
   <xi:include href="content/xml_queries.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
   <xi:include href="content/datatypes.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />


Property changes on: branches/as7/documentation/reference/src/main/docbook/en-US/Reference.xml
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/architecture.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/architecture.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/architecture.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -131,7 +131,9 @@
         specified timeout period, a ‘cancel’ command is issued to the
         server for the request and no results are returned to the
         client. The cancel command is issued by the JDBC API without the
-        client’s intervention.</para>
+        client’s intervention.  See the Client Developers Guide for more on setting 
+        statement timeouts via the connection property "QUERYTIMEOUT" and see the Java JDBC API for setting 
+        the query timeout via <code>java.sql.Statement.setQueryTimeout</code> method.</para>
     </section>
   </section>
   <section>

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/dataroles.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/dataroles.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/dataroles.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -168,4 +168,8 @@
 		<para>The <code>hasRole</code> system function will return true if the current user has the given data role.  
 		The <code>hasRole</code> function can be used in procedure or view definitions to allow for a more dynamic application of security - which allows for things such as value masking or row level security.</para>
 	</section>
+	<section>
+		<title>Customizing</title>
+		<para>See the Developer's Guide Custom Security Chapter for details on using an alternative authorization scheme.</para>
+	</section>
 </chapter>
\ No newline at end of file

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/federated_planning.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -172,19 +172,30 @@
         by the query planner based on <xref linkend='access_patterns'/>, hints, and
         costing information.</para>
       <para>
-        Teiid supports the MAKEDEP and MAKENOTDEP hints. Theses are
-        can be placed in either the
+        Teiid supports hints to control dependent join behavior: 
+        <itemizedlist>
+          <listitem>
+            <para>MAKEIND - indicates that the clause should be the independent side of a depedent join.</para>
+          </listitem>
+          <listitem>
+            <para>MAKEDEP - indicates that the clause should be the dependent side of a join.</para>
+          </listitem>
+          <listitem>
+            <para>MAKENOTDEP - prevents the clause from being the dependent side of a join.</para>
+          </listitem>
+        </itemizedlist>
+        Theses can be placed in either the
         <link linkend="option_clause">OPTION clause</link>
         or directly in the
         <link linkend="from_clause">FROM clause</link>
-        . As long as all <xref linkend='access_patterns'/> can be met, the MAKEDEP and
-        MAKENOTDEP hints override any use of costing information.
+        . As long as all <xref linkend='access_patterns'/> can be met, the MAKEIND, MAKEDEP, and
+        MAKENOTDEP hints override any use of costing information.  MAKENOTDEP supersedes the other hints.
       </para>
       <tip>
-        <para> The MAKEDEP hint should only be used if the proper query
+        <para> The MAKEDEP/MAKEIND hint should only be used if the proper query
           plan is not chosen by default. You should ensure that your
           costing information is representative of the actual source
-          cardinality. An inappropriate MAKEDEP hint can force an
+          cardinality. An inappropriate MAKEDEP/MAKEIND hint can force an
           inefficient join structure and may result in many source
           queries.</para>
       </tip>
@@ -332,14 +343,19 @@
 				This will only happen if the affected table has a primary key.  If it does not, then an exception will be thrown.</para>
 		</listitem>
 		<listitem>
-			<para>WHERE or HAVING clause IN and EXISTs predicates can take the MJ (merge join) or NO_UNNEST (no unnest) hints appearing just before the subquery.  
-			The MJ hint directs the optimizer to use a traditional, semijoin, or antisemijoin merge join if possible.  
-			The NO_UNNEST hint, which supercedes the MJ hint, will direct the optimizer to leave the subquery in place.
+			<para>WHERE or HAVING clause IN and EXISTs predicates can take the MJ (merge join), DJ (dependent join), or NO_UNNEST (no unnest) hints appearing just before the subquery.  
+			The MJ hint directs the optimizer to use a traditional, semijoin, or antisemijoin merge join if possible.
+			The DJ is the same as the MJ hint, but additional directs the optimizer to use the subquery as the independent side of a dependent join if possible.
+			The NO_UNNEST hint, which supercedes the other hints, will direct the optimizer to leave the subquery in place.
 			<example>
 				<title>Merge Join Hint Usage</title>
 				<programlisting language="SQL">SELECT col1 from tbl where col2 IN /*+ MJ */ (SELECT col1 FROM tbl2)</programlisting>
 			</example>
 			<example>
+				<title>Dependent Join Hint Usage</title>
+				<programlisting language="SQL">SELECT col1 from tbl where col2 IN /*+ DJ */ (SELECT col1 FROM tbl2)</programlisting>
+			</example>
+			<example>
 				<title>No Unnest Hint Usage</title>
 				<programlisting language="SQL">SELECT col1 from tbl where col2 IN /*+ NO_UNNEST */ (SELECT col1 FROM tbl2)</programlisting>
 			</example>
@@ -361,6 +377,41 @@
 		</listitem>
 	</itemizedlist>
    </section>
+   <section id="xquery_optimization">
+     <title>XQuery Optimization</title>
+     <para>A technique known as document projection is used to reduce the memory footprint of the context item document.  
+             Document projection loads only the parts of the document needed by the relevant XQuery and path expressions. 
+             Since document projection analysis uses all relevant path expressions, even 1 expression that could potentially use many nodes, e.g. //x rather than /a/b/x will cause a larger memory footprint.
+             With the relevant content removed the entire document will still be loaded into memory for processing.
+             Document projection will only be used when there is a context item (unnamed PASSING clause item) passed to XMLTABLE/XMLQUERY.  A named variable will not have document projection performed.
+             In some cases the expressions used may be too complex for the optimizer to use document projection.  You should check the SHOWPLAN DEBUG full plan output to see if the appropriate optimization has been performed.</para>
+     <para>With additional restrictions, simple context path expressions allow the processor to evaluate document subtrees independently - without loading the full document in memory.  
+     A simple context path expression can be of the form "[/][ns:]root/[ns1:]elem/...", where a namespace prefix or element name can also be the * wild card.  As with normal XQuery processing if namespace prefixes are used in the XQuery expression, they should be declared using the XMLNAMESPACES clause.</para>
+     <example>
+        <title>Streaming Eligible XMLQUERY</title>
+        <programlisting>XMLQUERY('/*:root/*:child' PASSING doc)</programlisting>
+        <para>Rather than loading the entire doc in-memory as a DOM tree, each child element will be independently added to the result.</para>
+     </example>
+     <example>
+        <title>Streaming Ineligible XMLQUERY</title>
+        <programlisting>XMLQUERY('//child' PASSING doc)</programlisting>
+        <para>The use of the descendent axis prevents the streaming optimization, but document projection can still be performed.</para>
+     </example>
+     <para>When using XMLTABLE, the COLUMN PATH expressions have additional restrictions.  
+     They are allowed to reference any part of the element subtree formed by the context expression and they may use any attribute value from their direct parentage. 
+     Any path expression where it is possible to reference a non-direct ancestor or sibling of the current context item prevent streaming from being used.
+     </para>
+     <example>
+        <title>Streaming Eligible XMLTABLE</title>
+        <programlisting>XMLTABLE('/*:root/*:child' PASSING doc COLUMNS fullchild XML PATH '.', parent_attr string PATH '../@attr', child_val integer)</programlisting>
+        <para>The context XQuery and the column path expression allow the streaming optimization, rather than loading the entire doc in-memory as a DOM tree, each child element will be independently added to the result.</para>
+     </example>
+     <example>
+        <title>Streaming Ineligible XMLTABLE</title>
+        <programlisting>XMLTABLE('/*:root/*:child' PASSING doc COLUMNS sibling_attr string PATH '../other_child/@attr')</programlisting>
+        <para>The reference of an element outside of the child subtree in the sibling_attr path prevents the streaming optimization from being used, but document projection can still be performed.</para>
+     </example>
+   </section>
    <section>
     <title>Federated Failure Modes</title>
     <section>

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/grammar.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/grammar.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/grammar.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,7 +1,8 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE appendix PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
 <appendix id="grammar">
-  <title>BNF for SQL Grammar</title><section>
+  <title>BNF for SQL Grammar</title>
+<section>
 <title>TOKENS</title>
 <informaltable frame="none">
 <tgroup cols="1">
@@ -168,7 +169,9 @@
 | &lt;LANGUAGE: "language"&gt;
 | &lt;LARGE: "large"&gt;
 | &lt;LEADING: "leading"&gt;
+| &lt;LEAVE: "leave"&gt;
 | &lt;LIKE: "like"&gt;
+| &lt;LIKE_REGEX: "like_regex"&gt;
 | &lt;LIMIT: "limit"&gt;
 | &lt;LOCAL: "local"&gt;
 | &lt;LOOP: "loop"&gt;
@@ -189,6 +192,7 @@
 | &lt;NOT: "not"&gt;
 | &lt;NULL: "null"&gt;
 | &lt;OF: "of"&gt;
+| &lt;OFFSET: "offset"&gt;
 | &lt;OLD: "old"&gt;
 | &lt;ON: "on"&gt;
 | &lt;ONLY: "only"&gt;
@@ -381,6 +385,7 @@
 | &lt;QMARK: "?"&gt;
 | &lt;DOLLAR: "$"&gt;
 | &lt;SEMICOLON: ";"&gt;
+| &lt;COLON: ":"&gt;
 | &lt;CONCAT_OP: "||"&gt;
 }
 
@@ -423,11 +428,11 @@
 <row>
 <entry align="right" valign="top"><para><anchor id="prod12" xreflabel="alter"/>alter</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;ALTER&gt; ( ( <link linkend="prod11">nonReserved</link> <link linkend="prod2">id</link> &lt;AS&gt; <link linkend="prod13">queryExpression</link> ) | ( &lt;PROCEDURE&gt; <link linkend="prod2">id</link> &lt;AS&gt; <link linkend="prod14">block</link> ) | ( &lt;TRIGGER&gt; &lt;ON&gt; <link linkend="prod2">id</link> <link linkend="prod11">nonReserved</link> &lt;OF&gt; ( &lt;INSERT&gt; | &lt;UPDATE&gt; | &lt;DELETE&gt; ) ( ( &lt;AS&gt; <link linkend="prod9">forEachRowTriggerAction</link> ) | <link linkend="prod11">nonReserved</link> ) ) )</para></entry></row>
+&lt;ALTER&gt; ( ( <link linkend="prod11">nonReserved</link> <link linkend="prod2">id</link> &lt;AS&gt; <link linkend="prod13">queryExpression</link> ) | ( &lt;PROCEDURE&gt; <link linkend="prod2">id</link> &lt;AS&gt; <link linkend="prod14">statement</link> ) | ( &lt;TRIGGER&gt; &lt;ON&gt; <link linkend="prod2">id</link> <link linkend="prod11">nonReserved</link> &lt;OF&gt; ( &lt;INSERT&gt; | &lt;UPDATE&gt; | &lt;DELETE&gt; ) ( ( &lt;AS&gt; <link linkend="prod9">forEachRowTriggerAction</link> ) | <link linkend="prod11">nonReserved</link> ) ) )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod9" xreflabel="forEachRowTriggerAction"/>forEachRowTriggerAction</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;FOR&gt; &lt;EACH&gt; &lt;ROW&gt; <link linkend="prod14">block</link></para></entry></row>
+&lt;FOR&gt; &lt;EACH&gt; &lt;ROW&gt; ( ( &lt;BEGIN&gt; ( &lt;ATOMIC&gt; )? ( <link linkend="prod14">statement</link> )* &lt;END&gt; ) | <link linkend="prod14">statement</link> )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod5" xreflabel="userCommand"/>userCommand</para></entry>
 <entry align="left" valign="top"><para>::= 
@@ -449,183 +454,179 @@
 <entry align="left" valign="top"><para>::= 
 &lt;ERROR&gt; <link linkend="prod24">expression</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod25" xreflabel="statement"/>statement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod14" xreflabel="statement"/>statement</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod26">ifStatement</link> | <link linkend="prod27">loopStatement</link> | <link linkend="prod28">whileStatement</link> | <link linkend="prod29">delimitedStatement</link> )</para></entry></row>
+( ( ( <link linkend="prod2">id</link> &lt;COLON&gt; )? ( <link linkend="prod25">loopStatement</link> | <link linkend="prod26">whileStatement</link> | <link linkend="prod27">compoundStatement</link> ) ) | ( <link linkend="prod28">ifStatement</link> | <link linkend="prod29">delimitedStatement</link> ) )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod29" xreflabel="delimitedStatement"/>delimitedStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod30">assignStatement</link> | <link linkend="prod31">sqlStatement</link> | <link linkend="prod23">errorStatement</link> | <link linkend="prod32">declareStatement</link> | <link linkend="prod33">continueStatement</link> | <link linkend="prod34">breakStatement</link> ) &lt;SEMICOLON&gt;</para></entry></row>
+( <link linkend="prod30">assignStatement</link> | <link linkend="prod31">sqlStatement</link> | <link linkend="prod23">errorStatement</link> | <link linkend="prod32">declareStatement</link> | <link linkend="prod33">branchingStatement</link> ) &lt;SEMICOLON&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod14" xreflabel="block"/>block</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod27" xreflabel="compoundStatement"/>compoundStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod25">statement</link> | ( &lt;BEGIN&gt; ( <link linkend="prod25">statement</link> )* &lt;END&gt; ) )</para></entry></row>
+&lt;BEGIN&gt; ( ( &lt;NOT&gt; )? &lt;ATOMIC&gt; )? ( <link linkend="prod14">statement</link> )* &lt;END&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod34" xreflabel="breakStatement"/>breakStatement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod33" xreflabel="branchingStatement"/>branchingStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;BREAK&gt;</para></entry></row>
+( ( ( &lt;BREAK&gt; | &lt;CONTINUE&gt; ) ( <link linkend="prod2">id</link> )? ) | ( &lt;LEAVE&gt; <link linkend="prod2">id</link> ) )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod33" xreflabel="continueStatement"/>continueStatement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod26" xreflabel="whileStatement"/>whileStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;CONTINUE&gt;</para></entry></row>
+&lt;WHILE&gt; &lt;LPAREN&gt; <link linkend="prod34">criteria</link> &lt;RPAREN&gt; <link linkend="prod14">statement</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod28" xreflabel="whileStatement"/>whileStatement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod25" xreflabel="loopStatement"/>loopStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;WHILE&gt; &lt;LPAREN&gt; <link linkend="prod35">criteria</link> &lt;RPAREN&gt; <link linkend="prod14">block</link></para></entry></row>
+&lt;LOOP&gt; &lt;ON&gt; &lt;LPAREN&gt; <link linkend="prod13">queryExpression</link> &lt;RPAREN&gt; &lt;AS&gt; <link linkend="prod2">id</link> <link linkend="prod14">statement</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod27" xreflabel="loopStatement"/>loopStatement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod28" xreflabel="ifStatement"/>ifStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;LOOP&gt; &lt;ON&gt; &lt;LPAREN&gt; <link linkend="prod13">queryExpression</link> &lt;RPAREN&gt; &lt;AS&gt; <link linkend="prod2">id</link> <link linkend="prod14">block</link></para></entry></row>
+&lt;IF&gt; &lt;LPAREN&gt; <link linkend="prod34">criteria</link> &lt;RPAREN&gt; <link linkend="prod14">statement</link> ( &lt;ELSE&gt; <link linkend="prod14">statement</link> )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod26" xreflabel="ifStatement"/>ifStatement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod35" xreflabel="criteriaSelector"/>criteriaSelector</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;IF&gt; &lt;LPAREN&gt; <link linkend="prod35">criteria</link> &lt;RPAREN&gt; <link linkend="prod14">block</link> ( &lt;ELSE&gt; <link linkend="prod14">block</link> )?</para></entry></row>
-<row>
-<entry align="right" valign="top"><para><anchor id="prod36" xreflabel="criteriaSelector"/>criteriaSelector</para></entry>
-<entry align="left" valign="top"><para>::= 
 ( ( &lt;EQ&gt; | &lt;NE&gt; | &lt;NE2&gt; | &lt;LE&gt; | &lt;GE&gt; | &lt;LT&gt; | &lt;GT&gt; | &lt;IN&gt; | &lt;LIKE&gt; | ( &lt;IS&gt; &lt;NULL&gt; ) | &lt;BETWEEN&gt; ) )? &lt;CRITERIA&gt; ( &lt;ON&gt; &lt;LPAREN&gt; <link linkend="prod2">id</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> )* &lt;RPAREN&gt; )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod37" xreflabel="hasCriteria"/>hasCriteria</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod36" xreflabel="hasCriteria"/>hasCriteria</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;HAS&gt; <link linkend="prod36">criteriaSelector</link></para></entry></row>
+&lt;HAS&gt; <link linkend="prod35">criteriaSelector</link></para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod32" xreflabel="declareStatement"/>declareStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;DECLARE&gt; <link linkend="prod38">dataType</link> <link linkend="prod2">id</link> ( ( <link linkend="prod11">nonReserved</link> | &lt;EQ&gt; ) <link linkend="prod39">assignStatementOperand</link> )?</para></entry></row>
+&lt;DECLARE&gt; <link linkend="prod37">dataType</link> <link linkend="prod2">id</link> ( ( <link linkend="prod11">nonReserved</link> | &lt;EQ&gt; ) <link linkend="prod38">assignStatementOperand</link> )?</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod30" xreflabel="assignStatement"/>assignStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod2">id</link> ( <link linkend="prod11">nonReserved</link> | &lt;EQ&gt; ) <link linkend="prod39">assignStatementOperand</link></para></entry></row>
+<link linkend="prod2">id</link> ( <link linkend="prod11">nonReserved</link> | &lt;EQ&gt; ) <link linkend="prod38">assignStatementOperand</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod39" xreflabel="assignStatementOperand"/>assignStatementOperand</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod38" xreflabel="assignStatementOperand"/>assignStatementOperand</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( ( <link linkend="prod16">insert</link> ) | <link linkend="prod17">update</link> | <link linkend="prod18">delete</link> | ( <link linkend="prod24">expression</link> ) | <link linkend="prod13">queryExpression</link> )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod31" xreflabel="sqlStatement"/>sqlStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-( ( <link linkend="prod5">userCommand</link> ) | <link linkend="prod40">dynamicCommand</link> | ( <link linkend="prod2">id</link> ( <link linkend="prod11">nonReserved</link> | &lt;EQ&gt; ) <link linkend="prod15">storedProcedure</link> ) )</para></entry></row>
+( ( <link linkend="prod5">userCommand</link> ) | <link linkend="prod39">dynamicCommand</link> | ( <link linkend="prod2">id</link> ( <link linkend="prod11">nonReserved</link> | &lt;EQ&gt; ) <link linkend="prod15">storedProcedure</link> ) )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod41" xreflabel="translateCriteria"/>translateCriteria</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod40" xreflabel="translateCriteria"/>translateCriteria</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;TRANSLATE&gt; <link linkend="prod36">criteriaSelector</link> ( &lt;WITH&gt; &lt;LPAREN&gt; <link linkend="prod2">id</link> &lt;EQ&gt; <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> &lt;EQ&gt; <link linkend="prod24">expression</link> )* &lt;RPAREN&gt; )?</para></entry></row>
+&lt;TRANSLATE&gt; <link linkend="prod35">criteriaSelector</link> ( &lt;WITH&gt; &lt;LPAREN&gt; <link linkend="prod2">id</link> &lt;EQ&gt; <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> &lt;EQ&gt; <link linkend="prod24">expression</link> )* &lt;RPAREN&gt; )?</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod4" xreflabel="createUpdateProcedure"/>createUpdateProcedure</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;CREATE&gt; ( &lt;VIRTUAL&gt; )? ( &lt;UPDATE&gt; )? &lt;PROCEDURE&gt; <link linkend="prod14">block</link></para></entry></row>
+&lt;CREATE&gt; ( &lt;VIRTUAL&gt; )? ( &lt;UPDATE&gt; )? &lt;PROCEDURE&gt; <link linkend="prod14">statement</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod40" xreflabel="dynamicCommand"/>dynamicCommand</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod39" xreflabel="dynamicCommand"/>dynamicCommand</para></entry>
 <entry align="left" valign="top"><para>::= 
-( &lt;EXECUTE&gt; | &lt;EXEC&gt; ) ( ( &lt;STRING&gt; | &lt;IMMEDIATE&gt; ) )? <link linkend="prod24">expression</link> ( &lt;AS&gt; <link linkend="prod42">createElementsWithTypes</link> ( &lt;INTO&gt; <link linkend="prod2">id</link> )? )? ( &lt;USING&gt; <link linkend="prod43">setClauseList</link> )? ( &lt;UPDATE&gt; ( ( &lt;INTEGERVAL&gt; ) | ( &lt;STAR&gt; ) ) )?</para></entry></row>
+( &lt;EXECUTE&gt; | &lt;EXEC&gt; ) ( ( &lt;STRING&gt; | &lt;IMMEDIATE&gt; ) )? <link linkend="prod24">expression</link> ( &lt;AS&gt; <link linkend="prod41">createElementsWithTypes</link> ( &lt;INTO&gt; <link linkend="prod2">id</link> )? )? ( &lt;USING&gt; <link linkend="prod42">setClauseList</link> )? ( &lt;UPDATE&gt; ( ( &lt;INTEGERVAL&gt; ) | ( &lt;STAR&gt; ) ) )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod43" xreflabel="setClauseList"/>setClauseList</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod42" xreflabel="setClauseList"/>setClauseList</para></entry>
 <entry align="left" valign="top"><para>::= 
 <link linkend="prod2">id</link> &lt;EQ&gt; ( &lt;COMMA&gt; <link linkend="prod2">id</link> &lt;EQ&gt; )*</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod42" xreflabel="createElementsWithTypes"/>createElementsWithTypes</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod41" xreflabel="createElementsWithTypes"/>createElementsWithTypes</para></entry>
 <entry align="left" valign="top"><para>::= 
 <link linkend="prod2">id</link> <link linkend="prod22">dataTypeString</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> <link linkend="prod22">dataTypeString</link> )*</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod6" xreflabel="callableStatement"/>callableStatement</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;LBRACE&gt; ( &lt;QMARK&gt; &lt;EQ&gt; )? &lt;CALL&gt; <link linkend="prod2">id</link> ( &lt;LPAREN&gt; ( <link linkend="prod44">executeUnnamedParams</link> ) &lt;RPAREN&gt; )? &lt;RBRACE&gt; ( <link linkend="prod45">option</link> )?</para></entry></row>
+&lt;LBRACE&gt; ( &lt;QMARK&gt; &lt;EQ&gt; )? &lt;CALL&gt; <link linkend="prod2">id</link> ( &lt;LPAREN&gt; ( <link linkend="prod43">executeUnnamedParams</link> ) &lt;RPAREN&gt; )? &lt;RBRACE&gt; ( <link linkend="prod44">option</link> )?</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod15" xreflabel="storedProcedure"/>storedProcedure</para></entry>
 <entry align="left" valign="top"><para>::= 
-( ( &lt;EXEC&gt; | &lt;EXECUTE&gt; | &lt;CALL&gt; ) <link linkend="prod2">id</link> &lt;LPAREN&gt; ( <link linkend="prod46">executeNamedParams</link> | <link linkend="prod44">executeUnnamedParams</link> ) &lt;RPAREN&gt; ) ( <link linkend="prod45">option</link> )?</para></entry></row>
+( ( &lt;EXEC&gt; | &lt;EXECUTE&gt; | &lt;CALL&gt; ) <link linkend="prod2">id</link> &lt;LPAREN&gt; ( <link linkend="prod45">executeNamedParams</link> | <link linkend="prod43">executeUnnamedParams</link> ) &lt;RPAREN&gt; ) ( <link linkend="prod44">option</link> )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod44" xreflabel="executeUnnamedParams"/>executeUnnamedParams</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod43" xreflabel="executeUnnamedParams"/>executeUnnamedParams</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )* )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod46" xreflabel="executeNamedParams"/>executeNamedParams</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod45" xreflabel="executeNamedParams"/>executeNamedParams</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( <link linkend="prod2">id</link> &lt;EQ&gt; ( &lt;GT&gt; )? <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> &lt;EQ&gt; ( &lt;GT&gt; )? <link linkend="prod24">expression</link> )* )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod16" xreflabel="insert"/>insert</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;INSERT&gt; &lt;INTO&gt; <link linkend="prod2">id</link> ( <link linkend="prod47">columnList</link> )? ( ( &lt;VALUES&gt; <link linkend="prod48">rowValues</link> ) | ( <link linkend="prod13">queryExpression</link> ) ) ( <link linkend="prod45">option</link> )?</para></entry></row>
+&lt;INSERT&gt; &lt;INTO&gt; <link linkend="prod2">id</link> ( <link linkend="prod46">columnList</link> )? ( ( &lt;VALUES&gt; &lt;LPAREN&gt; <link linkend="prod47">expressionList</link> &lt;RPAREN&gt; ) | ( <link linkend="prod13">queryExpression</link> ) ) ( <link linkend="prod44">option</link> )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod47" xreflabel="columnList"/>columnList</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod46" xreflabel="columnList"/>columnList</para></entry>
 <entry align="left" valign="top"><para>::= 
 &lt;LPAREN&gt; <link linkend="prod2">id</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> )* &lt;RPAREN&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod48" xreflabel="rowValues"/>rowValues</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod47" xreflabel="expressionList"/>expressionList</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;LPAREN&gt; <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )* &lt;RPAREN&gt;</para></entry></row>
+<link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )*</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod17" xreflabel="update"/>update</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;UPDATE&gt; <link linkend="prod2">id</link> &lt;SET&gt; <link linkend="prod43">setClauseList</link> ( <link linkend="prod49">where</link> )? ( <link linkend="prod45">option</link> )?</para></entry></row>
+&lt;UPDATE&gt; <link linkend="prod2">id</link> &lt;SET&gt; <link linkend="prod42">setClauseList</link> ( <link linkend="prod48">where</link> )? ( <link linkend="prod44">option</link> )?</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod18" xreflabel="delete"/>delete</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;DELETE&gt; &lt;FROM&gt; <link linkend="prod2">id</link> ( <link linkend="prod49">where</link> )? ( <link linkend="prod45">option</link> )?</para></entry></row>
+&lt;DELETE&gt; &lt;FROM&gt; <link linkend="prod2">id</link> ( <link linkend="prod48">where</link> )? ( <link linkend="prod44">option</link> )?</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod13" xreflabel="queryExpression"/>queryExpression</para></entry>
 <entry align="left" valign="top"><para>::= 
-( &lt;WITH&gt; <link linkend="prod50">withListElement</link> ( &lt;COMMA&gt; <link linkend="prod50">withListElement</link> )* )? <link linkend="prod51">queryExpressionBody</link></para></entry></row>
+( &lt;WITH&gt; <link linkend="prod49">withListElement</link> ( &lt;COMMA&gt; <link linkend="prod49">withListElement</link> )* )? <link linkend="prod50">queryExpressionBody</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod50" xreflabel="withListElement"/>withListElement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod49" xreflabel="withListElement"/>withListElement</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod2">id</link> ( <link linkend="prod47">columnList</link> )? &lt;AS&gt; &lt;LPAREN&gt; <link linkend="prod13">queryExpression</link> &lt;RPAREN&gt;</para></entry></row>
+<link linkend="prod2">id</link> ( <link linkend="prod46">columnList</link> )? &lt;AS&gt; &lt;LPAREN&gt; <link linkend="prod13">queryExpression</link> &lt;RPAREN&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod51" xreflabel="queryExpressionBody"/>queryExpressionBody</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod50" xreflabel="queryExpressionBody"/>queryExpressionBody</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod52">queryTerm</link> ( ( &lt;UNION&gt; | &lt;EXCEPT&gt; ) ( &lt;ALL&gt; | &lt;DISTINCT&gt; )? <link linkend="prod52">queryTerm</link> )* ( <link linkend="prod53">orderby</link> )? ( <link linkend="prod54">limit</link> )? ( <link linkend="prod45">option</link> )?</para></entry></row>
+<link linkend="prod51">queryTerm</link> ( ( &lt;UNION&gt; | &lt;EXCEPT&gt; ) ( &lt;ALL&gt; | &lt;DISTINCT&gt; )? <link linkend="prod51">queryTerm</link> )* ( <link linkend="prod52">orderby</link> )? ( <link linkend="prod53">limit</link> )? ( <link linkend="prod44">option</link> )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod52" xreflabel="queryTerm"/>queryTerm</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod51" xreflabel="queryTerm"/>queryTerm</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod55">queryPrimary</link> ( &lt;INTERSECT&gt; ( &lt;ALL&gt; | &lt;DISTINCT&gt; )? <link linkend="prod55">queryPrimary</link> )*</para></entry></row>
+<link linkend="prod54">queryPrimary</link> ( &lt;INTERSECT&gt; ( &lt;ALL&gt; | &lt;DISTINCT&gt; )? <link linkend="prod54">queryPrimary</link> )*</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod55" xreflabel="queryPrimary"/>queryPrimary</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod54" xreflabel="queryPrimary"/>queryPrimary</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod56">query</link> | ( &lt;TABLE&gt; <link linkend="prod2">id</link> ) | ( &lt;LPAREN&gt; <link linkend="prod51">queryExpressionBody</link> &lt;RPAREN&gt; ) )</para></entry></row>
+( <link linkend="prod55">query</link> | ( &lt;TABLE&gt; <link linkend="prod2">id</link> ) | ( &lt;LPAREN&gt; <link linkend="prod50">queryExpressionBody</link> &lt;RPAREN&gt; ) )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod56" xreflabel="query"/>query</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod55" xreflabel="query"/>query</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod57">select</link> ( <link linkend="prod58">into</link> )? ( <link linkend="prod59">from</link> ( <link linkend="prod49">where</link> )? ( <link linkend="prod60">groupBy</link> )? ( <link linkend="prod61">having</link> )? )?</para></entry></row>
+<link linkend="prod56">select</link> ( <link linkend="prod57">into</link> )? ( <link linkend="prod58">from</link> ( <link linkend="prod48">where</link> )? ( <link linkend="prod59">groupBy</link> )? ( <link linkend="prod60">having</link> )? )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod58" xreflabel="into"/>into</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod57" xreflabel="into"/>into</para></entry>
 <entry align="left" valign="top"><para>::= 
 &lt;INTO&gt; ( <link linkend="prod2">id</link> )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod57" xreflabel="select"/>select</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod56" xreflabel="select"/>select</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;SELECT&gt; ( &lt;ALL&gt; | ( &lt;DISTINCT&gt; ) )? ( &lt;STAR&gt; | ( <link linkend="prod62">selectSymbol</link> ( &lt;COMMA&gt; <link linkend="prod62">selectSymbol</link> )* ) )</para></entry></row>
+&lt;SELECT&gt; ( &lt;ALL&gt; | ( &lt;DISTINCT&gt; ) )? ( &lt;STAR&gt; | ( <link linkend="prod61">selectSymbol</link> ( &lt;COMMA&gt; <link linkend="prod61">selectSymbol</link> )* ) )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod62" xreflabel="selectSymbol"/>selectSymbol</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod61" xreflabel="selectSymbol"/>selectSymbol</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod63">selectExpression</link> | <link linkend="prod64">allInGroupSymbol</link> )</para></entry></row>
+( <link linkend="prod62">selectExpression</link> | <link linkend="prod63">allInGroupSymbol</link> )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod63" xreflabel="selectExpression"/>selectExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod62" xreflabel="selectExpression"/>selectExpression</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( <link linkend="prod24">expression</link> ( ( &lt;AS&gt; )? <link linkend="prod2">id</link> )? )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod65" xreflabel="derivedColumn"/>derivedColumn</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod64" xreflabel="derivedColumn"/>derivedColumn</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( <link linkend="prod24">expression</link> ( &lt;AS&gt; <link linkend="prod2">id</link> )? )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod64" xreflabel="allInGroupSymbol"/>allInGroupSymbol</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod63" xreflabel="allInGroupSymbol"/>allInGroupSymbol</para></entry>
 <entry align="left" valign="top"><para>::= 
 &lt;ALL_IN_GROUP&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod66" xreflabel="xmlAgg"/>xmlAgg</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod65" xreflabel="orderedAgg"/>orderedAgg</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;XMLAGG&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> ( <link linkend="prod53">orderby</link> )? &lt;RPAREN&gt;</para></entry></row>
+( &lt;XMLAGG&gt; | &lt;ARRAY_AGG&gt; ) &lt;LPAREN&gt; <link linkend="prod24">expression</link> ( <link linkend="prod52">orderby</link> )? &lt;RPAREN&gt; <link linkend="prod66">filterClause</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod67" xreflabel="arrayAgg"/>arrayAgg</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod67" xreflabel="textAgg"/>textAgg</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;ARRAY_AGG&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> ( <link linkend="prod53">orderby</link> )? &lt;RPAREN&gt;</para></entry></row>
+<link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; &lt;FOR&gt; <link linkend="prod64">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod64">derivedColumn</link> )* ( &lt;ID&gt; <link linkend="prod68">charVal</link> )? ( ( &lt;ID&gt; <link linkend="prod68">charVal</link> ) )? ( &lt;ID&gt; )? ( ( &lt;ID&gt; <link linkend="prod2">id</link> ) )? ( <link linkend="prod52">orderby</link> )? &lt;RPAREN&gt; <link linkend="prod66">filterClause</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod68" xreflabel="textAgg"/>textAgg</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod69" xreflabel="aggregateSymbol"/>aggregateSymbol</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; &lt;FOR&gt; <link linkend="prod65">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod65">derivedColumn</link> )* ( &lt;ID&gt; <link linkend="prod69">charVal</link> )? ( ( &lt;ID&gt; <link linkend="prod69">charVal</link> ) )? ( &lt;ID&gt; )? ( ( &lt;ID&gt; <link linkend="prod2">id</link> ) )? ( <link linkend="prod53">orderby</link> )? &lt;RPAREN&gt;</para></entry></row>
+( ( ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; &lt;STAR&gt; &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; &lt;RPAREN&gt; ) | ( ( <link linkend="prod11">nonReserved</link> | &lt;ANY&gt; | &lt;SOME&gt; ) &lt;LPAREN&gt; ( &lt;DISTINCT&gt; | &lt;ALL&gt; )? <link linkend="prod24">expression</link> &lt;RPAREN&gt; ) ) <link linkend="prod66">filterClause</link> )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod70" xreflabel="aggregateSymbol"/>aggregateSymbol</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod66" xreflabel="filterClause"/>filterClause</para></entry>
 <entry align="left" valign="top"><para>::= 
-( ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; &lt;STAR&gt; &lt;RPAREN&gt; ) | ( ( <link linkend="prod11">nonReserved</link> | &lt;ANY&gt; | &lt;SOME&gt; ) &lt;LPAREN&gt; ( &lt;DISTINCT&gt; | &lt;ALL&gt; )? <link linkend="prod24">expression</link> &lt;RPAREN&gt; ) )</para></entry></row>
+( &lt;FILTER&gt; &lt;LPAREN&gt; &lt;WHERE&gt; <link linkend="prod70">booleanPrimary</link> &lt;RPAREN&gt; )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod59" xreflabel="from"/>from</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod58" xreflabel="from"/>from</para></entry>
 <entry align="left" valign="top"><para>::= 
 &lt;FROM&gt; ( <link linkend="prod71">tableReference</link> ( &lt;COMMA&gt; <link linkend="prod71">tableReference</link> )* )</para></entry></row>
 <row>
@@ -643,7 +644,7 @@
 <row>
 <entry align="right" valign="top"><para><anchor id="prod75" xreflabel="qualifiedJoin"/>qualifiedJoin</para></entry>
 <entry align="left" valign="top"><para>::= 
-( ( ( &lt;RIGHT&gt; ( &lt;OUTER&gt; )? ) | ( &lt;LEFT&gt; ( &lt;OUTER&gt; )? ) | ( &lt;FULL&gt; ( &lt;OUTER&gt; )? ) | &lt;INNER&gt; )? &lt;JOIN&gt; <link linkend="prod71">tableReference</link> &lt;ON&gt; <link linkend="prod35">criteria</link> )</para></entry></row>
+( ( ( &lt;RIGHT&gt; ( &lt;OUTER&gt; )? ) | ( &lt;LEFT&gt; ( &lt;OUTER&gt; )? ) | ( &lt;FULL&gt; ( &lt;OUTER&gt; )? ) | &lt;INNER&gt; )? &lt;JOIN&gt; <link linkend="prod71">tableReference</link> &lt;ON&gt; <link linkend="prod34">criteria</link> )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod73" xreflabel="tablePrimary"/>tablePrimary</para></entry>
 <entry align="left" valign="top"><para>::= 
@@ -659,27 +660,27 @@
 <row>
 <entry align="right" valign="top"><para><anchor id="prod77" xreflabel="arrayTable"/>arrayTable</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;ID&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> <link linkend="prod11">nonReserved</link> <link linkend="prod42">createElementsWithTypes</link> &lt;RPAREN&gt; ( &lt;AS&gt; )? <link linkend="prod2">id</link></para></entry></row>
+&lt;ID&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> <link linkend="prod11">nonReserved</link> <link linkend="prod41">createElementsWithTypes</link> &lt;RPAREN&gt; ( &lt;AS&gt; )? <link linkend="prod2">id</link></para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod76" xreflabel="textTable"/>textTable</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;ID&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> <link linkend="prod11">nonReserved</link> <link linkend="prod82">textColumn</link> ( &lt;COMMA&gt; <link linkend="prod82">textColumn</link> )* ( &lt;ID&gt; <link linkend="prod69">charVal</link> )? ( ( &lt;ESCAPE&gt; <link linkend="prod69">charVal</link> ) | ( &lt;ID&gt; <link linkend="prod69">charVal</link> ) )? ( &lt;ID&gt; ( <link linkend="prod83">intVal</link> )? )? ( &lt;ID&gt; <link linkend="prod83">intVal</link> )? &lt;RPAREN&gt; ( &lt;AS&gt; )? <link linkend="prod2">id</link></para></entry></row>
+&lt;ID&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> <link linkend="prod11">nonReserved</link> <link linkend="prod82">textColumn</link> ( &lt;COMMA&gt; <link linkend="prod82">textColumn</link> )* ( &lt;NO&gt; &lt;ROW&gt; <link linkend="prod11">nonReserved</link> )? ( &lt;ID&gt; <link linkend="prod68">charVal</link> )? ( ( &lt;ESCAPE&gt; <link linkend="prod68">charVal</link> ) | ( &lt;ID&gt; <link linkend="prod68">charVal</link> ) )? ( &lt;ID&gt; ( <link linkend="prod83">intVal</link> )? )? ( &lt;ID&gt; <link linkend="prod83">intVal</link> )? &lt;RPAREN&gt; ( &lt;AS&gt; )? <link linkend="prod2">id</link></para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod82" xreflabel="textColumn"/>textColumn</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod2">id</link> <link linkend="prod38">dataType</link> ( &lt;ID&gt; <link linkend="prod83">intVal</link> )?</para></entry></row>
+<link linkend="prod2">id</link> <link linkend="prod37">dataType</link> ( &lt;ID&gt; <link linkend="prod83">intVal</link> ( &lt;NO&gt; <link linkend="prod11">nonReserved</link> )? )?</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod84" xreflabel="xmlQuery"/>xmlQuery</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;XMLQUERY&gt; &lt;LPAREN&gt; ( <link linkend="prod85">xmlNamespaces</link> &lt;COMMA&gt; )? <link linkend="prod1">stringVal</link> ( &lt;ID&gt; <link linkend="prod65">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod65">derivedColumn</link> )* )? ( ( &lt;NULL&gt; | <link linkend="prod11">nonReserved</link> ) &lt;ON&gt; <link linkend="prod11">nonReserved</link> )? &lt;RPAREN&gt;</para></entry></row>
+&lt;XMLQUERY&gt; &lt;LPAREN&gt; ( <link linkend="prod85">xmlNamespaces</link> &lt;COMMA&gt; )? <link linkend="prod1">stringVal</link> ( &lt;ID&gt; <link linkend="prod64">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod64">derivedColumn</link> )* )? ( ( &lt;NULL&gt; | <link linkend="prod11">nonReserved</link> ) &lt;ON&gt; <link linkend="prod11">nonReserved</link> )? &lt;RPAREN&gt;</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod78" xreflabel="xmlTable"/>xmlTable</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;XMLTABLE&gt; &lt;LPAREN&gt; ( <link linkend="prod85">xmlNamespaces</link> &lt;COMMA&gt; )? <link linkend="prod1">stringVal</link> ( &lt;ID&gt; <link linkend="prod65">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod65">derivedColumn</link> )* )? ( &lt;ID&gt; <link linkend="prod86">xmlColumn</link> ( &lt;COMMA&gt; <link linkend="prod86">xmlColumn</link> )* )? &lt;RPAREN&gt; ( &lt;AS&gt; )? <link linkend="prod2">id</link></para></entry></row>
+&lt;XMLTABLE&gt; &lt;LPAREN&gt; ( <link linkend="prod85">xmlNamespaces</link> &lt;COMMA&gt; )? <link linkend="prod1">stringVal</link> ( &lt;ID&gt; <link linkend="prod64">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod64">derivedColumn</link> )* )? ( &lt;ID&gt; <link linkend="prod86">xmlColumn</link> ( &lt;COMMA&gt; <link linkend="prod86">xmlColumn</link> )* )? &lt;RPAREN&gt; ( &lt;AS&gt; )? <link linkend="prod2">id</link></para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod86" xreflabel="xmlColumn"/>xmlColumn</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod2">id</link> ( ( &lt;FOR&gt; <link linkend="prod11">nonReserved</link> ) | ( <link linkend="prod38">dataType</link> ( &lt;DEFAULT_KEYWORD&gt; <link linkend="prod24">expression</link> )? ( <link linkend="prod11">nonReserved</link> <link linkend="prod1">stringVal</link> )? ) )</para></entry></row>
+<link linkend="prod2">id</link> ( ( &lt;FOR&gt; <link linkend="prod11">nonReserved</link> ) | ( <link linkend="prod37">dataType</link> ( &lt;DEFAULT_KEYWORD&gt; <link linkend="prod24">expression</link> )? ( <link linkend="prod11">nonReserved</link> <link linkend="prod1">stringVal</link> )? ) )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod83" xreflabel="intVal"/>intVal</para></entry>
 <entry align="left" valign="top"><para>::= 
@@ -693,11 +694,11 @@
 <entry align="left" valign="top"><para>::= 
 ( &lt;ID&gt; ( ( &lt;AS&gt; )? <link linkend="prod2">id</link> )? )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod49" xreflabel="where"/>where</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod48" xreflabel="where"/>where</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;WHERE&gt; <link linkend="prod35">criteria</link></para></entry></row>
+&lt;WHERE&gt; <link linkend="prod34">criteria</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod35" xreflabel="criteria"/>criteria</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod34" xreflabel="criteria"/>criteria</para></entry>
 <entry align="left" valign="top"><para>::= 
 <link linkend="prod87">compoundCritOr</link></para></entry></row>
 <row>
@@ -711,11 +712,11 @@
 <row>
 <entry align="right" valign="top"><para><anchor id="prod89" xreflabel="notCrit"/>notCrit</para></entry>
 <entry align="left" valign="top"><para>::= 
-( &lt;NOT&gt; )? <link linkend="prod90">booleanPrimary</link></para></entry></row>
+( &lt;NOT&gt; )? <link linkend="prod70">booleanPrimary</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod90" xreflabel="booleanPrimary"/>booleanPrimary</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod70" xreflabel="booleanPrimary"/>booleanPrimary</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod41">translateCriteria</link> | ( <link linkend="prod91">commonValueExpression</link> ( ( <link linkend="prod92">betweenCrit</link> | <link linkend="prod93">matchCrit</link> | <link linkend="prod94">setCrit</link> | <link linkend="prod95">isNullCrit</link> | <link linkend="prod96">subqueryCompareCriteria</link> | <link linkend="prod97">compareCrit</link> ) )? ) | <link linkend="prod98">existsCriteria</link> | <link linkend="prod37">hasCriteria</link> )</para></entry></row>
+( <link linkend="prod40">translateCriteria</link> | ( <link linkend="prod90">commonValueExpression</link> ( ( <link linkend="prod91">betweenCrit</link> | <link linkend="prod92">matchCrit</link> | <link linkend="prod93">regexMatchCrit</link> | <link linkend="prod94">setCrit</link> | <link linkend="prod95">isNullCrit</link> | <link linkend="prod96">subqueryCompareCriteria</link> | <link linkend="prod97">compareCrit</link> ) )? ) | <link linkend="prod98">existsCriteria</link> | <link linkend="prod36">hasCriteria</link> )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod99" xreflabel="operator"/>operator</para></entry>
 <entry align="left" valign="top"><para>::= 
@@ -723,7 +724,7 @@
 <row>
 <entry align="right" valign="top"><para><anchor id="prod97" xreflabel="compareCrit"/>compareCrit</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod99">operator</link> <link linkend="prod91">commonValueExpression</link></para></entry></row>
+<link linkend="prod99">operator</link> <link linkend="prod90">commonValueExpression</link></para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod100" xreflabel="subquery"/>subquery</para></entry>
 <entry align="left" valign="top"><para>::= 
@@ -737,17 +738,21 @@
 <entry align="left" valign="top"><para>::= 
 <link linkend="prod99">operator</link> ( &lt;ANY&gt; | &lt;SOME&gt; | &lt;ALL&gt; ) <link linkend="prod100">subquery</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod93" xreflabel="matchCrit"/>matchCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod92" xreflabel="matchCrit"/>matchCrit</para></entry>
 <entry align="left" valign="top"><para>::= 
-( &lt;NOT&gt; )? &lt;LIKE&gt; <link linkend="prod91">commonValueExpression</link> ( &lt;ESCAPE&gt; <link linkend="prod69">charVal</link> | ( &lt;LBRACE&gt; &lt;ESCAPE&gt; <link linkend="prod69">charVal</link> &lt;RBRACE&gt; ) )?</para></entry></row>
+( &lt;NOT&gt; )? ( &lt;LIKE&gt; | ( &lt;SIMILAR&gt; &lt;TO&gt; ) ) <link linkend="prod90">commonValueExpression</link> ( &lt;ESCAPE&gt; <link linkend="prod68">charVal</link> | ( &lt;LBRACE&gt; &lt;ESCAPE&gt; <link linkend="prod68">charVal</link> &lt;RBRACE&gt; ) )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod69" xreflabel="charVal"/>charVal</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod93" xreflabel="regexMatchCrit"/>regexMatchCrit</para></entry>
 <entry align="left" valign="top"><para>::= 
+( &lt;NOT&gt; )? &lt;LIKE_REGEX&gt; <link linkend="prod90">commonValueExpression</link></para></entry></row>
+<row>
+<entry align="right" valign="top"><para><anchor id="prod68" xreflabel="charVal"/>charVal</para></entry>
+<entry align="left" valign="top"><para>::= 
 <link linkend="prod1">stringVal</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod92" xreflabel="betweenCrit"/>betweenCrit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod91" xreflabel="betweenCrit"/>betweenCrit</para></entry>
 <entry align="left" valign="top"><para>::= 
-( &lt;NOT&gt; )? &lt;BETWEEN&gt; <link linkend="prod91">commonValueExpression</link> &lt;AND&gt; <link linkend="prod91">commonValueExpression</link></para></entry></row>
+( &lt;NOT&gt; )? &lt;BETWEEN&gt; <link linkend="prod90">commonValueExpression</link> &lt;AND&gt; <link linkend="prod90">commonValueExpression</link></para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod95" xreflabel="isNullCrit"/>isNullCrit</para></entry>
 <entry align="left" valign="top"><para>::= 
@@ -755,113 +760,121 @@
 <row>
 <entry align="right" valign="top"><para><anchor id="prod94" xreflabel="setCrit"/>setCrit</para></entry>
 <entry align="left" valign="top"><para>::= 
-( &lt;NOT&gt; )? &lt;IN&gt; ( ( <link linkend="prod101">subqueryAndHint</link> ) | ( &lt;LPAREN&gt; <link linkend="prod91">commonValueExpression</link> ( &lt;COMMA&gt; <link linkend="prod91">commonValueExpression</link> )* &lt;RPAREN&gt; ) )</para></entry></row>
+( &lt;NOT&gt; )? &lt;IN&gt; ( ( <link linkend="prod101">subqueryAndHint</link> ) | ( &lt;LPAREN&gt; <link linkend="prod90">commonValueExpression</link> ( &lt;COMMA&gt; <link linkend="prod90">commonValueExpression</link> )* &lt;RPAREN&gt; ) )</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod98" xreflabel="existsCriteria"/>existsCriteria</para></entry>
 <entry align="left" valign="top"><para>::= 
 &lt;EXISTS&gt; <link linkend="prod101">subqueryAndHint</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod60" xreflabel="groupBy"/>groupBy</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod59" xreflabel="groupBy"/>groupBy</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;GROUP&gt; &lt;BY&gt; ( <link linkend="prod102">groupByItem</link> ( &lt;COMMA&gt; <link linkend="prod102">groupByItem</link> )* )</para></entry></row>
+&lt;GROUP&gt; &lt;BY&gt; <link linkend="prod47">expressionList</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod102" xreflabel="groupByItem"/>groupByItem</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod60" xreflabel="having"/>having</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod24">expression</link></para></entry></row>
+&lt;HAVING&gt; <link linkend="prod34">criteria</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod61" xreflabel="having"/>having</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod52" xreflabel="orderby"/>orderby</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;HAVING&gt; <link linkend="prod35">criteria</link></para></entry></row>
+&lt;ORDER&gt; &lt;BY&gt; <link linkend="prod102">sortSpecification</link> ( &lt;COMMA&gt; <link linkend="prod102">sortSpecification</link> )*</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod53" xreflabel="orderby"/>orderby</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod102" xreflabel="sortSpecification"/>sortSpecification</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;ORDER&gt; &lt;BY&gt; <link linkend="prod103">sortSpecification</link> ( &lt;COMMA&gt; <link linkend="prod103">sortSpecification</link> )*</para></entry></row>
+<link linkend="prod103">sortKey</link> ( &lt;ASC&gt; | &lt;DESC&gt; )? ( <link linkend="prod11">nonReserved</link> <link linkend="prod11">nonReserved</link> )?</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod103" xreflabel="sortSpecification"/>sortSpecification</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod103" xreflabel="sortKey"/>sortKey</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod104">sortKey</link> ( &lt;ASC&gt; | &lt;DESC&gt; )? ( <link linkend="prod11">nonReserved</link> <link linkend="prod11">nonReserved</link> )?</para></entry></row>
+<link linkend="prod24">expression</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod104" xreflabel="sortKey"/>sortKey</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod104" xreflabel="intParam"/>intParam</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod24">expression</link></para></entry></row>
+( <link linkend="prod83">intVal</link> | &lt;QMARK&gt; )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod54" xreflabel="limit"/>limit</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod53" xreflabel="limit"/>limit</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;LIMIT&gt; ( &lt;INTEGERVAL&gt; | &lt;QMARK&gt; ) ( &lt;COMMA&gt; ( &lt;INTEGERVAL&gt; | &lt;QMARK&gt; ) )?</para></entry></row>
+( ( &lt;LIMIT&gt; <link linkend="prod104">intParam</link> ( &lt;COMMA&gt; <link linkend="prod104">intParam</link> )? ) | ( &lt;OFFSET&gt; <link linkend="prod104">intParam</link> ( &lt;ROW&gt; | &lt;ROWS&gt; ) ( <link linkend="prod105">fetchLimit</link> )? ) | ( <link linkend="prod105">fetchLimit</link> ) )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod45" xreflabel="option"/>option</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod105" xreflabel="fetchLimit"/>fetchLimit</para></entry>
 <entry align="left" valign="top"><para>::= 
+&lt;FETCH&gt; <link linkend="prod11">nonReserved</link> ( <link linkend="prod104">intParam</link> )? ( &lt;ROW&gt; | &lt;ROWS&gt; ) &lt;ONLY&gt;</para></entry></row>
+<row>
+<entry align="right" valign="top"><para><anchor id="prod44" xreflabel="option"/>option</para></entry>
+<entry align="left" valign="top"><para>::= 
 &lt;OPTION&gt; ( &lt;MAKEDEP&gt; <link linkend="prod2">id</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> )* | &lt;MAKENOTDEP&gt; <link linkend="prod2">id</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> )* | &lt;NOCACHE&gt; ( <link linkend="prod2">id</link> ( &lt;COMMA&gt; <link linkend="prod2">id</link> )* )? )*</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod24" xreflabel="expression"/>expression</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod35">criteria</link></para></entry></row>
+<link linkend="prod34">criteria</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod91" xreflabel="commonValueExpression"/>commonValueExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod90" xreflabel="commonValueExpression"/>commonValueExpression</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod105">plusExpression</link> ( &lt;CONCAT_OP&gt; <link linkend="prod105">plusExpression</link> )* )</para></entry></row>
+( <link linkend="prod106">plusExpression</link> ( &lt;CONCAT_OP&gt; <link linkend="prod106">plusExpression</link> )* )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod105" xreflabel="plusExpression"/>plusExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod106" xreflabel="plusExpression"/>plusExpression</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod106">timesExpression</link> ( <link linkend="prod107">plusOperator</link> <link linkend="prod106">timesExpression</link> )* )</para></entry></row>
+( <link linkend="prod107">timesExpression</link> ( <link linkend="prod108">plusOperator</link> <link linkend="prod107">timesExpression</link> )* )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod107" xreflabel="plusOperator"/>plusOperator</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod108" xreflabel="plusOperator"/>plusOperator</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( &lt;PLUS&gt; | &lt;MINUS&gt; )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod106" xreflabel="timesExpression"/>timesExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod107" xreflabel="timesExpression"/>timesExpression</para></entry>
 <entry align="left" valign="top"><para>::= 
-( <link linkend="prod108">valueExpressionPrimary</link> ( <link linkend="prod109">timesOperator</link> <link linkend="prod108">valueExpressionPrimary</link> )* )</para></entry></row>
+( <link linkend="prod109">valueExpressionPrimary</link> ( <link linkend="prod110">timesOperator</link> <link linkend="prod109">valueExpressionPrimary</link> )* )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod109" xreflabel="timesOperator"/>timesOperator</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod110" xreflabel="timesOperator"/>timesOperator</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( &lt;STAR&gt; | &lt;SLASH&gt; )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod108" xreflabel="valueExpressionPrimary"/>valueExpressionPrimary</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod109" xreflabel="valueExpressionPrimary"/>valueExpressionPrimary</para></entry>
 <entry align="left" valign="top"><para>::= 
-( &lt;QMARK&gt; | &lt;POS_REF&gt; | <link linkend="prod110">literal</link> | ( &lt;LBRACE&gt; <link linkend="prod11">nonReserved</link> <link linkend="prod111">function</link> &lt;RBRACE&gt; ) | ( <link linkend="prod68">textAgg</link> ) | ( <link linkend="prod70">aggregateSymbol</link> ) | ( <link linkend="prod70">aggregateSymbol</link> ) | ( <link linkend="prod70">aggregateSymbol</link> ) | ( <link linkend="prod66">xmlAgg</link> ) | ( <link linkend="prod67">arrayAgg</link> ) | ( <link linkend="prod111">function</link> ) | ( &lt;ID&gt; ( &lt;LSBRACE&gt; <link linkend="prod83">intVal</link> &lt;RSBRACE&gt; )? ) | <link linkend="prod100">subquery</link> | ( &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;RPAREN&gt; ( &lt;LSBRACE&gt; <link linkend="prod83">intVal</link> &lt;RSBRACE&gt; )? ) | <link linkend="prod112">searchedCaseExpression</link> | <link linkend="prod113">caseExpression</link> )</para></entry></row>
+( &lt;QMARK&gt; | &lt;POS_REF&gt; | <link linkend="prod111">literal</link> | ( &lt;LBRACE&gt; <link linkend="prod11">nonReserved</link> <link linkend="prod112">function</link> &lt;RBRACE&gt; ) | ( <link linkend="prod67">textAgg</link> ( <link linkend="prod113">windowSpecification</link> )? ) | ( <link linkend="prod69">aggregateSymbol</link> ( <link linkend="prod113">windowSpecification</link> )? ) | ( <link linkend="prod69">aggregateSymbol</link> ( <link linkend="prod113">windowSpecification</link> )? ) | <link linkend="prod65">orderedAgg</link> ( <link linkend="prod113">windowSpecification</link> )? | ( <link linkend="prod69">aggregateSymbol</link> <link linkend="prod113">windowSpecification</link> ) | ( <link linkend="prod112">function</link> ) | ( &lt;ID&gt; ( &lt;LSBRACE&gt; <link linkend="prod83">intVal</link> &lt;RSBRACE&gt; )? ) | <link linkend="prod100">subquery</link> | ( &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;RPAREN&gt; ( &lt;LSBRACE&gt; <link!
  linkend="prod83">intVal</link> &lt;RSBRACE&gt; )? ) | <link linkend="prod114">searchedCaseExpression</link> | <link linkend="prod115">caseExpression</link> )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod113" xreflabel="caseExpression"/>caseExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod113" xreflabel="windowSpecification"/>windowSpecification</para></entry>
 <entry align="left" valign="top"><para>::= 
+&lt;OVER&gt; &lt;LPAREN&gt; ( &lt;PARTITION&gt; &lt;BY&gt; <link linkend="prod47">expressionList</link> )? ( <link linkend="prod52">orderby</link> )? &lt;RPAREN&gt;</para></entry></row>
+<row>
+<entry align="right" valign="top"><para><anchor id="prod115" xreflabel="caseExpression"/>caseExpression</para></entry>
+<entry align="left" valign="top"><para>::= 
 &lt;CASE&gt; <link linkend="prod24">expression</link> ( &lt;WHEN&gt; <link linkend="prod24">expression</link> &lt;THEN&gt; <link linkend="prod24">expression</link> )+ ( &lt;ELSE&gt; <link linkend="prod24">expression</link> )? &lt;END&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod112" xreflabel="searchedCaseExpression"/>searchedCaseExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod114" xreflabel="searchedCaseExpression"/>searchedCaseExpression</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;CASE&gt; ( &lt;WHEN&gt; <link linkend="prod35">criteria</link> &lt;THEN&gt; <link linkend="prod24">expression</link> )+ ( &lt;ELSE&gt; <link linkend="prod24">expression</link> )? &lt;END&gt;</para></entry></row>
+&lt;CASE&gt; ( &lt;WHEN&gt; <link linkend="prod34">criteria</link> &lt;THEN&gt; <link linkend="prod24">expression</link> )+ ( &lt;ELSE&gt; <link linkend="prod24">expression</link> )? &lt;END&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod111" xreflabel="function"/>function</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod112" xreflabel="function"/>function</para></entry>
 <entry align="left" valign="top"><para>::= 
-( ( &lt;CONVERT&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;COMMA&gt; <link linkend="prod38">dataType</link> &lt;RPAREN&gt; ) | ( &lt;CAST&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;AS&gt; <link linkend="prod38">dataType</link> &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;COMMA&gt; <link linkend="prod114">stringConstant</link> &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; <link linkend="prod115">intervalType</link> &lt;COMMA&gt; <link linkend="prod24">expression</link> &lt;COMMA&gt; <link linkend="prod24">expression</link> &lt;RPAREN&gt; ) | <link linkend="prod116">queryString</link> | ( ( &lt;LEFT&gt; | &lt;RIGHT&gt; | &lt;CHAR&gt; | &lt;USER&gt; | &lt;YEAR&gt; | &lt;MONTH&gt; | &lt;HOUR&gt; | &lt;MINUTE&gt; | &lt;SECOND&gt; | &lt;XMLCONCAT&gt; | &lt;XMLCOMMENT&gt; ) &lt;LPAREN&gt; ( <link linkend="prod24">expression</link> !
 ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )* )? &lt;RPAREN&gt; ) | ( ( &lt;INSERT&gt; ) &lt;LPAREN&gt; ( <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )* )? &lt;RPAREN&gt; ) | ( ( &lt;TRANSLATE&gt; ) &lt;LPAREN&gt; ( <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )* )? &lt;RPAREN&gt; ) | <link linkend="prod117">xmlParse</link> | <link linkend="prod118">xmlElement</link> | ( &lt;XMLPI&gt; &lt;LPAREN&gt; ( &lt;ID&gt; <link linkend="prod119">idExpression</link> | <link linkend="prod119">idExpression</link> ) ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )? &lt;RPAREN&gt; ) | <link linkend="prod120">xmlForest</link> | <link linkend="prod81">xmlSerialize</link> | <link linkend="prod84">xmlQuery</link> | ( <link linkend="prod2">id</link> &lt;LPAREN&gt; ( <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )*!
  )? &lt;RPAREN&gt; ) )</para></entry></row>
+( ( &lt;CONVERT&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;COMMA&gt; <link linkend="prod37">dataType</link> &lt;RPAREN&gt; ) | ( &lt;CAST&gt; &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;AS&gt; <link linkend="prod37">dataType</link> &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;FROM&gt; <link linkend="prod24">expression</link> ( &lt;FOR&gt; <link linkend="prod24">expression</link> )? &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; ( &lt;YEAR&gt; | &lt;MONTH&gt; | &lt;DAY&gt; | &lt;HOUR&gt; | &lt;MINUTE&gt; | &lt;SECOND&gt; ) &lt;FROM&gt; <link linkend="prod24">expression</link> &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; ( ( ( ( &lt;LEADING&gt; | &lt;TRAILING&gt; | &lt;BOTH&gt; ) ( <link linkend="prod24">expression</link> )? ) | <link linkend="prod24">expression</link> ) &lt;FROM&gt; )? <link linkend!
 ="prod24">expression</link> &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; <link linkend="prod24">expression</link> &lt;COMMA&gt; <link linkend="prod116">stringConstant</link> &lt;RPAREN&gt; ) | ( <link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; <link linkend="prod117">intervalType</link> &lt;COMMA&gt; <link linkend="prod24">expression</link> &lt;COMMA&gt; <link linkend="prod24">expression</link> &lt;RPAREN&gt; ) | <link linkend="prod118">queryString</link> | ( ( &lt;LEFT&gt; | &lt;RIGHT&gt; | &lt;CHAR&gt; | &lt;USER&gt; | &lt;YEAR&gt; | &lt;MONTH&gt; | &lt;HOUR&gt; | &lt;MINUTE&gt; | &lt;SECOND&gt; | &lt;XMLCONCAT&gt; | &lt;XMLCOMMENT&gt; ) &lt;LPAREN&gt; ( <link linkend="prod47">expressionList</link> )? &lt;RPAREN&gt; ) | ( ( &lt;TRANSLATE&gt; | &lt;INSERT&gt; ) &lt;LPAREN&gt; ( <link linkend="prod47">expressionList</link> )? &lt;RPAREN&gt; ) | <link linkend="prod119">xmlParse</link> | <link linkend="prod120">xmlElement</link> | ( &l!
 t;XMLPI&gt; &lt;LPAREN&gt; ( &lt;ID&gt; <link linkend="prod121!
 ">idExpr
ession</link> | <link linkend="prod121">idExpression</link> ) ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )? &lt;RPAREN&gt; ) | <link linkend="prod122">xmlForest</link> | <link linkend="prod81">xmlSerialize</link> | <link linkend="prod84">xmlQuery</link> | ( <link linkend="prod2">id</link> &lt;LPAREN&gt; ( <link linkend="prod47">expressionList</link> )? &lt;RPAREN&gt; ) )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod114" xreflabel="stringConstant"/>stringConstant</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod116" xreflabel="stringConstant"/>stringConstant</para></entry>
 <entry align="left" valign="top"><para>::= 
 <link linkend="prod1">stringVal</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod117" xreflabel="xmlParse"/>xmlParse</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod119" xreflabel="xmlParse"/>xmlParse</para></entry>
 <entry align="left" valign="top"><para>::= 
 &lt;XMLPARSE&gt; &lt;LPAREN&gt; <link linkend="prod11">nonReserved</link> <link linkend="prod24">expression</link> ( <link linkend="prod11">nonReserved</link> )? &lt;RPAREN&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod116" xreflabel="queryString"/>queryString</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod118" xreflabel="queryString"/>queryString</para></entry>
 <entry align="left" valign="top"><para>::= 
-<link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod65">derivedColumn</link> )* &lt;RPAREN&gt;</para></entry></row>
+<link linkend="prod11">nonReserved</link> &lt;LPAREN&gt; <link linkend="prod24">expression</link> ( &lt;COMMA&gt; <link linkend="prod64">derivedColumn</link> )* &lt;RPAREN&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod118" xreflabel="xmlElement"/>xmlElement</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod120" xreflabel="xmlElement"/>xmlElement</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;XMLELEMENT&gt; &lt;LPAREN&gt; ( &lt;ID&gt; <link linkend="prod2">id</link> | <link linkend="prod2">id</link> ) ( &lt;COMMA&gt; <link linkend="prod85">xmlNamespaces</link> )? ( &lt;COMMA&gt; <link linkend="prod121">xmlAttributes</link> )? ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )* &lt;RPAREN&gt;</para></entry></row>
+&lt;XMLELEMENT&gt; &lt;LPAREN&gt; ( &lt;ID&gt; <link linkend="prod2">id</link> | <link linkend="prod2">id</link> ) ( &lt;COMMA&gt; <link linkend="prod85">xmlNamespaces</link> )? ( &lt;COMMA&gt; <link linkend="prod123">xmlAttributes</link> )? ( &lt;COMMA&gt; <link linkend="prod24">expression</link> )* &lt;RPAREN&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod121" xreflabel="xmlAttributes"/>xmlAttributes</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod123" xreflabel="xmlAttributes"/>xmlAttributes</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;XMLATTRIBUTES&gt; &lt;LPAREN&gt; <link linkend="prod65">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod65">derivedColumn</link> )* &lt;RPAREN&gt;</para></entry></row>
+&lt;XMLATTRIBUTES&gt; &lt;LPAREN&gt; <link linkend="prod64">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod64">derivedColumn</link> )* &lt;RPAREN&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod120" xreflabel="xmlForest"/>xmlForest</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod122" xreflabel="xmlForest"/>xmlForest</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;XMLFOREST&gt; &lt;LPAREN&gt; ( <link linkend="prod85">xmlNamespaces</link> &lt;COMMA&gt; )? <link linkend="prod65">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod65">derivedColumn</link> )* &lt;RPAREN&gt;</para></entry></row>
+&lt;XMLFOREST&gt; &lt;LPAREN&gt; ( <link linkend="prod85">xmlNamespaces</link> &lt;COMMA&gt; )? <link linkend="prod64">derivedColumn</link> ( &lt;COMMA&gt; <link linkend="prod64">derivedColumn</link> )* &lt;RPAREN&gt;</para></entry></row>
 <row>
 <entry align="right" valign="top"><para><anchor id="prod85" xreflabel="xmlNamespaces"/>xmlNamespaces</para></entry>
 <entry align="left" valign="top"><para>::= 
-&lt;XMLNAMESPACES&gt; &lt;LPAREN&gt; <link linkend="prod122">namespaceItem</link> ( &lt;COMMA&gt; <link linkend="prod122">namespaceItem</link> )* &lt;RPAREN&gt;</para></entry></row>
+&lt;XMLNAMESPACES&gt; &lt;LPAREN&gt; <link linkend="prod124">namespaceItem</link> ( &lt;COMMA&gt; <link linkend="prod124">namespaceItem</link> )* &lt;RPAREN&gt;</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod122" xreflabel="namespaceItem"/>namespaceItem</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod124" xreflabel="namespaceItem"/>namespaceItem</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( <link linkend="prod1">stringVal</link> &lt;AS&gt; <link linkend="prod2">id</link> )</para></entry></row>
 <row>
@@ -873,7 +886,7 @@
 <entry align="left" valign="top"><para>::= 
 ( &lt;DEFAULT_KEYWORD&gt; <link linkend="prod1">stringVal</link> )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod119" xreflabel="idExpression"/>idExpression</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod121" xreflabel="idExpression"/>idExpression</para></entry>
 <entry align="left" valign="top"><para>::= 
 <link linkend="prod2">id</link></para></entry></row>
 <row>
@@ -881,19 +894,19 @@
 <entry align="left" valign="top"><para>::= 
 ( &lt;STRING&gt; | &lt;VARCHAR&gt; | &lt;BOOLEAN&gt; | &lt;BYTE&gt; | &lt;TINYINT&gt; | &lt;SHORT&gt; | &lt;SMALLINT&gt; | &lt;CHAR&gt; | &lt;INTEGER&gt; | &lt;LONG&gt; | &lt;BIGINT&gt; | &lt;BIGINTEGER&gt; | &lt;FLOAT&gt; | &lt;REAL&gt; | &lt;DOUBLE&gt; | &lt;BIGDECIMAL&gt; | &lt;DECIMAL&gt; | &lt;DATE&gt; | &lt;TIME&gt; | &lt;TIMESTAMP&gt; | &lt;OBJECT&gt; | &lt;BLOB&gt; | &lt;CLOB&gt; | &lt;XML&gt; )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod38" xreflabel="dataType"/>dataType</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod37" xreflabel="dataType"/>dataType</para></entry>
 <entry align="left" valign="top"><para>::= 
 <link linkend="prod22">dataTypeString</link></para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod115" xreflabel="intervalType"/>intervalType</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod117" xreflabel="intervalType"/>intervalType</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( <link linkend="prod11">nonReserved</link> )</para></entry></row>
 <row>
-<entry align="right" valign="top"><para><anchor id="prod110" xreflabel="literal"/>literal</para></entry>
+<entry align="right" valign="top"><para><anchor id="prod111" xreflabel="literal"/>literal</para></entry>
 <entry align="left" valign="top"><para>::= 
 ( <link linkend="prod1">stringVal</link> | &lt;INTEGERVAL&gt; | &lt;FLOATVAL&gt; | &lt;FALSE&gt; | &lt;TRUE&gt; | &lt;UNKNOWN&gt; | &lt;NULL&gt; | ( ( &lt;BOOLEANTYPE&gt; | &lt;TIMESTAMPTYPE&gt; | &lt;DATETYPE&gt; | &lt;TIMETYPE&gt; ) <link linkend="prod1">stringVal</link> &lt;RBRACE&gt; ) )</para></entry></row>
 </tbody>
 </tgroup>
 </informaltable>
 </section>
-</appendix>
+</appendix>
\ No newline at end of file

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/procedures.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/procedures.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/procedures.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -218,12 +218,40 @@
   	  </section>
     </section>
     <section>
+      <title>Compound Statement</title>
+      <para>A compound statement or block logically groups a series of statements.  Temporary tables and variables created in a compound statement are local only to that block are destroyed when exiting the block.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >[label :] BEGIN [[NOT] ATOMIC]  
+  statement*
+END</synopsis>
+		<note><para>When a block is expected by a IF, LOOP, WHILE, etc. a single statement is also accepted by the parser.  Even though the block BEGIN/END are not expected, the statement will execute as if wrapped in a BEGIN/END pair.</para></note>
+      </para>
+      <itemizedlist>
+	 	<para>Syntax Rules</para>
+	    <listitem><para>IF NOT ATOMIC or no ATOMIC clause is specificed, the block will be executed non-atomically.</para>
+	    </listitem>
+	    <listitem><para>IF ATOMIC the block must execute atomically.  If a transaction is already associated with the thread, no aditional action will be taken - savepoints and/or sub-transactions are not currrently used.  Otherwise a transaction will be associated with the execution of the block.</para>
+	    </listitem>
+	    <listitem><para>The label must not be the same as any other label used in statements containing this one.</para>
+	    </listitem>
+      </itemizedlist>
+    </section>
+    <section>
       <title>If Statement</title>
       <para>An IF statement evaluates a condition and executes either
-        one of two blocks depending on the result. You can nest IF
+        one of two statements depending on the result. You can nest IF
         statements to create complex branching logic. A dependent ELSE
-        statement will execute its block of code only if the IF statement
+        statement will execute its statement only if the IF statement
         evaluates to false.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >IF (criteria) 
+  block
+[ELSE
+  block]
+END</synopsis>
+      </para>
       <example>
         <title>Example If Statement</title>
         <programlisting>IF ( var1 = 'North America') 
@@ -234,45 +262,90 @@
   ...statement... 
 END</programlisting>
       </example>
-      <note>
+      <tip>
         <para>
           NULL values should be considered in the criteria of an IF statement.  IS NULL criteria can be used to detect the presense of a NULL value.  
         </para>
-      </note>
+      </tip>
     </section>
     <section>
       <title>Loop Statement</title>
       <para>A LOOP statement is an iterative control construct that is used to cursor through a result set.</para>
       <para>
         Usage:
-        <synopsis label="Usage" >LOOP ON &lt;select statement&gt; AS &lt;cursorname&gt; 
-BEGIN 
-  ...
-END</synopsis>
+        <synopsis label="Usage" >[label :] LOOP ON &lt;select statement&gt; AS &lt;cursorname&gt; 
+  block</synopsis>
       </para>
+      <itemizedlist>
+	 	<para>Syntax Rules</para>
+	    <listitem><para>The label must not be the same as any other label used in statements containing this one.</para>
+	    </listitem>
+      </itemizedlist>
     </section>
     <section>
       <title>While Statement</title>
-      <para>A WHILE statement is an iterative control construct that is used to execute a set of statements repeatedly whenever a specified condition is met.</para>
+      <para>A WHILE statement is an iterative control construct that is used to execute a block repeatedly whenever a specified condition is met.</para>
       <para>
         Usage:
-        <synopsis label="Usage" >WHILE &lt;criteria&gt; 
-BEGIN 
-  ...
-END</synopsis>
+        <synopsis label="Usage" >[label :] WHILE &lt;criteria&gt; 
+  block</synopsis>
       </para>
+      <itemizedlist>
+	 	<para>Syntax Rules</para>
+	    <listitem><para>The label must not be the same as any other label used in statements containing this one.</para>
+	    </listitem>
+      </itemizedlist>
     </section>
     <section>
       <title>Continue Statement</title>
       <para>A CONTINUE statement is used inside a LOOP or WHILE construct to continue with the next loop by skipping over the rest of the statements in the loop. It must be used inside a LOOP or WHILE statement.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >CONTINUE [label];</synopsis>
+      </para>
+      <itemizedlist>
+	 	<para>Syntax Rules</para>
+	    <listitem><para>If the label is specified, it must exist on a containing LOOP or WHILE statement.</para>
+	    </listitem>
+	    <listitem><para>If no label is specified, the statement will affect the closest containing LOOP or WHILE statement.</para>
+	    </listitem>
+      </itemizedlist>
     </section>
     <section>
       <title>Break Statement</title>
       <para>A BREAK statement is used inside a LOOP or WHILE construct to break from the loop. It must be used inside a LOOP or WHILE statement.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >BREAK [label];</synopsis>
+      </para>
+      <itemizedlist>
+	 	<para>Syntax Rules</para>
+	    <listitem><para>If the label is specified, it must exist on a containing LOOP or WHILE statement.</para>
+	    </listitem>
+	    <listitem><para>If no label is specified, the statement will affect the closest containing LOOP or WHILE statement.</para>
+	    </listitem>
+      </itemizedlist>
     </section>
     <section>
+      <title>Leave Statement</title>
+      <para>A LEAVE statement is used inside a compound, LOOP, or WHILE construct to leave to the specified level.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >LEAVE label;</synopsis>
+      </para>
+      <itemizedlist>
+	 	<para>Syntax Rules</para>
+	    <listitem><para>The label must exist on a containing compound statement, LOOP, or WHILE statement.</para>
+	    </listitem>
+      </itemizedlist>
+    </section>
+    <section>
       <title>Error Statement</title>
       <para>An ERROR statement declares that the procedure has entered an error state and should abort. This statement will also roll back the current transaction, if one exists. Any valid expression can be specified after the ERROR keyword.</para>
+      <para>
+        Usage:
+        <synopsis label="Usage" >ERROR message;</synopsis>
+      </para>
       <example>
         <title>Example Error Statement</title>
         <programlisting>ERROR 'Invalid input value: ' || nvl(Acct.GetBalance.AcctID, 'null');</programlisting>
@@ -292,13 +365,10 @@
       <para>
         Usage:
         <synopsis label="Usage" >CREATE VIRTUAL PROCEDURE 
-BEGIN 
-  ...
-END</synopsis>
+block</synopsis>
       </para>
       <para>The CREATE VIRTUAL PROCEDURE line demarcates the beginning of
-        the procedure. The BEGIN and END keywords are used to denote block
-        boundaries. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
+        the procedure. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
       </para>
       <para>There is no explict cursoring or return statement, rather the last command statement executed in the procedure that returns a result set will be
         returned as the result. The output of that statement must match the
@@ -462,7 +532,7 @@
     	There may only be 1 FOR EACH ROW procedure for each INSERT, UPDATE, or DELETE operation against a view.  FOR EACH ROW update procedures can also be used to emulate BEFORE/AFTER each row triggers while still retaining the ability to perform an inherent update.  
     	This BEFORE/AFTER trigger behavior with an inherent update can be achieved by creating an additional updatable view over the target view with update proceudres of the form:
 		<programlisting lang="sql">FOR EACH ROW
-	BEGIN
+	BEGIN ATOMIC
 	--before row logic
 	
 	--default insert/update/delete against the target view
@@ -476,13 +546,16 @@
 	      <para>
 	        Usage:
 	        <synopsis label="Usage" >FOR EACH ROW 
-	BEGIN 
+	BEGIN ATOMIC
 	  ...
 	END</synopsis>
 	      </para>
 	      <para>The BEGIN and END keywords are used to denote block
 	        boundaries. Within the body of the procedure, any valid <link linkend="procedure_language">statement</link> may be used.
 	      </para>
+	      <note>
+	      <para>The use of the atomic keyword is currently optional for backward compatibility, but unlike a normal block, the default for instead of triggers is atomic.</para>
+	      </note>
 	    </section>
 	    <section>
 	      <title>Special Variables</title>

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/scalar_functions.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1005,6 +1005,7 @@
           <row>
             <entry>
               <para>SUBSTRING(x, y)</para>
+              <para>SUBSTRING(x FROM y)</para>
             </entry>
             <entry>
               <para>Get substring from x, from position y to the end of x
@@ -1017,6 +1018,7 @@
           <row>
             <entry>
               <para>SUBSTRING(x, y, z)</para>
+              <para>SUBSTRING(x FROM y FOR z)</para>
             </entry>
             <entry>
               <para>Get substring from x from position y with length z
@@ -1063,6 +1065,18 @@
           </row>
           <row>
             <entry>
+              <para>TRIM([[LEADING|TRAILING|BOTH] [x] FROM] y)</para>
+            </entry>
+            <entry>
+              <para>Trim the leading, trailing, or both ends of a string y of character x.  
+              If LEADING/TRAILING/BOTH is not specified, BOTH is used.  If no trim character x is specficed then the blank space ' ' is used.</para>
+            </entry>
+            <entry>
+              <para>x in {character}, y in {string}</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
               <para>UCASE(x)</para>
             </entry>
             <entry>
@@ -1194,6 +1208,21 @@
           </row>
           <row>
             <entry>
+              <para>EXTRACT(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND FROM x)</para>
+            </entry>
+            <entry>
+              <para>Return the given field value from the date value x.
+              Produces the same result as the assoceated YEAR, MONTH, DAYOFMONTH, HOUR, MINUTE, SECOND functions.
+              </para>
+              <para>The SQL specification also allows for TIMEZONE_HOUR and TIMEZONE_MINUTE as extraction targets.  
+              In Teiid all date values are in the timezone of the server.</para>
+            </entry>
+            <entry>
+              <para>x in {date, time, timestamp}, returns integer</para>
+            </entry>
+          </row>
+          <row>
+            <entry>
               <para>FORMATDATE(x, y)</para>
             </entry>
             <entry>
@@ -1795,20 +1824,21 @@
     <para><synopsis>LOOKUP(codeTable, returnColumn, keyColumn, keyValue)</synopsis></para>
     <para>In the lookup table codeTable, find the row where
       keyColumn has the value keyValue and return the
-      associated returnColumn. codeTable must be a fully-qualified string
-      literal containing metadata identifiers, keyValue datatype
-      must match datatype of the keyColumn, return datatype
-      matches that of returnColumn. returnColumn and
-      keyColumn parameters should use their shortened names.
+      associated returnColumn value or null if no matching key is found. codeTable must be a string literal that is the fully-qualified name of the target table.
+      returnColumn and key Column must also be string literals of just the relevant column names.
+      The keyValue can be any expression that must match the datatype of the keyColumn.  The return datatype
+      matches that of returnColumn.
     </para>
-    <para>For example, a StatePostalCodes table used to translate postal codes to
-      complete state names might represent an example of this type of
-      lookup table. One column, PostalCode, represents a key column.
-      Other tables refer to this two-letter code. A
-      second column, StateDisplayName, would represent the complete name
-      of the state. Hence, a query to this lookup table would typically
-      provide the PostalCode and expect the StateDisplayName in response.
-    </para>
+    <example>
+		<title>Country Code Lookup</title>
+		<programlisting>lookup('ISOCountryCodes', 'CountryName', 'CountryCode', 'US')</programlisting>
+		<para>A ISOCountryCodes table used to translate country name to
+      ISO codes. One column, CountryName, represents a key column.
+      A second column, CountryCode, would represent the ISO code of the country. 
+      Hence, a query to this lookup table would
+      provide a CountryName, shown above as 'US', and expect a CountryCode value in response.
+		</para>
+	</example>
     <para>When you call this function for any combination of codeTable, returnColumn, and
       keyColumn for the first time, the Teiid System caches the result. 
       The Teiid System uses this cache for all
@@ -1817,6 +1847,7 @@
       the Teiid System. Thus, you should not use this function for
       data that is subject to updates. Instead, you can use it against
       static data that does not change over time.</para>
+    <para>See the Caching Guide for more on the caching aspects of the lookup function.</para>
     <note>
       <itemizedlist>
         <listitem>
@@ -1829,100 +1860,44 @@
   <section>
     <title>System Functions</title>
     <para>System functions provide access to information in the Teiid system from within a query. </para>
-    <informaltable frame="all">
-      <tgroup cols="3">
-        <thead>
-          <row>
-            <entry>
-              <para>Function</para>
-            </entry>
-            <entry>
-              <para>Definition</para>
-            </entry>
-            <entry>
-              <para>Datatype Constraint</para>
-            </entry>
-          </row>
-        </thead>
-        <tbody>
-          <row>
-            <entry>
-              <para><code>COMMANDPAYLOAD()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the string form of the command payload
+      <section>
+    	<title>COMMANDPAYLOAD</title>
+    	<para>Retrieve a string from the command payload
                 or null if no command payload was specified. The command
                 payload is set by a method on the Teiid JDBC API
                 extensions on a per-query basis.</para>
-            </entry>
-            <entry>
-              <para>Returns a string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>COMMANDPAYLOAD(key)</code></para>
-            </entry>
-            <entry>
-              <para>Cast the command payload object to a
-                java.util.Properties object and look up the specified key in
-                the object</para>
-            </entry>
-            <entry>
-              <para>key in {string}, return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>ENV(key)</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve a system environment property. The only key specific to the current session is ‘sessionid’.  
+    	<para><synopsis>COMMANDPAYLOAD([key])</synopsis></para>
+    	<para>If the key parameter is provided, the command payload object is cast to a
+                java.util.Properties object and the corresponding property value for the key is returned.  If the key is not specified the return value is the command payload object toString value.</para>
+    	<para>key, return value are strings</para>
+     </section>
+     <section>
+    	<title>ENV</title>
+    	<para>Retrieve a system environment property.</para>
+    	<para><synopsis>ENV(key)</synopsis></para>
+    	<para>The only key specific to the current session is 'sessionid'.  
                 However the preferred mechanism for getting the session id is with the session_id() function.  
-                To prevent untrusted access to system properties, the use of this function must be specifically enabled in the &jboss-beans; file.
-                </para>
-            </entry>
-            <entry>
-              <para>key in {string}, return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>SESSION_ID()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the string form of the current session id.</para>
-            </entry>
-            <entry>
-              <para>return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>USER()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the name of the user executing the
-                query</para>
-            </entry>
-            <entry>
-              <para>return is string</para>
-            </entry>
-          </row>
-          <row>
-            <entry>
-              <para><code>CURRENT_DATABASE()</code></para>
-            </entry>
-            <entry>
-              <para>Retrieve the catalog name of the database. Currently VDB's name is also the catalog name.</para>
-            </entry>
-            <entry>
-              <para>return is string</para>
-            </entry>
-          </row>          
-        </tbody>
-      </tgroup>
-    </informaltable>
+                To prevent untrusted access to system properties, the use of this function must be specifically enabled in the &jboss-beans; file.</para>
+    	<para>key, return value are strings</para>
+     </section>
+     <section>
+    	<title>SESSION_ID</title>
+    	<para>Retrieve the string form of the current session id.</para>
+    	<para><synopsis>SESSION_ID()</synopsis></para>
+    	<para>return value is string.</para>
+     </section>
+     <section>
+    	<title>USER</title>
+    	<para>Retrieve the name of the user executing the query.</para>
+    	<para><synopsis>USER()</synopsis></para>
+    	<para>return value is string.</para>
+     </section>
+     <section>
+    	<title>CURRENT_DATABASE</title>
+    	<para>Retrieve the catalog name of the database. The VDB name is always the catalog name.</para>
+    	<para><synopsis>CURRENT_DATABASE()</synopsis></para>
+    	<para>return value is string.</para>
+     </section>
   </section>
   <section id="xml_functions">
     <title>XML Functions</title>
@@ -2036,9 +2011,7 @@
              <para>xquery in string. Return value is xml.</para>
              <para>XMLQUERY is part of the SQL/XML 2006 specification.</para>
              <para>See also <link linkend="xmltable">XMLTABLE</link></para>
-             <note><para>A technique known as document projection is used to reduce the memory footprint of the context item document.  
-             Only the parts of the document needed by the XQuery path expressions will be loaded into memory.  Since document projection analysis uses all relevant path expressions, even 1 expression that could potentially use many nodes, e.g. //x rather than /a/b/x will cause a larger memory footprint.</para></note>
-             
+             <note><para>See also <xref linkend="xquery_optimization"/></para></note>
     </section>
     <section id="xmlserialize">
     	<title>XMLSERIALIZE</title>

Copied: branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_clauses.xml (from rev 3382, trunk/documentation/reference/src/main/docbook/en-US/content/sql_clauses.xml)
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_clauses.xml	                        (rev 0)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_clauses.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,522 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
+<chapter id="sql_clauses">
+    <title>SQL Clauses</title>
+    <para>This section describes the clauses that are used in the various <link linkend="sql_commands">SQL commands</link> described in the previous section. Nearly all these features follow standard SQL syntax and functionality, so any SQL reference can be used for more information.</para>
+    <section id="with_clause">
+      <title>WITH Clause</title>
+      <para>
+      Teiid supports non-recursive common table expressions via the WITH clause.  With clause items may be referenced as tables in subsequent with clause items and in the main query.  The WITH clause can be thought of as providing query scoped temporary tables.
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage">WITH name [(column, ...)] AS (query expression) ... </synopsis>
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:</para>
+        <listitem><para>All of the projected column names must be unique.  If they are not unique, then the column name list must be provided.</para></listitem>
+        <listitem><para>If the columns of the WITH clause item are declared, then they must match the number of columns projected by the query expression.</para></listitem>
+        <listitem><para>Each with clause item must have a unique name.</para></listitem>
+      </itemizedlist> 
+    </section>
+    <section id="select_clause">
+      <title>SELECT Clause</title>
+      <para>
+      SQL queries that start with the SELECT keyword and are often referred to as "SELECT statements". Teiid supports most of the standard SQL query constructs.
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage">SELECT [DISTINCT|ALL] ((expression [[AS] name])|(group identifier.STAR))*|STAR ...</synopsis>
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:</para>
+        <listitem><para>Aliased expressions are only used as the output column names and in the ORDER BY clause. They cannot be used in other clauses of the query.</para></listitem>
+        <listitem><para>DISTINCT may only be specified if the SELECT symbols are comparable.</para></listitem>
+      </itemizedlist> 
+    </section>
+    <section id="from_clause">
+      <title>FROM Clause</title>
+      <para>
+      The FROM clause specifies the target table(s) for SELECT, UPDATE, and DELETE statements. 
+      </para>
+      <itemizedlist>
+        <para>Example Syntax:</para>
+        <listitem><para>FROM table [[AS] alias]</para></listitem>
+        <listitem><para>FROM table1 [INNER|LEFT OUTER|RIGHT OUTER|FULL OUTER] JOIN table2 ON join-criteria</para></listitem>
+        <listitem><para>FROM table1 CROSS JOIN table2</para></listitem>
+        <listitem><para>FROM (subquery) [AS] alias</para></listitem>
+        <listitem><para>FROM <link linkend="nested_table">TABLE(subquery)</link> [AS] alias</para></listitem>
+        <listitem><para>FROM table1 JOIN /*+ MAKEDEP */ table2 ON join-criteria</para></listitem>
+        <listitem><para>FROM table1 JOIN /*+ MAKENOTDEP */ table2 ON join-criteria</para></listitem>
+        <listitem><para>FROM /*+ MAKEIND */ table1 JOIN table2 ON join-criteria</para></listitem>
+        <listitem><para>FROM table1 left outer join <link linkend="optional_join">/*+ optional */</link> table2 ON join-criteria</para></listitem>
+        <listitem><para>FROM <link linkend="texttable">TEXTTABLE...</link></para></listitem>
+        <listitem><para>FROM <link linkend="xmltable">XMLTABLE...</link></para></listitem>
+        <listitem><para>FROM <link linkend="arraytable">ARRAYTABLE...</link></para></listitem>
+        <listitem><para>FROM <link linkend="from_subquery">(SELECT ...</link></para></listitem>
+      </itemizedlist> 
+      <note>
+        <title>DEP Hints</title>
+        <para>
+          MAKEIND, MAKEDEP, and MAKENOTDEP are hints used to control
+          <link linkend="dependent_joins">dependent join</link>
+          behavior. They should only be used in situations where the optimizer
+          does not choose the most optimal plan based upon query structure,
+          metadata, and costing information.  The hints may appear in a comment that proceeds the from clause.  
+          The hints can be specified against any from clause, not just a named table.
+        </para>
+      </note>
+      <section id="nested_table">
+		<title>Nested Table Reference</title>
+		<para>Nested tables may appear in the FROM clause with the TABLE
+			keyword. They are an alternative to using a view with normal join
+			semantics.  The columns projected from the command contained in the nested table
+			 may be used just as any of the other FROM clause projected columns in join criteria, the where clause, etc.
+      	</para>
+		<para>A nested table may have correlated references to preceeding FROM
+			clause column references as long as INNER and LEFT OUTER joins are used. This is
+			especially useful in cases where then nested expression is a
+			procedure or function call.</para>
+		<para>Valid example: 
+		<programlisting>select * from t1, TABLE(call proc(t1.x)) t2</programlisting>
+		</para>
+		<para>Invalid example, since t1 appears after the nested table in the from clause: 
+		<programlisting>select * from TABLE(call proc(t1.x)) t2, t1</programlisting>
+		</para>
+		<note>
+			<title>Multiple Execution</title>
+			<para>The usage of a correlated nested table may result in multiple
+				executions of the table expression - once for each correlated row.
+			</para>
+		</note>
+	  </section>
+	  <section id="texttable">
+		<title>TEXTTABLE</title>
+		<para>The TEXTTABLE funciton processes character input to produce tabular ouptut.  It supports both fixed and delimited file format parsing.  
+			The function itself defines what columns it projects.  
+		    The TEXTTABLE function is implicitly a nested table and may be correlated to preceeding FROM clause entries.
+      	</para>
+      	<para>
+        Usage:
+        	<synopsis label="Usage">TEXTTABLE(expression COLUMNS &lt;COLUMN&gt;, ... [NO ROW DELIMITER] [DELIMITER char] [(QUOTE|ESCAPE) char] [HEADER [integer]] [SKIP integer]) AS name</synopsis>
+        	<synopsis label="Usage">COLUMN := name datatype [WIDTH integer [NO TRIM]]</synopsis> 
+      	</para>
+      	<itemizedlist>
+        	<para>Parameters</para>
+        <listitem>
+          <para>expression - the text content to process, which should be convertable to CLOB.
+          </para>
+        </listitem>
+        <listitem>
+        	<para>NO ROW DELIMITER indicates that fixed parsing should not assume the presense of newline row delimiters.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>DELIMITER sets the field delimiter character to use.  Defaults to ','.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>QUOTE sets the quote, or qualifier, character used to wrap field values.  Defaults to '"'.  
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>ESCAPE sets the escape character to use if no quoting character is in use.  
+        	This is used in situations where the delimiter or new line characters are escaped with a preceding character, e.g. \,  
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>HEADER specifies the text line number (counting every new line) on which the column names occur.  All lines prior to the header will be skipped.
+        	If HEADER is specified, then the header line will be used to determine the TEXTTABLE column position by case-insensitive name matching.  This is especially useful in situations where only a subset of the columns are needed.
+        	If the HEADER value is not specified, it defaults to 1.  
+        	If HEADER is not specified, then columns are expected to match positionally with the text contents. 
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>SKIP specifies the number of text lines (counting every new line) to skip before parsing the contents.  HEADER may still be specified with SKP.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>WIDTH indicates the fixed-width length of a column in characters - not bytes.  The CR NL newline value counts as a single character.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>NO TRIM specifies that the text value should not be trimmed of all leading and trailing white space.
+        	</para>
+        </listitem>
+      	</itemizedlist>
+      	<itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>If width is specified for one column it must be specified for all columns and be a non-negative integer.
+          </para>
+        </listitem>
+        <listitem>
+          <para>If width is specified, then fixed width parsing is used and ESCAPE, QUOTE, and HEADER should not be specified.
+          </para>
+        </listitem>
+        <listitem>
+          <para>If width is not specified, then NO ROW DELIMITER cannot be used.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The columns names must be not contain duplicates.
+          </para>
+        </listitem>
+        </itemizedlist>
+      	<itemizedlist>
+        	<para>Examples</para>
+        	<listitem>
+		        <para>Use of the HEADER parameter, returns 1 row ['b']: <programlisting>SELECT * FROM TEXTTABLE(UNESCAPE('col1,col2,col3\na,b,c') COLUMNS col2 string HEADER) x</programlisting>
+				</para>		
+        	</listitem>
+        	<listitem>
+		        <para>Use of fixed width, returns 2 rows ['a', 'b', 'c'], ['d', 'e', 'f']: <programlisting>SELECT * FROM TEXTTABLE(UNESCAPE('abc\ndef') COLUMNS col1 string width 1, col2 string width 1, col3 string width 1) x</programlisting>
+				</para>		
+        	</listitem>
+        	<listitem>
+		        <para>Use of fixed width without a row delimiter, returns 3 rows ['a'], ['b'], ['c']: <programlisting>SELECT * FROM TEXTTABLE('abc' COLUMNS col1 string width 1 NO ROW DELIMITER) x</programlisting>
+				</para>		
+        	</listitem>
+        	<listitem>
+		        <para>Use of ESCAPE parameter, returns 1 row ['a,', 'b']: <programlisting>SELECT * FROM TEXTTABLE('a:,,b' COLUMNS col1 string, col2 string ESCAPE ':') x</programlisting>
+				</para>		
+        	</listitem>
+        	<listitem>
+		        <para>As a nested table: <programlisting>SELECT x.* FROM t, TEXTTABLE(t.clobcolumn COLUMNS first string, second date SKIP 1) x</programlisting>
+				</para>		
+        	</listitem>
+		</itemizedlist>		
+	  </section>
+	  <section id="xmltable">
+		<title>XMLTABLE</title>
+		<para>The XMLTABLE funciton uses XQuery to produce tabular ouptut.  
+		    The XMLTABLE function is implicitly a nested table and may be correlated to preceeding FROM clause entries.  XMLTABLE is part of the SQL/XML 2006 specification. 
+      	</para>
+      	<para>
+        Usage:
+        	<synopsis label="Usage">XMLTABLE([&lt;NSP&gt;,] xquery-expression [&lt;PASSING&gt;] [COLUMNS &lt;COLUMN&gt;, ... )] AS name</synopsis>
+        	<synopsis label="Usage">COLUMN := name (FOR ORDINALITY | (datatype [DEFAULT expression] [PATH string]))</synopsis> 
+      	</para>
+      	<para>See XMLELEMENT for the definition of NSP - <link linkend="xmlnamespaces">XMLNAMESPACES</link>.</para>
+      	<para>See XMLQUERY for the definition of <link linkend="passing">PASSING</link>.</para>
+      	<para>See also <link linkend="xmlquery">XMLQUERY</link></para>
+      	<note><para>See also <xref linkend="xquery_optimization"/></para></note>
+      	<itemizedlist>
+        	<para>Parameters</para>
+        <listitem>
+        	<para>The optional XMLNAMESPACES clause specifies the namepaces for use in the XQuery and COLUMN path expressions.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>The xquery-expression should be a valid XQuery.  Each sequence item returned by the xquery will be used to create a row of values as defined by the COLUMNS clause.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>If COLUMNS is not specified, then that is the same as having the COLUMNS clause: "COLUMNS OBJECT_VALUE XML PATH '.'", which returns the entire item as an XML value.   
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>A FOR ORDINALITY column is typed as integer and will return the 1-based item number as its value.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>Each non-ordinality column specifies a type and optionally a PATH and a DEFAULT expression.
+        	</para>
+        </listitem>
+        <listitem>
+        	<para>If PATH is not specified, then the path will be the same as the column name.
+        	</para>
+        </listitem>
+      	</itemizedlist>
+      	<itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>Only 1 FOR ORDINALITY column may be specified.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The columns names must be not contain duplicates.
+          </para>
+        </listitem>
+        </itemizedlist>
+      	<itemizedlist>
+        	<para>Examples</para>
+        	<listitem>
+		        <para>Use of passing, returns 1 row [1]: <programlisting>select * from xmltable('/a' PASSING xmlparse(document '&lt;a id="1"/&gt;') COLUMNS id integer PATH '@id') x</programlisting>
+				</para>		
+        	</listitem>
+        	<listitem>
+		        <para>As a nested table: <programlisting>select x.* from t, xmltable('/x/y' PASSING t.doc COLUMNS first string, second FOR ORDINALITY) x</programlisting>
+				</para>		
+        	</listitem>
+		</itemizedlist>		
+	  </section>
+    </section>
+    	  <section id="arraytable">
+		<title>ARRAYTABLE</title>
+		<para>The ARRAYTABLE funciton processes an array input to produce tabular ouptut.  
+			The function itself defines what columns it projects.  
+		    The ARRAYTABLE function is implicitly a nested table and may be correlated to preceeding FROM clause entries.
+      	</para>
+      	<para>
+        Usage:
+        	<synopsis label="Usage">ARRAYTABLE(expression COLUMNS &lt;COLUMN&gt;, ...) AS name</synopsis>
+        	<synopsis label="Usage">COLUMN := name datatype</synopsis> 
+      	</para>
+      	<itemizedlist>
+        	<para>Parameters</para>
+        <listitem>
+          <para>expression - the array to process, which should be a java.sql.Array or java array value.
+          </para>
+        </listitem>
+      	</itemizedlist>
+      	<itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>The columns names must be not contain duplicates.
+          </para>
+        </listitem>
+        </itemizedlist>
+      	<itemizedlist>
+        	<para>Examples</para>
+        	<listitem>
+		        <para>As a nested table: <programlisting>select x.* from (call source.invokeMDX('some query')) r, arraytable(r.tuple COLUMNS first string, second bigdecimal) x</programlisting>
+				</para>		
+        	</listitem>
+		</itemizedlist>
+		<para>ARRAYTABLE is effectively a shortcut for using the <xref linkend="array_get"/> function in a nested table.  For example "ARRAYGET(val COLUMNS col1 string, col2 integer) AS X" is the same as "TABLE(SELECT cast(array_get(val, 1) AS string) AS col1, cast(array_get(val, 2) AS integer) AS col2) AS X".</para>		
+	  </section>
+    <section id="where_clause">
+      <title>WHERE Clause</title>
+      <para>
+      The WHERE clause defines the criteria to limit the records affected by SELECT, UPDATE, and DELETE statements.  
+      </para>
+      <itemizedlist>
+        <para>The general form of the WHERE is:
+        </para>
+        <listitem>
+          <para>WHERE <link linkend="criteria">criteria</link>
+          </para>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section id="groupby_clause">
+      <title>GROUP BY Clause</title>
+      <para>
+      The GROUP BY clause denotes that rows should be grouped according to the specified expression values. One row will be returned for each group, after optionally filtering those aggregate rows based on a HAVING clause.   
+      </para>
+      <itemizedlist>
+        <para>The general form of the GROUP BY is:
+        </para>
+        <listitem>
+          <para>GROUP BY expression (,expression)*
+          </para>
+        </listitem>
+      </itemizedlist>
+      <itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>Column references in the group by clause must by to unaliased output columns.
+          </para>
+        </listitem>
+        <listitem>
+          <para>Expressions used in the group by must appear in the select clause.
+          </para>
+        </listitem>
+        <listitem>
+          <para>Column references and expessions in the select clause that are not used in the group by clause must appear in aggregate functions. 
+          </para>
+        </listitem>
+        <listitem>
+          <para>If an aggregate function is used in the SELECT clause and no
+            GROUP BY is specified, an implicit GROUP BY will be performed with
+            the entire result set as a single group. In this case, every column
+            in the SELECT must be an aggregate function as no other column value
+            will be fixed across the entire group. 
+          </para>
+        </listitem>
+        <listitem>
+          <para>The group by columns must be of a comparable type.</para>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section id="having_clause">
+      <title>HAVING Clause</title>
+      <para>
+      The HAVING clause operates exactly as a WHERE clause although it operates on the output of a GROUP BY. It supports the same syntax as the WHERE clause.
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>Expressions used in the group by clause must either
+            contain an aggregate function: COUNT, AVG, SUM, MIN, MAX. or be one
+            of the grouping expressions.</para>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section id="orderby_clause">
+      <title>ORDER BY Clause</title>
+      <para>
+      The ORDER BY clause specifies how records should be sorted. The options are ASC (ascending) and DESC (descending).
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage">ORDER BY expression [ASC|DESC] [NULLS (FIRST|LAST)], ...</synopsis>
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>Sort columns may be specified positionally by a 1-based positional
+	        integer, by SELECT clause alias name, by SELECT clause expression, or by an unrelated expression.</para>
+        </listitem>
+        <listitem>
+          <para>Column references may appear in the SELECT clause as the
+			expression for an aliased column or may reference columns from tables
+			in the FROM clause.
+			If the column reference is not in the SELECT clause the query must not
+			be a set operation, specify SELECT DISTINCT, or contain a GROUP BY
+			clause.</para>
+        </listitem>
+        <listitem>
+          <para>Unrelated expressions, expressions not appearing as an aliased expression in the select clause, 
+          are allowed in the order by clause of a non-set QUERY.  The columns referenced in the expression must come from the
+          from clause table references.  The column references cannot be to alias names or positional.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The ORDER BY columns must be of a comparable type.</para>
+        </listitem>
+        <listitem>
+          <para>If an ORDER BY is used in an inline view or view
+	         definition without a limit clause, it will be removed by the Teiid
+	         optimizer.</para>
+        </listitem>
+        <listitem>
+        	<para>If NULLS FIRST/LAST is specified, then nulls are guaranteed to be sorted either first or last.  If the null ordering is not specified, then results will 
+        	typically be sorted with nulls as low values, which is Teiid's internal default sorting behavior.   
+        	However not all sources return results with nulss sorted as low values by default, and Teiid may return results with different null orderings. 
+        	</para>
+        </listitem>
+      </itemizedlist>
+      <warning>
+		<para>The use of positional ordering is no longer supported by the
+				ANSI SQL standard and is a deprecated feature in Teiid. It is
+				preferable to use alias names in the order by clause.</para>
+	  </warning>
+    </section>
+    <section id="limit_clause">
+      <title>LIMIT Clause</title>
+      <para>
+      The LIMIT clause specifies a limit on the number of records returned from the SELECT command. An optional offset (the number of rows to skip) can be specified.  The LIMIT clause can also be specfied using the SQL 2008 OFFSET/FETCH FIRST clauses.  
+      If an ORDER BY is also specified, it will be applied before the OFFSET/LIMIT are applied.  If an ORDER BY is not specified there is generally no guarantee what subset of rows will be returned.
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage">LIMIT [offset,] limit</synopsis>
+        <synopsis label="Usage">[OFFSET offset ROW|ROWS] [FETCH FIRST|NEXT [limit] ROW|ROWS ONLY</synopsis>
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>The limit/offset expressions must be a non-negative integer or a parameter reference (?).  An offset of 0 is ignored.  A limit of 0 will return no rows.
+          </para>
+        </listitem>
+        <listitem>
+          <para>The terms FIRST/NEXT are interchangable as well as ROW/ROWS.
+          </para>
+        </listitem>
+      </itemizedlist>
+      <itemizedlist>
+        <para>Examples:
+        </para>
+        <listitem>
+          <para>LIMIT 100 - returns the first 100 records (rows 1-100)</para>
+        </listitem>
+        <listitem>
+          <para>LIMIT 500, 100 - skips 500 records and returns the next 100 records (rows 501-600)</para>
+        </listitem>
+        <listitem>
+          <para>OFFSET 500 ROWS - skips 500 records</para>
+        </listitem>
+        <listitem>
+          <para>OFFSET 500 ROWS FETCH NEXT 100 ROWS ONLY - skips 500 records and returns the next 100 records (rows 501-600)</para>
+        </listitem>
+        <listitem>
+          <para>FETCH FIRST ROW ONLY - returns only the first record</para>
+        </listitem>
+      </itemizedlist>
+    </section>
+    <section id="into_clause">
+      <title>INTO Clause</title>
+      <warning>
+      	<para>Usage of the INTO Clause for inserting into a table has been been deprecated.  An <link linkend="insert_command">INSERT</link> with a query command should be used instead.</para>
+      </warning>
+      <para>
+      When the into clause is specified with a SELECT, the results of the query are inserted into the specified table. This is often used to insert records into a temporary table. The INTO clause immediately precedes the FROM clause.   
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage">INTO table FROM ...</synopsis>
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+          <para>The INTO clause is logically applied last in processing, after the ORDER BY and LIMIT clauses.</para>
+        </listitem>
+        <listitem>
+          <para>Teiid's support for SELECT INTO is similar to
+            MS SQL Server. The target of the INTO clause is a table where
+            the result of the rest select command will be inserted. SELECT
+            INTO should not be used UNION query.</para>
+        </listitem>
+      </itemizedlist>
+    </section>    
+    <section id="option_clause">
+      <title>OPTION Clause</title>
+      <para>
+      The OPTION keyword denotes options the user can pass in with the command. These options are Teiid-specific and not covered by any SQL specification.  
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage">OPTION option, (option)*</synopsis>
+      </para>
+      <itemizedlist>
+        <para>Supported options:
+        </para>
+        <listitem>
+          <para>MAKEDEP table [(,table)*] - specifies source tables that should be made dependent in the join
+          </para>
+        </listitem>
+        <listitem>
+          <para>MAKENOTDEP table [(,table)*] - prevents a dependent join from being used
+          </para>
+        </listitem>
+        <listitem>
+          <para>NOCACHE [table (,table)*] - prevents cache from being used for all tables or for the given tables
+          </para>
+        </listitem>
+      </itemizedlist>
+      <itemizedlist>
+        <para>Examples:
+        </para>
+        <listitem>
+          <para>OPTION MAKEDEP table1</para>
+        </listitem>
+        <listitem>
+          <para>OPTION NOCACHE</para>
+        </listitem>
+      </itemizedlist>
+      <para>All tables specified in the OPTION clause should be fully qualified.</para>
+      <note><para>Previous versions of Teiid accepted the PLANONLY, DEBUG, and SHOWPLAN option arguments.  These are no longer accepted in the OPTION clause.
+      Please see the Client Developers Guide for replacements to those options.
+      </para></note>
+    </section>
+</chapter>
\ No newline at end of file

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_support.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_support.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/sql_support.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -108,8 +108,14 @@
       resulting names are unambiguous in the context of the command.
       Different forms of qualification can be mixed in the same query.
     </para>
+    <section>
+    	<title>Reserved Words</title>
+    	<para>Teiid's reserved words include the standard SQL 2003 Foundation, SQL/MED, and SQL/XML reserved words, as well as Teiid specific words such as BIGINTEGER, BIGDECIMAL, or MAKEDEP. 
+    	See the <xref linkend="grammar"/> TOKENS section for all reserved words.  They will appear as 'SMALLINT: "smallint"' where the quoted string is the actual lexical form. 
+    	 </para>
+    </section>
   </section>
-  <section>
+  <section id="expressions">
     <title>Expressions</title>
     <para> Identifiers, literals, and functions can be combined into
       expressions. Expressions can be used almost anywhere in a query --
@@ -130,6 +136,9 @@
         <para><link linkend="aggregate_functions">Aggregate functions</link></para>
       </listitem>
       <listitem>
+        <para><link linkend="window_functions">Window functions</link></para>
+      </listitem>
+      <listitem>
         <para><link linkend="case">Case and searched case</link></para>
       </listitem>
       <listitem>
@@ -247,7 +256,7 @@
           </para>
         </listitem>                
         <listitem>
-          <para>XMLAGG(xml_expr <link linkend="orderby_clause">[ORDER BY ...]</link>) – xml concatination of all xml expressions in a group (excluding null)</para>
+          <para>XMLAGG(xml_expr <link linkend="orderby_clause">[ORDER BY ...]</link>) – xml concatination of all xml expressions in a group (excluding null).  The ORDER BY clause cannot reference alias names or use positional ordering.</para>
         </listitem>                
       </itemizedlist>
       <itemizedlist>
@@ -258,18 +267,144 @@
           </para>
         </listitem>
         <listitem>
-          <para>Aggregate functions may only be used in the HAVING or SELECT clauses and may not be nested within another aggregate function.
+          <para>Aggregate functions cannot be used in FROM, GROUP BY, or WHERE clauses without an intervening query expression.
           </para>
         </listitem>
         <listitem>
+          <para>Aggregate functions cannot be nested within another aggregate function without an intervening query expression.
+          </para>
+        </listitem>
+        <listitem>
           <para>Aggregate functions may be nested inside other functions.
           </para>
         </listitem>
+        <listitem>
+          <para>Any aggregate function may take an optional FILTER clasue of the form <synopsis label="Usage">FILTER ( WHERE condition )</synopsis>.  The condition may be any boolean value expression that does not contain a subquery or a correlated variable.
+	      The filter will logically be evaluated for each row prior to the grouping operation.  If false the aggregate function will not accumulate a value for the given row.          
+          </para>
+        </listitem>
       </itemizedlist>
       <para>
       For more information on aggregates, see the sections on GROUP BY or HAVING.
       </para>
     </section>
+    <section id="window_functions">
+      <title>Window functions</title>
+      <para>Teiid supports ANSI SQL 2003 window functions.  A window function allows an aggregrate function to be applied to a subset of the result set, without the need for a GROUP BY clause.  
+      A window function is similar to an aggregate function, but requires the use of an OVER clause or window specification.
+      </para>
+      <para>
+        Usage:
+        <synopsis label="Usage">aggregate|ranking OVER ([PARTION BY expression [, expression]*] <link linkend="orderby_clause">[ORDER BY ...]</link>)</synopsis>
+        aggregate can be any <xref linkend="aggregate_functions"/>.  Ranking can be one of ROW_NUMBER(), RANK(), DENSE_RANK().   
+      </para>
+      <itemizedlist>
+        <para>Syntax Rules:
+        </para>
+        <listitem>
+	      <para>Window functions can only appear in the SELECT and ORDER BY clauses of a query expression.
+	      </para>
+        </listitem>
+        <listitem>
+	      <para>Window functions cannot be nested in one another.
+	      </para>
+        </listitem>
+        <listitem>
+	      <para>Partitioning and order by expressions cannot contain subqueries or outer references.
+	      </para>
+        </listitem>
+        <listitem>
+	      <para>The ranking (ROW_NUMBER, RANK, DENSE_RANK) functions require the use of the window specification ORDER BY clause.
+	      </para>
+        </listitem>
+        <listitem>
+	      <para>An XMLAGG ORDER BY clause cannot be used when windowed.
+	      </para>
+        </listitem>        
+        <listitem>
+	      <para>The window specification ORDER BY clause cannot reference alias names or use positional ordering.
+	      </para>
+        </listitem>
+        <listitem>
+	      <para>Windowed aggregates may not use DISTINCT.
+	      </para>
+        </listitem>
+	  </itemizedlist>
+	  <section>
+	  	<title>Function Definitions</title>
+	  	<itemizedlist>
+	        <listitem>
+	          <para>ROW_NUMBER() – functional the same as COUNT(*) with the same window specification.  Assigns a number to each row in a partition starting at 1.</para>
+	        </listitem>
+	        <listitem>
+	          <para>RANK() – Assigns a number to each unique ordering value within each partition starting at 1, such that the next rank is equal to the count of prior rows.</para>
+	        </listitem>
+	        <listitem>
+	          <para>DENSE_RANK() – Assigns a number to each unique ordering value within each partition starting at 1, such that the next rank is sequential.</para>
+	        </listitem>
+		</itemizedlist>	  	
+	  </section>
+	  <section>
+	  	<title>Processing</title>
+	  	<para>Window functions are logically processed just before creating the output from the SELECT clause. 	Window functions can use nested aggregates if a GROUP BY clause is present.
+	  	The is no guarenteed affect on the output ordering from the presense of window functions.  The SELECT statement must have an ORDER BY clause to have a predictable ordering.
+	  	</para><para>
+	  	Teiid will process all window functions with the same window specification together.  In general a full pass over the row values coming into the SELECT clause will be required for each unique window specification.
+	  	For each window specification the values will be grouped according to the PARTITION BY clause.  If no PARTITION BY clause is specified, then the entire input is treated as a single partition.
+	  	The output value is determined based upon the current row value, it's peers (that is rows that are the same with respect to their ordering), and all prior row values based upon ordering in the partition.
+	  	The ROW_NUMBER function will assign a unique value to every row regardless of the number of peers.
+	  	</para>
+	  	<example>
+          <title>Example Windowed Results</title>
+          <programlisting language="SQL">SELECT name, salary, max(salary) over (partition by name) as max_sal, 
+          rank() over (order by salary) as rank, dense_rank() over (order by salary) as dense_rank, 
+          row_number() over (order by salary) as row_num FROM employees</programlisting>
+          <informaltable frame="all">
+			<tgroup cols="6">
+				<thead>
+					<row>
+						<entry>
+							<para>name</para>
+						</entry>
+						<entry>
+							<para>salary</para>
+						</entry>
+						<entry>
+							<para>max_sal</para>
+						</entry>
+						<entry>
+							<para>rank</para>
+						</entry>
+						<entry>
+							<para>dense_rank</para>
+						</entry>
+						<entry>
+							<para>row_num</para>
+						</entry>
+					</row>
+				</thead>
+				<tbody>
+					<row>
+					<entry><para>John</para></entry><entry><para>100000</para></entry><entry><para>100000</para></entry><entry><para>2</para></entry><entry><para>2</para></entry><entry><para>2</para></entry>
+					</row>
+					<row>
+					<entry><para>Henry</para></entry><entry><para>50000</para></entry><entry><para>100000</para></entry><entry><para>5</para></entry><entry><para>4</para></entry><entry><para>5</para></entry>
+					</row>
+					<row>
+					<entry><para>John</para></entry><entry><para>60000</para></entry><entry><para>60000</para></entry><entry><para>3</para></entry><entry><para>3</para></entry><entry><para>3</para></entry>
+					</row>
+					<row>
+					<entry><para>Suzie</para></entry><entry><para>60000</para></entry><entry><para>150000</para></entry><entry><para>3</para></entry><entry><para>3</para></entry><entry><para>4</para></entry>
+					</row>
+					<row>
+					<entry><para>Suzie</para></entry><entry><para>150000</para></entry><entry><para>150000</para></entry><entry><para>1</para></entry><entry><para>1</para></entry><entry><para>1</para></entry>
+					</row>
+				</tbody>
+				</tgroup>
+			</informaltable>						
+        </example>
+	  </section>
+    </section>
     <section id="case">
       <title>Case and searched case</title>
       <para>
@@ -336,50 +471,81 @@
       </listitem>
     </itemizedlist>
     <itemizedlist>
-      <para>Syntax Rules:
+      <para>Usage:
       </para>
       <listitem>
-        <para>expression (=|&lt;&gt;|!=|&lt;|>|&lt;=|>=) (expression|((ANY|ALL|SOME) subquery))
+        <para><synopsis label="Usage">criteria AND|OR criteria</synopsis>
         </para>
       </listitem>
       <listitem>
-        <para>expression [NOT] IS NULL
+        <para><synopsis label="Usage">NOT criteria</synopsis>
         </para>
       </listitem>
       <listitem>
-        <para>expression [NOT] IN (expression[,expression]*)|subquery
+        <para><synopsis label="Usage">(criteria)</synopsis>
         </para>
       </listitem>
       <listitem>
-        <para>expression [NOT] LIKE expression [ESCAPE char]
+        <para><synopsis label="Usage">expression (=|&lt;&gt;|!=|&lt;|>|&lt;=|>=) (expression|((ANY|ALL|SOME) subquery))</synopsis>
         </para>
       </listitem>
       <listitem>
-        <para>EXISTS(subquery)
+        <para><synopsis label="Usage">expression [NOT] IS NULL</synopsis>
         </para>
       </listitem>
       <listitem>
-        <para>expression BETWEEN minExpression AND maxExpression
+        <para><synopsis label="Usage">expression [NOT] IN (expression[,expression]*)|subquery</synopsis>
         </para>
       </listitem>
       <listitem>
-        <para>criteria AND|OR criteria
+        <para><synopsis label="Usage">expression [NOT] LIKE pattern [ESCAPE char]</synopsis>
+        Matches the string expression against the given string pattern.  
+        The pattern may contain % to match any number of characters and _ to match any single character.  The escape character can be used to escape the match characters % and _.</para>
+      </listitem>
+      <listitem>
+        <para><synopsis label="Usage">expression [NOT] SIMILAR TO pattern [ESCAPE char]</synopsis>
+        SIMILAR TO is a cross between LIKE and standard regular expression syntax.  % and _ are still used, rather than .* and . respectively.</para>
+        <note><para>Teiid does not exhaustively validate SIMILAR TO pattern values.  Rather the pattern is converted to an equivalent regular expression.  
+        Care should be taken not to rely on general regular expression features when using SIMILAR TO.  If additional features are needed, then LIKE_REGEX should be used.
+        Usage of a non-literal pattern is discouraged as pushdown support is limited.</para></note>
+      </listitem>
+      <listitem>
+        <para><synopsis label="Usage">expression [NOT] LIKE_REGEX pattern</synopsis>
+        LIKE_REGEX allows for standard regular expression syntax to be used for matching.  This differs from SIMILAR TO and LIKE in that the escape character is no longer used (\ is already the 
+        standard escape mechansim in regular expressions and % and _ have no special meaning.  
+        The runtime engine uses the JRE implementation of regular expressions - see the <ulink url="http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html">java.util.regex.Pattern</ulink> class for details.
+        <note><para>Teiid does not exhaustively validate LIKE_REGEX pattern values.  It is possible to use JRE only regular expression features that are not specified by the SQL specification.  Additional not all sources support
+        the same regular expression flavor or extensions.  Care should be taken in pushdown situations to ensure that the pattern used will have same meaning in Teiid and across all applicable sources.</para></note>
         </para>
       </listitem>
       <listitem>
-        <para>NOT criteria
+        <para><synopsis label="Usage">EXISTS(subquery)</synopsis>
         </para>
       </listitem>
       <listitem>
-        <para>expression
+        <para><synopsis label="Usage">expression [NOT] BETWEEN minExpression AND maxExpression</synopsis>
+        Teiid converts BETWEEN into the equivalent form expression &gt;= minExpression AND expression &lt;= maxExpression
         </para>
       </listitem>
       <listitem>
-        <para>Criteria may be nested using parenthesis.
+        <para><synopsis label="Usage">expression</synopsis>
+        Where expression has type boolean.
         </para>
       </listitem>
     </itemizedlist>
     <itemizedlist>
+      <para>Syntax Rules:
+      </para>
+      <listitem>
+        <para>The precedence ordering from lowest to highest is comparison, NOT, AND, OR 
+        </para>
+      </listitem>
+      <listitem>
+        <para>Criteria nested by parenthesis will be logically evaluated prior to evaluating the parent criteria.
+        </para>
+      </listitem>
+    </itemizedlist>
+    <itemizedlist>
       <para>Some examples of valid criteria are:
       </para>
       <listitem>
@@ -445,7 +611,7 @@
         </listitem>
         <listitem>  
           <para>
-            <link linkend="limit_clause">[LIMIT [offset,] limit]</link>
+            <link linkend="limit_clause">[(LIMIT ...) | ([OFFSET ...] [FETCH ...])]</link>
           </para>
         </listitem>
         <listitem>  
@@ -651,469 +817,6 @@
 	  </note>
     </section>
   </section>
-  <section>
-    <title>SQL Clauses</title>
-    <para>This section describes the clauses that are used in the various <link linkend="sql_commands">SQL commands</link> described in the previous section. Nearly all these features follow standard SQL syntax and functionality, so any SQL reference can be used for more information.</para>
-    <section id="with_clause">
-      <title>WITH Clause</title>
-      <para>
-      Teiid supports non-recursive common table expressions via the WITH clause.  With clause items may be referenced as tables in subsequent with clause items and in the main query.  The WITH clause can be thought of as providing query scoped temporary tables.
-      </para>
-      <para>
-        Usage:
-        <synopsis label="Usage">WITH name [(column, ...)] AS (query expression) ... </synopsis>
-      </para>
-      <itemizedlist>
-        <para>Syntax Rules:</para>
-        <listitem><para>All of the projected column names must be unique.  If they are not unique, then the column name list must be provided.</para></listitem>
-        <listitem><para>If the columns of the WITH clause item are declared, then they must match the number of columns projected by the query expression.</para></listitem>
-        <listitem><para>Each with clause item must have a unique name.</para></listitem>
-      </itemizedlist> 
-    </section>
-    <section id="select_clause">
-      <title>SELECT Clause</title>
-      <para>
-      SQL queries that start with the SELECT keyword and are often referred to as "SELECT statements". Teiid supports most of the standard SQL query constructs.
-      </para>
-      <para>
-        Usage:
-        <synopsis label="Usage">SELECT [DISTINCT|ALL] ((expression [[AS] name])|(group identifier.STAR))*|STAR ...</synopsis>
-      </para>
-      <itemizedlist>
-        <para>Syntax Rules:</para>
-        <listitem><para>Aliased expressions are only used as the output column names and in the ORDER BY clause. They cannot be used in other clauses of the query.</para></listitem>
-        <listitem><para>DISTINCT may only be specified if the SELECT symbols are comparable.</para></listitem>
-      </itemizedlist> 
-    </section>
-    <section id="from_clause">
-      <title>FROM Clause</title>
-      <para>
-      The FROM clause specifies the target table(s) for SELECT, UPDATE, and DELETE statements. 
-      </para>
-      <itemizedlist>
-        <para>Example Syntax:</para>
-        <listitem><para>FROM table [[AS] alias]</para></listitem>
-        <listitem><para>FROM table1 [INNER|LEFT OUTER|RIGHT OUTER|FULL OUTER] JOIN table2 ON join-criteria</para></listitem>
-        <listitem><para>FROM table1 CROSS JOIN table2</para></listitem>
-        <listitem><para>FROM (subquery) [AS] alias</para></listitem>
-        <listitem><para>FROM <link linkend="nested_table">TABLE(subquery)</link> [AS] alias</para></listitem>
-        <listitem><para>FROM table1 JOIN table2 MAKEDEP ON join-criteria</para></listitem>
-        <listitem><para>FROM table1 JOIN table2 MAKENOTDEP ON join-criteria</para></listitem>
-        <listitem><para>FROM table1 left outer join <link linkend="optional_join">/*+ optional */</link> table2 ON join-criteria</para></listitem>
-        <listitem><para>FROM <link linkend="texttable">TEXTTABLE...</link></para></listitem>
-        <listitem><para>FROM <link linkend="xmltable">XMLTABLE...</link></para></listitem>
-        <listitem><para>FROM <link linkend="arraytable">ARRAYTABLE...</link></para></listitem>
-        <listitem><para>FROM <link linkend="from_subquery">(SELECT ...</link></para></listitem>
-      </itemizedlist> 
-      <note>
-        <title>DEP Hints</title>
-        <para>
-          MAKEDEP and MAKENOTDEP are hints used to control
-          <link linkend="dependent_joins">dependent join</link>
-          behavior. They should only be used in situations where the optimizer
-          does not choose the most optimal plan based upon query structure,
-          metadata, and costing information.
-        </para>
-      </note>
-      <section id="nested_table">
-		<title>Nested Table Reference</title>
-		<para>Nested tables may appear in the FROM clause with the TABLE
-			keyword. They are an alternative to using a view with normal join
-			semantics.  The columns projected from the command contained in the nested table
-			 may be used just as any of the other FROM clause projected columns in join criteria, the where clause, etc.
-      	</para>
-		<para>A nested table may have correlated references to preceeding FROM
-			clause column references as long as INNER and LEFT OUTER joins are used. This is
-			especially useful in cases where then nested expression is a
-			procedure or function call.</para>
-		<para>Valid example: 
-		<programlisting>select * from t1, TABLE(call proc(t1.x)) t2</programlisting>
-		</para>
-		<para>Invalid example, since t1 appears after the nested table in the from clause: 
-		<programlisting>select * from TABLE(call proc(t1.x)) t2, t1</programlisting>
-		</para>
-		<note>
-			<title>Multiple Execution</title>
-			<para>The usage of a correlated nested table may result in multiple
-				executions of the table expression - once for each correlated row.
-			</para>
-		</note>
-	  </section>
-	  <section id="texttable">
-		<title>TEXTTABLE</title>
-		<para>The TEXTTABLE funciton processes character input to produce tabular ouptut.  It supports both fixed and delimited file format parsing.  
-			The function itself defines what columns it projects.  
-		    The TEXTTABLE function is implicitly a nested table and may be correlated to preceeding FROM clause entries.
-      	</para>
-      	<para>
-        Usage:
-        	<synopsis label="Usage">TEXTTABLE(expression COLUMNS &lt;COLUMN&gt;, ... [DELIMITER char] [(QUOTE|ESCAPE) char] [HEADER [integer]] [SKIP integer]) AS name</synopsis>
-        	<synopsis label="Usage">COLUMN := name datatype [WIDTH integer]</synopsis> 
-      	</para>
-      	<itemizedlist>
-        	<para>Parameters</para>
-        <listitem>
-          <para>expression - the text content to process, which should be convertable to CLOB.
-          </para>
-        </listitem>
-        <listitem>
-        	<para>DELIMITER sets the field delimiter character to use.  Defaults to ','.
-        	</para>
-        </listitem>
-        <listitem>
-        	<para>QUOTE sets the quote, or qualifier, character used to wrap field values.  Defaults to '"'.  
-        	</para>
-        </listitem>
-        <listitem>
-        	<para>ESCAPE sets the escape character to use if no quoting character is in use.  
-        	This is used in situations where the delimiter or new line characters are escaped with a preceding character, e.g. \,  
-        	</para>
-        </listitem>
-        <listitem>
-        	<para>HEADER specifies the text line number (counting every new line) on which the column names occur.  All lines prior to the header will be skipped.
-        	If HEADER is specified, then the header line will be used to determine the TEXTTABLE column position by case-insensitive name matching.  This is especially useful in situations where only a subset of the columns are needed.
-        	If the HEADER value is not specified, it defaults to 1.  
-        	If HEADER is not specified, then columns are expected to match positionally with the text contents. 
-        	</para>
-        </listitem>
-        <listitem>
-        	<para>SKIP specifies the number of text lines (counting every new line) to skip before parsing the contents.  HEADER may still be specified with SKP.
-        	</para>
-        </listitem>
-      	</itemizedlist>
-      	<itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>If width is specified for one column it must be specified for all columns.
-          </para>
-        </listitem>
-        <listitem>
-          <para>If width is specified, then fixed width parsing is used and ESCAPE, QUOTE, and HEADER should not be specified.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The columns names must be not contain duplicates.
-          </para>
-        </listitem>
-        </itemizedlist>
-      	<itemizedlist>
-        	<para>Examples</para>
-        	<listitem>
-		        <para>Use of the HEADER parameter, returns 1 row ['b']: <programlisting>select * from texttable('col1,col2,col3\na,b,c' COLUMNS col2 string HEADER) x</programlisting>
-				</para>		
-        	</listitem>
-        	<listitem>
-		        <para>Use of fixed width, returns 1 row ['a', 'b', 'c']: <programlisting>select * from texttable('abc' COLUMNS col1 string width 1, col2 string width 1, col3 string width 1) x</programlisting>
-				</para>		
-        	</listitem>
-        	<listitem>
-		        <para>Use of ESCAPE parameter, returns 1 row ['a,', 'b']: <programlisting>select * from texttable('a:,,b' COLUMNS col1 string, col2 string ESCAPE ':') x</programlisting>
-				</para>		
-        	</listitem>
-        	<listitem>
-		        <para>As a nested table: <programlisting>select x.* from t, texttable(t.clobcolumn COLUMNS first string, second date SKIP 1) x</programlisting>
-				</para>		
-        	</listitem>
-		</itemizedlist>		
-	  </section>
-	  <section id="xmltable">
-		<title>XMLTABLE</title>
-		<para>The XMLTABLE funciton uses XQuery to produce tabular ouptut.  
-		    The XMLTABLE function is implicitly a nested table and may be correlated to preceeding FROM clause entries.  XMLTABLE is part of the SQL/XML 2006 specification. 
-      	</para>
-      	<para>
-        Usage:
-        	<synopsis label="Usage">XMLTABLE([&lt;NSP&gt;,] xquery-expression [&lt;PASSING&gt;] [COLUMNS &lt;COLUMN&gt;, ... )] AS name</synopsis>
-        	<synopsis label="Usage">COLUMN := name (FOR ORDINALITY | (datatype [DEFAULT expression] [PATH string]))</synopsis> 
-      	</para>
-      	<para>See XMLELEMENT for the definition of NSP - <link linkend="xmlnamespaces">XMLNAMESPACES</link>.</para>
-      	<para>See XMLQUERY for the definition of <link linkend="passing">PASSING</link>.</para>
-      	<para>See also <link linkend="xmlquery">XMLQUERY</link></para>
-      	<itemizedlist>
-        	<para>Parameters</para>
-        <listitem>
-        	<para>The optional XMLNAMESPACES clause specifies the namepaces for use in the XQuery and COLUMN path expressions.
-        	</para>
-        </listitem>
-        <listitem>
-        	<para>The xquery-expression should be a valid XQuery.  Each sequence item returned by the xquery will be used to create a row of values as defined by the COLUMNS clause.
-        	</para>
-        </listitem>
-        <listitem>
-        	<para>If COLUMNS is not specified, then that is the same as having the COLUMNS clause: "COLUMNS OBJECT_VALUE XML PATH '.'", which returns the entire item as an XML value.  Each non-ordinality column specifies a type and optionally a PATH and a DEFAULT expression.  
-        	If PATH is not specified, then the path will be the same as the column name.  A FOR ORDINALITY column is typed as integer and will return the 1-based item number as its value.    
-        	</para>
-        </listitem>
-      	</itemizedlist>
-      	<itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>Only 1 FOR ORDINALITY column may be specified.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The columns names must be not contain duplicates.
-          </para>
-        </listitem>
-        </itemizedlist>
-      	<itemizedlist>
-        	<para>Examples</para>
-        	<listitem>
-		        <para>Use of passing, returns 1 row [1]: <programlisting>select * from xmltable('/a' PASSING xmlparse(document '&lt;a id="1"/&gt;') COLUMNS id integer PATH '@id') x</programlisting>
-				</para>		
-        	</listitem>
-        	<listitem>
-		        <para>As a nested table: <programlisting>select x.* from t, xmltable('/x/y' PASSING t.doc COLUMNS first string, second FOR ORDINALITY) x</programlisting>
-				</para>		
-        	</listitem>
-		</itemizedlist>		
-	  </section>
-    </section>
-    	  <section id="arraytable">
-		<title>ARRAYTABLE</title>
-		<para>The ARRAYTABLE funciton processes an array input to produce tabular ouptut.  
-			The function itself defines what columns it projects.  
-		    The ARRAYTABLE function is implicitly a nested table and may be correlated to preceeding FROM clause entries.
-      	</para>
-      	<para>
-        Usage:
-        	<synopsis label="Usage">ARRAYTABLE(expression COLUMNS &lt;COLUMN&gt;, ...) AS name</synopsis>
-        	<synopsis label="Usage">COLUMN := name datatype</synopsis> 
-      	</para>
-      	<itemizedlist>
-        	<para>Parameters</para>
-        <listitem>
-          <para>expression - the array to process, which should be a java.sql.Array or java array value.
-          </para>
-        </listitem>
-      	</itemizedlist>
-      	<itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>The columns names must be not contain duplicates.
-          </para>
-        </listitem>
-        </itemizedlist>
-      	<itemizedlist>
-        	<para>Examples</para>
-        	<listitem>
-		        <para>As a nested table: <programlisting>select x.* from (call source.invokeMDX('some query')) r, arraytable(r.tuple COLUMNS first string, second bigdecimal) x</programlisting>
-				</para>		
-        	</listitem>
-		</itemizedlist>
-		<para>ARRAYTABLE is effectively a shortcut for using the <xref linkend="array_get"/> function in a nested table.  For example "ARRAYGET(val COLUMNS col1 string, col2 integer) AS X" is the same as "TABLE(SELECT cast(array_get(val, 1) AS string) AS col1, cast(array_get(val, 2) AS integer) AS col2) AS X".</para>		
-	  </section>
-    <section id="where_clause">
-      <title>WHERE Clause</title>
-      <para>
-      The WHERE clause defines the criteria to limit the records affected by SELECT, UPDATE, and DELETE statements.  
-      </para>
-      <itemizedlist>
-        <para>The general form of the WHERE is:
-        </para>
-        <listitem>
-          <para>WHERE <link linkend="criteria">criteria</link>
-          </para>
-        </listitem>
-      </itemizedlist>
-    </section>
-    <section id="groupby_clause">
-      <title>GROUP BY Clause</title>
-      <para>
-      The GROUP BY clause denotes that rows should be grouped according to the specified expression values. One row will be returned for each group, after optionally filtering those aggregate rows based on a HAVING clause.   
-      </para>
-      <itemizedlist>
-        <para>The general form of the GROUP BY is:
-        </para>
-        <listitem>
-          <para>GROUP BY expression (,expression)*
-          </para>
-        </listitem>
-      </itemizedlist>
-      <itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>Column references in the group by clause must by to unaliased output columns.
-          </para>
-        </listitem>
-        <listitem>
-          <para>Expressions used in the group by must appear in the select clause.
-          </para>
-        </listitem>
-        <listitem>
-          <para>Column references and expessions in the select clause that are not used in the group by clause must appear in aggregate functions. 
-          </para>
-        </listitem>
-        <listitem>
-          <para>If an aggregate function is used in the SELECT clause and no
-            GROUP BY is specified, an implicit GROUP BY will be performed with
-            the entire result set as a single group. In this case, every column
-            in the SELECT must be an aggregate function as no other column value
-            will be fixed across the entire group. 
-          </para>
-        </listitem>
-        <listitem>
-          <para>The group by columns must be of a comparable type.</para>
-        </listitem>
-      </itemizedlist>
-    </section>
-    <section id="having_clause">
-      <title>HAVING Clause</title>
-      <para>
-      The HAVING clause operates exactly as a WHERE clause although it operates on the output of a GROUP BY. It supports the same syntax as the WHERE clause.
-      </para>
-      <itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>Expressions used in the group by clause must either
-            contain an aggregate function: COUNT, AVG, SUM, MIN, MAX. or be one
-            of the grouping expressions.</para>
-        </listitem>
-      </itemizedlist>
-    </section>
-    <section id="orderby_clause">
-      <title>ORDER BY Clause</title>
-      <para>
-      The ORDER BY clause specifies how records should be sorted. The options are ASC (ascending) and DESC (descending).
-      </para>
-      <para>
-        Usage:
-        <synopsis label="Usage">ORDER BY expression [ASC|DESC] [NULLS (FIRST|LAST)], ...</synopsis>
-      </para>
-      <itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>Sort columns may be specified positionally by a 1-based positional
-	        integer, by SELECT clause alias name, by SELECT clause expression, or by an unrelated expression.</para>
-        </listitem>
-        <listitem>
-          <para>Column references may appear in the SELECT clause as the
-			expression for an aliased column or may reference columns from tables
-			in the FROM clause.
-			If the column reference is not in the SELECT clause the query must not
-			be a set operation, specify SELECT DISTINCT, or contain a GROUP BY
-			clause.</para>
-        </listitem>
-        <listitem>
-          <para>Unrelated expressions, expressions not appearing as an aliased expression in the select clause, 
-          are allowed in the order by clause of a non-set QUERY.  The columns referenced in the expression must come from the
-          from clause table references.  The column references cannot be to alias names or positional.
-          </para>
-        </listitem>
-        <listitem>
-          <para>The ORDER BY columns must be of a comparable type.</para>
-        </listitem>
-        <listitem>
-          <para>If an ORDER BY is used in an inline view or view
-	         definition without a limit clause, it will be removed by the Teiid
-	         optimizer.</para>
-        </listitem>
-        <listitem>
-        	<para>If NULLS FIRST/LAST is specified, then nulls are guaranteed to be sorted either first or last.  If the null ordering is not specified, then results will 
-        	typically be sorted with nulls as low values, which is Teiid's internal default sorting behavior.   
-        	However not all sources return results with nulss sorted as low values by default, and Teiid may return results with different null orderings. 
-        	</para>
-        </listitem>
-      </itemizedlist>
-      <warning>
-		<para>The use of positional ordering is no longer supported by the
-				ANSI SQL standard and is a deprecated feature in Teiid. It is
-				preferable to use alias names in the order by clause.</para>
-	  </warning>
-    </section>
-    <section id="limit_clause">
-      <title>LIMIT Clause</title>
-      <para>
-      The LIMIT clause specifies a limit on the number of records returned from the SELECT command. An optional offset (the number of rows to skip) can be specified. 
-      </para>
-      <para>
-        Usage:
-        <synopsis label="Usage">LIMIT [offset,] limit</synopsis>
-      </para>
-      <itemizedlist>
-        <para>Examples:
-        </para>
-        <listitem>
-          <para>LIMIT 100 - returns the first 100 records (rows 1-100)</para>
-        </listitem>
-        <listitem>
-          <para>LIMIT 500, 100 - skips 500 records and returns the next 100 records (rows 501-600)</para>
-        </listitem>
-      </itemizedlist>
-    </section>
-    <section id="into_clause">
-      <title>INTO Clause</title>
-      <warning>
-      	<para>Usage of the INTO Clause for inserting into a table has been been deprecated.  An <link linkend="insert_command">INSERT</link> with a query command should be used instead.</para>
-      </warning>
-      <para>
-      When the into clause is specified with a SELECT, the results of the query are inserted into the specified table. This is often used to insert records into a temporary table. The INTO clause immediately precedes the FROM clause.   
-      </para>
-      <para>
-        Usage:
-        <synopsis label="Usage">INTO table FROM ...</synopsis>
-      </para>
-      <itemizedlist>
-        <para>Syntax Rules:
-        </para>
-        <listitem>
-          <para>The INTO clause is logically applied last in processing, after the ORDER BY and LIMIT clauses.</para>
-        </listitem>
-        <listitem>
-          <para>Teiid's support for SELECT INTO is similar to
-            MS SQL Server. The target of the INTO clause is a table where
-            the result of the rest select command will be inserted. SELECT
-            INTO should not be used UNION query.</para>
-        </listitem>
-      </itemizedlist>
-    </section>    
-    <section id="option_clause">
-      <title>OPTION Clause</title>
-      <para>
-      The OPTION keyword denotes options the user can pass in with the command. These options are Teiid-specific and not covered by any SQL specification.  
-      </para>
-      <para>
-        Usage:
-        <synopsis label="Usage">OPTION option, (option)*</synopsis>
-      </para>
-      <itemizedlist>
-        <para>Supported options:
-        </para>
-        <listitem>
-          <para>MAKEDEP table [(,table)*] - specifies source tables that should be made dependent in the join
-          </para>
-        </listitem>
-        <listitem>
-          <para>MAKENOTDEP table [(,table)*] - prevents a dependent join from being used
-          </para>
-        </listitem>
-        <listitem>
-          <para>NOCACHE [table (,table)*] - prevents cache from being used for all tables or for the given tables
-          </para>
-        </listitem>
-      </itemizedlist>
-      <itemizedlist>
-        <para>Examples:
-        </para>
-        <listitem>
-          <para>OPTION MAKEDEP table1</para>
-        </listitem>
-        <listitem>
-          <para>OPTION NOCACHE</para>
-        </listitem>
-      </itemizedlist>
-      <para>All tables specified in the OPTION clause should be fully qualified.</para>
-      <note><para>Previous versions of Teiid accepted the PLANONLY, DEBUG, and SHOWPLAN option arguments.  These are no longer accepted in the OPTION clause.
-      Please see the Client Developers Guide for replacements to those options.
-      </para></note>
-    </section>
-  </section>
   <section id="set_operations">
     <title>Set Operations</title>
     <para>Teiid supports the UNION, UNION ALL, INTERSECT, EXCEPT set operation as a way of combining the results of query expressions.</para>

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/system_schema.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/system_schema.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/system_schema.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1807,6 +1807,32 @@
         <para><synopsis>SYS.getXMLSchemas(document in string) returns schema string</synopsis></para>
         </section>
         <section>
+    	<title>SYSADMIN.logMsg</title>
+    	<para>Log a message to the underlying logging system.</para>
+        <para><synopsis>SYSADMIN.logMsg(logged RETURN boolean, level IN string, context IN string, msg IN object)</synopsis></para>
+        <para>Returns true if the message was logged.  level can be one of the log4j levels: OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE.  level defaults to 'DEBUG' and context defaults to 'org.teiid.PROCESSOR'</para>
+        <example lang="sql">
+        	<title>Example logMsg</title>
+        	<programlisting>CALL SYSADMIN.logMsg(msg=>'some debug', context=>'org.something')</programlisting>
+        	<para>This will log the message 'some debug' at the default level DEBUG to the context org.something.</para>
+        </example>
+        </section>
+        <section>
+    	<title>SYSADMIN.isLoggable</title>
+    	<para>Tests if logging is enabled at the given level and context.</para>
+        <para><synopsis>SYSADMIN.isLoggable(loggable RETURN boolean, level IN string, context IN string)</synopsis></para>
+        <para>Returns true if logging is enabled.  level can be one of the log4j levels: OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE.  level defaults to 'DEBUG' and context defaults to 'org.teiid.PROCESSOR'</para>
+        <example lang="sql">
+        	<title>Example isLoggable</title>
+        	<programlisting>IF ((CALL SYSADMIN.isLoggable(context=>'org.something'))
+BEGIN
+   DECLARE STRING msg;
+   // logic to build the message ...
+   CALL SYSADMIN.logMsg(msg=>msg, context=>'org.something')
+END</programlisting>
+        </example>
+        </section>
+        <section>
     	<title>SYSADMIN.refreshMatView</title>
     	<para>Returns integer RowsUpdated. -1 indicates a load is in progress, otherwise the cardinality of the table is returned.  See the Caching Guide for more.</para>
         <para><synopsis>SYSADMIN.refreshMatView(RowsUpdated return integer, ViewName in string, Invalidate in boolean)</synopsis></para>

Modified: branches/as7/documentation/reference/src/main/docbook/en-US/content/translators.xml
===================================================================
--- branches/as7/documentation/reference/src/main/docbook/en-US/content/translators.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/documentation/reference/src/main/docbook/en-US/content/translators.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -162,40 +162,46 @@
                             <entry>The encoding that should be used for CLOBs returned by the getTextFiles procedure</entry>
                             <entry>The system default encoding</entry>
                         </row>
+                        <row>
+                            <entry>ExceptionIfFileNotFound</entry>
+                            <entry>Throw an exception in getFiles or getTextFiles if the specified file/directory does not exist.</entry>
+                            <entry>false</entry>
+                        </row>
                     </tbody>
                 </tgroup>
             </table>
             
-            <para>There are file importer settings, but it does provide metadata for dynamic vdbs.</para>
-            
             <section>
                 <title>Usage</title>
                 <para>
-                Retrieve all files as BLOBs with the given extension at the given path.
+                Retrieve all files as BLOBs with an optional extension at the given path.
                 </para>
                 
                 <programlisting>call getFiles('path/*.ext')</programlisting>
                 
                 <para>
+                If the extension path is specified, then it will filter all of the file in the directory referenced by the base path. 
                 If the extension pattern is not specified and the path is a directory, 
-                then all files in the directory will be returned.  If the path or filename 
-                doesn't exist, then no results will be returned.
+                then all files in the directory will be returned.  Otherwise the single file referenced will be returned.  If the path 
+                doesn't exist, then no results will be returned if ExceptionIfFileNotFound is false, otherwise an exception will be raised.
                 </para>
                 
                 <para>
-                Retrieve all files as CLOBs with the given extension at the given path.
+                Retrieve all files as CLOB(s) with the an optional extension at the given path.
                 </para>
                 <programlisting>call getTextFiles('path/*.ext')</programlisting>
                 
                 <para>
-                Save the CLOB, BLOB, or XML file to given path
+                All the same files a getFiles will be retrieved, the only difference is that
+                the results will be CLOB values using the encoding execution property as the character set. 
                 </para>
-                <programlisting>call saveFile('path', value)</programlisting>
                 
                 <para>
-                See the database metadata for full descriptions of the getFiles, 
-                getTextFiles, and saveFile procedures.
+                Save the CLOB, BLOB, or XML value to given path
                 </para>
+                <programlisting>call saveFile('path', value)</programlisting>
+                
+                <para>The path should reference a new file location or an existing file to overwrite completely.</para>
             </section>
             
             <section>
@@ -467,6 +473,12 @@
                         <entry>true will allow the import of overloaded procedures (which will normally result in a duplicate procedure error) by using the unique procedure specific name as the Teiid name.  This option will only work with JDBC 4.0 compatable drivers that report specific names.</entry>
                         <entry>false</entry>
                     </row>
+                    <row>
+                        <entry>useCatalogName</entry>
+                        <entry>true will use any non-null/non-empty catalog name as part of the name in source, e.g. "catalog"."table"."column", and in the Teiid runtime name if useFullSchemaName is true.  
+                        false will not use the catalog name in either the name in source or the Teiid runtime name.  Should be set to false for sources that do not fully support a catalog concept, but return a non-null catalog name in their metadata - such as HSQL.</entry>
+                        <entry>true</entry>
+                    </row>
                 </tbody>
             </tgroup>
         </table>
@@ -538,6 +550,11 @@
                         <entry>Restrict Searches to objectClass named in the Name field for a table</entry>
                         <entry>false</entry>
                     </row>
+                    <row>
+                    	<entry>UsePagination</entry>
+                        <entry>Use a PagedResultsControl to page through large results.  This is not supported by all directory servers.</entry>
+                        <entry>false</entry>
+                    </row>
                 </tbody>
             </tgroup>
         </table>

Modified: branches/as7/engine/pom.xml
===================================================================
--- branches/as7/engine/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,14 +1,14 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-    <parent>
-        <artifactId>teiid-parent</artifactId>
-        <groupId>org.jboss.teiid</groupId>
-        <version>7.5.0.Alpha1-SNAPSHOT</version>
-    </parent>
-    <modelVersion>4.0.0</modelVersion>
-    <artifactId>teiid-engine</artifactId>
-    <name>Engine</name>
-    <description>Relational, procedural, and xml core engine.</description>
+	<parent>
+		<artifactId>teiid-parent</artifactId>
+		<groupId>org.jboss.teiid</groupId>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
+	</parent>
+	<modelVersion>4.0.0</modelVersion>
+	<artifactId>teiid-engine</artifactId>
+	<name>Engine</name>
+	<description>Relational, procedural, and xml core engine.</description>
 
     <build>
         <plugins>
@@ -83,22 +83,33 @@
 			<scope>provided</scope>
 		</dependency>
          -->
-        <dependency>
-            <groupId>net.sourceforge.saxon</groupId>
-            <artifactId>saxon</artifactId>
+		<dependency>
+			<groupId>net.sourceforge.saxon</groupId>
+			<artifactId>saxonhe</artifactId>
+		</dependency>
+		<dependency>
+			<groupId>com.googlecode.json-simple</groupId>
+			<artifactId>json-simple</artifactId>
+		</dependency>
+		
+		<dependency>
+            <groupId>nux</groupId>
+            <artifactId>nux</artifactId>
+            <version>1.6</version>
         </dependency>
 
         <dependency>
-            <groupId>net.sourceforge.saxon</groupId>
-            <classifier>dom</classifier>
-            <artifactId>saxon</artifactId>
+            <groupId>xom</groupId>
+            <artifactId>xom</artifactId>
+            <version>1.2</version>
         </dependency>
-
+        
         <dependency>
-            <groupId>com.googlecode.json-simple</groupId>
-            <artifactId>json-simple</artifactId>
+            <groupId>org.jboss.logging</groupId>
+            <artifactId>jboss-logging</artifactId>
+            <scope>test</scope>        
         </dependency>
 
-    </dependencies>
+	</dependencies>
 
-</project>
\ No newline at end of file
+</project>

Modified: branches/as7/engine/src/main/java/org/teiid/api/exception/query/QueryParserException.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/api/exception/query/QueryParserException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/api/exception/query/QueryParserException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,12 +22,16 @@
 
 package org.teiid.api.exception.query;
 
+import org.teiid.query.parser.ParseException;
 
+
 /**
  * Thrown when a query cannot be parsed.  This is most likely due to not 
  * following the Query Parser grammar, which defines how queries are parsed.
  */
 public class QueryParserException extends QueryProcessingException {
+	
+	private ParseException parseException;
 
     /**
      * No-arg constructor required by Externalizable semantics.
@@ -76,4 +80,12 @@
     public QueryParserException( Throwable e, String code, String message ) {
         super( e, code, message );
     }
+    
+    public ParseException getParseException() {
+		return parseException;
+	}
+    
+    public void setParseException(ParseException parseException) {
+		this.parseException = parseException;
+	}
 }

Modified: branches/as7/engine/src/main/java/org/teiid/common/buffer/BlockedException.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/common/buffer/BlockedException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/common/buffer/BlockedException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,6 +23,9 @@
 package org.teiid.common.buffer;
 
 import org.teiid.core.TeiidComponentException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
 
 /**
  * This exception is thrown if the buffer manager blocks waiting on input during
@@ -40,4 +43,11 @@
         super();
     }
     
+    public static BlockedException block(Object... msg) {
+    	if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
+    		LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, msg);
+    	}
+    	return INSTANCE;
+    }
+    
 }


Property changes on: branches/as7/engine/src/main/java/org/teiid/common/buffer/BlockedException.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/common/buffer/BlockedException.java:3149-3217
/trunk/engine/src/main/java/org/teiid/common/buffer/BlockedException.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/common/buffer/BufferManager.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/common/buffer/BufferManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/common/buffer/BufferManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -67,8 +67,8 @@
 
 	public static int DEFAULT_CONNECTOR_BATCH_SIZE = 1024;
 	public static int DEFAULT_PROCESSOR_BATCH_SIZE = 512;
-	public static int DEFAULT_MAX_PROCESSING_BATCHES = -1;
-	public static int DEFAULT_RESERVE_BUFFERS = -1;
+	public static int DEFAULT_MAX_PROCESSING_KB = -1;
+	public static int DEFAULT_RESERVE_BUFFER_KB = -1;
 	
     /**
      * Get the batch size to use during query processing.  


Property changes on: branches/as7/engine/src/main/java/org/teiid/common/buffer/BufferManager.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/common/buffer/BufferManager.java:3220-3275
/trunk/engine/src/main/java/org/teiid/common/buffer/BufferManager.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/common/buffer/STree.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/common/buffer/STree.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/common/buffer/STree.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -169,6 +169,10 @@
 		return null;
 	}
 	
+	public List find(List n) throws TeiidComponentException {
+		return find(n, new LinkedList<SearchResult>());
+	}
+	
 	public List insert(List tuple, InsertMode mode, int sizeHint) throws TeiidComponentException {
 		LinkedList<SearchResult> places = new LinkedList<SearchResult>();
 		List match = null;

Modified: branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBatch.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBatch.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBatch.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -156,6 +156,10 @@
         this.types = types;
     }
     
+    public String[] getDataTypes() {
+		return types;
+	}
+    
     public boolean containsRow(int row) {
     	return rowOffset <= row && getEndRow() >= row;
     }


Property changes on: branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBatch.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/common/buffer/TupleBatch.java:3220-3275
/trunk/engine/src/main/java/org/teiid/common/buffer/TupleBatch.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -48,13 +48,13 @@
      * @return
      * @since 4.2
      */
-    public static String[] getTypeNames(List expressions) {
+    public static String[] getTypeNames(List<? extends Expression> expressions) {
     	if (expressions == null) {
     		return null;
     	}
         String[] types = new String[expressions.size()];
-        for (ListIterator i = expressions.listIterator(); i.hasNext();) {
-            Expression expr = (Expression)i.next();
+        for (ListIterator<? extends Expression> i = expressions.listIterator(); i.hasNext();) {
+            Expression expr = i.next();
             types[i.previousIndex()] = DataTypeManager.getDataTypeName(expr.getType());
         }
         return types;
@@ -63,7 +63,7 @@
 	//construction state
 	private BatchManager manager;
 	private String tupleSourceID;
-	private List<?> schema;
+	private List<? extends Expression> schema;
 	private String[] types;
 	private int batchSize;
 	
@@ -80,7 +80,7 @@
 	private String uuid;
 	private FileStore lobStore;
 	
-	public TupleBuffer(BatchManager manager, String id, List<?> schema, int[] lobIndexes, int batchSize) {
+	public TupleBuffer(BatchManager manager, String id, List<? extends Expression> schema, int[] lobIndexes, int batchSize) {
 		this.manager = manager;
 		this.tupleSourceID = id;
 		this.schema = schema;
@@ -99,8 +99,12 @@
 			this.uuid = java.util.UUID.randomUUID().toString();
 		}
 		return this.uuid;
-	}	
+	}
 	
+	public void setId(String uuid) {
+		this.uuid = uuid;
+	}
+	
 	public boolean isLobs() {
 		return lobIndexes != null;
 	}
@@ -276,7 +280,7 @@
 		this.isFinal = isFinal;
 	}
 	
-	public List<?> getSchema() {
+	public List<? extends Expression> getSchema() {
 		return schema;
 	}
 	
@@ -318,7 +322,7 @@
 				if(isFinal) {
 		            return null;
 		        } 
-		        throw BlockedException.INSTANCE;
+		        throw BlockedException.block("Blocking on non-final TupleBuffer", tupleSourceID); //$NON-NLS-1$
 			}
 			
 			@Override
@@ -365,4 +369,8 @@
 		return prefersMemory;
 	}
 	
+	public String[] getTypes() {
+		return types;
+	}
+	
 }


Property changes on: branches/as7/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java:3149-3217,3220-3275,3340-3349
/trunk/engine/src/main/java/org/teiid/common/buffer/TupleBuffer.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/BufferManagerImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,6 +33,7 @@
 import java.lang.ref.SoftReference;
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.Iterator;
@@ -64,6 +65,7 @@
 import org.teiid.dqp.internal.process.DQPConfiguration;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.processor.relational.ListNestedSortComparator;
 import org.teiid.query.sql.symbol.Expression;
@@ -87,25 +89,24 @@
  */
 public class BufferManagerImpl implements BufferManager, StorageManager {
 	
-	public static final double KB_PER_VALUE = 64d/1024;
 	private static final int IO_BUFFER_SIZE = 1 << 14;
 	private static final int COMPACTION_THRESHOLD = 1 << 25; //start checking at 32 megs
 	
 	private final class BatchManagerImpl implements BatchManager {
 		private final String id;
-		private final int columnCount;
 		private volatile FileStore store;
 		private Map<Long, long[]> physicalMapping = new ConcurrentHashMap<Long, long[]>();
 		private ReadWriteLock compactionLock = new ReentrantReadWriteLock();
 		private AtomicLong unusedSpace = new AtomicLong();
 		private int[] lobIndexes;
+		private SizeUtility sizeUtility;
 
-		private BatchManagerImpl(String newID, int columnCount, int[] lobIndexes) {
+		private BatchManagerImpl(String newID, int[] lobIndexes) {
 			this.id = newID;
-			this.columnCount = columnCount;
 			this.store = createFileStore(id);
 			this.store.setCleanupReference(this);
 			this.lobIndexes = lobIndexes;
+			this.sizeUtility = new SizeUtility();
 		}
 		
 		public FileStore createStorage(String prefix) {
@@ -185,7 +186,7 @@
 		ManagedBatchImpl removeBatch(int row) {
 			ManagedBatchImpl result = batches.remove(row);
 			if (result != null) {
-				activeBatchColumnCount -= result.batchManager.columnCount;
+				activeBatchKB -= result.sizeEstimate;
 			}
 			return result;
 		}
@@ -200,17 +201,19 @@
 		private BatchManagerImpl batchManager;
 		private long id;
 		private LobManager lobManager;
+		private int sizeEstimate;
 		
 		public ManagedBatchImpl(TupleBatch batch, BatchManagerImpl manager, boolean softCache) {
 			this.softCache = softCache;
 			id = batchAdded.incrementAndGet();
-            LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Add batch to BufferManager", id); //$NON-NLS-1$
 			this.activeBatch = batch;
 			this.beginRow = batch.getBeginRow();
 			this.batchManager = manager;
 			if (this.batchManager.lobIndexes != null) {
 				this.lobManager = new LobManager();
 			}
+			sizeEstimate = (int) Math.max(1, manager.sizeUtility.getBatchSize(batch) / 1024);
+            LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Add batch to BufferManager", id, "with size estimate", sizeEstimate); //$NON-NLS-1$ //$NON-NLS-2$
 		}
 		
 		@Override
@@ -225,7 +228,7 @@
 				if (batch == null) {
 					return; //already removed
 				}
-				activeBatchColumnCount += batchManager.columnCount;
+				activeBatchKB += sizeEstimate;
 				TupleBufferInfo tbi = null;
 				if (update) {
 					tbi = activeBatches.remove(batchManager.id);
@@ -287,6 +290,7 @@
 				try {
 					this.batchManager.compactionLock.readLock().lock();
 					long[] info = batchManager.physicalMapping.get(this.id);
+					Assertion.isNotNull(info, "Invalid batch " + id); //$NON-NLS-1$
 					ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(batchManager.store.createInputStream(info[0]), IO_BUFFER_SIZE));
 		            batch = new TupleBatch();
 		            batch.setDataTypes(types);
@@ -341,7 +345,7 @@
 					}
 					if (softCache) {
 						this.batchReference = new SoftReference<TupleBatch>(batch);
-					} else {
+					} else if (useWeakReferences) {
 						this.batchReference = new WeakReference<TupleBatch>(batch);
 					}
 				}
@@ -385,22 +389,21 @@
     private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
     private int processorBatchSize = BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE;
     //set to acceptable defaults for testing
-    private int maxProcessingBatches = 128;
-    private int maxReserveBatchColumns = 16384; 
-    private int maxProcessingKB;
-    private int maxReserveBatchKB;
+    private int maxProcessingKB = 1 << 11; 
+    private Integer maxProcessingKBOrig;
+    private int maxReserveKB = 1 << 25;
     private volatile int reserveBatchKB;
     private int maxActivePlans = DQPConfiguration.DEFAULT_MAX_ACTIVE_PLANS; //used as a hint to set the reserveBatchKB
+    private boolean useWeakReferences = true;
 
     private ReentrantLock lock = new ReentrantLock(true);
     private Condition batchesFreed = lock.newCondition();
     
-    private volatile int activeBatchColumnCount = 0;
+    private volatile int activeBatchKB = 0;
     private Map<String, TupleBufferInfo> activeBatches = new LinkedHashMap<String, TupleBufferInfo>();
 	private Map<String, TupleReference> tupleBufferMap = new ConcurrentHashMap<String, TupleReference>();
 	private ReferenceQueue<TupleBuffer> tupleBufferQueue = new ReferenceQueue<TupleBuffer>();
     
-    
     private StorageManager diskMgr;
 
     private AtomicLong tsId = new AtomicLong();
@@ -431,10 +434,6 @@
 		return maxProcessingKB;
 	}
     
-    public void setMaxProcessingBatchColumns(int maxProcessingBatches) {
-		this.maxProcessingBatches = maxProcessingBatches;
-	}
-
     /**
      * Get processor batch size
      * @return Number of rows in a processor batch
@@ -480,17 +479,19 @@
     		TupleSourceType tupleSourceType) {
     	final String newID = String.valueOf(this.tsId.getAndIncrement());
     	int[] lobIndexes = LobManager.getLobIndexes(elements);
-    	BatchManager batchManager = new BatchManagerImpl(newID, elements.size(), lobIndexes);
+    	BatchManager batchManager = new BatchManagerImpl(newID, lobIndexes);
         TupleBuffer tupleBuffer = new TupleBuffer(batchManager, newID, elements, lobIndexes, getProcessorBatchSize());
-        LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating TupleBuffer:", newID, "of type ", tupleSourceType); //$NON-NLS-1$ //$NON-NLS-2$
+        if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.DETAIL)) {
+        	LogManager.logDetail(LogConstants.CTX_BUFFER_MGR, "Creating TupleBuffer:", newID, elements, Arrays.toString(tupleBuffer.getTypes()), "of type", tupleSourceType); //$NON-NLS-1$ //$NON-NLS-2$
+        }
         return tupleBuffer;
     }
     
     public STree createSTree(final List elements, String groupName, int keyLength) {
     	String newID = String.valueOf(this.tsId.getAndIncrement());
     	int[] lobIndexes = LobManager.getLobIndexes(elements);
-    	BatchManager bm = new BatchManagerImpl(newID, elements.size(), lobIndexes);
-    	BatchManager keyManager = new BatchManagerImpl(String.valueOf(this.tsId.getAndIncrement()), keyLength, null);
+    	BatchManager bm = new BatchManagerImpl(newID, lobIndexes);
+    	BatchManager keyManager = new BatchManagerImpl(String.valueOf(this.tsId.getAndIncrement()), null);
     	int[] compareIndexes = new int[keyLength];
     	for (int i = 1; i < compareIndexes.length; i++) {
 			compareIndexes[i] = i;
@@ -509,27 +510,35 @@
 		this.maxActivePlans = maxActivePlans;
 	}
     
+    public void setMaxProcessingKB(int maxProcessingKB) {
+		this.maxProcessingKB = maxProcessingKB;
+	}
+    
+    public void setMaxReserveKB(int maxReserveBatchKB) {
+		this.maxReserveKB = maxReserveBatchKB;
+	}
+    
 	@Override
 	public void initialize() throws TeiidComponentException {
 		int maxMemory = (int)Math.min(Runtime.getRuntime().maxMemory() / 1024, Integer.MAX_VALUE);
 		maxMemory -= 300 * 1024; //assume 300 megs of overhead for the AS/system stuff
-		if (maxReserveBatchColumns < 0) {
-			this.maxReserveBatchKB = 0;
+		if (maxReserveKB < 0) {
+			this.maxReserveKB = 0;
 			int one_gig = 1024 * 1024;
 			if (maxMemory > one_gig) {
 				//assume 75% of the memory over the first gig
-				this.maxReserveBatchKB += (int)Math.max(0, (maxMemory - one_gig) * .75);
+				this.maxReserveKB += (int)Math.max(0, (maxMemory - one_gig) * .75);
 			}
-			this.maxReserveBatchKB += Math.max(0, Math.min(one_gig, maxMemory) * .5);
-    	} else {
-    		this.maxReserveBatchKB = Math.max(0, (int)Math.min(maxReserveBatchColumns * KB_PER_VALUE * processorBatchSize, Integer.MAX_VALUE));
+			this.maxReserveKB += Math.max(0, Math.min(one_gig, maxMemory) * .5);
     	}
-		this.reserveBatchKB = this.maxReserveBatchKB;
-		if (this.maxProcessingBatches < 0) {
-			this.maxProcessingKB = Math.max((int)Math.min(128 * KB_PER_VALUE * processorBatchSize, Integer.MAX_VALUE), (int)(.1 * maxMemory)/maxActivePlans);
-		} else {
-			this.maxProcessingKB = Math.max(0, (int)Math.min(Math.ceil(maxProcessingBatches * KB_PER_VALUE * processorBatchSize), Integer.MAX_VALUE));
+		this.reserveBatchKB = this.maxReserveKB;
+		if (this.maxProcessingKBOrig == null) {
+			//store the config value so that we can be reinitialized (this is not a clean approach)
+			this.maxProcessingKBOrig = this.maxProcessingKB;
 		}
+		if (this.maxProcessingKBOrig < 0) {
+			this.maxProcessingKB = Math.max(Math.min(8 * processorBatchSize, Integer.MAX_VALUE), (int)(.1 * maxMemory)/maxActivePlans);
+		} 
 	}
 	
     @Override
@@ -537,6 +546,9 @@
     	if (count < 1) {
     		return;
     	}
+    	if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.TRACE)) {
+    		LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Releasing buffer space", count); //$NON-NLS-1$
+    	}
     	lock.lock();
     	try {
 	    	this.reserveBatchKB += count;
@@ -548,11 +560,14 @@
     
     @Override
     public int reserveBuffers(int count, BufferReserveMode mode) {
+    	if (LogManager.isMessageToBeRecorded(LogConstants.CTX_BUFFER_MGR, MessageLevel.TRACE)) {
+    		LogManager.logTrace(LogConstants.CTX_BUFFER_MGR, "Reserving buffer space", count, mode); //$NON-NLS-1$
+    	}
     	lock.lock();
 	    try {
 	    	if (mode == BufferReserveMode.WAIT) {
 	    		//don't wait for more than is available
-	    		int waitCount = Math.min(count, this.maxReserveBatchKB);
+	    		int waitCount = Math.min(count, this.maxReserveKB);
 		    	while (waitCount > 0 && waitCount > this.reserveBatchKB) {
 		    		try {
 						batchesFreed.await(100, TimeUnit.MILLISECONDS);
@@ -576,13 +591,13 @@
     }
     
 	void persistBatchReferences() {
-		if (activeBatchColumnCount == 0 || activeBatchColumnCount <= reserveBatchKB) {
-			int memoryCount = activeBatchColumnCount + maxReserveBatchColumns - reserveBatchKB;
+		if (activeBatchKB == 0 || activeBatchKB <= reserveBatchKB) {
+    		int memoryCount = activeBatchKB + maxReserveKB - reserveBatchKB;
 			if (DataTypeManager.isValueCacheEnabled()) {
-				if (memoryCount < maxReserveBatchColumns / 8) {
+    			if (memoryCount < maxReserveKB / 8) {
 					DataTypeManager.setValueCacheEnabled(false);
 				}
-			} else if (memoryCount > maxReserveBatchColumns / 4) {
+			} else if (memoryCount > maxReserveKB / 4) {
 				DataTypeManager.setValueCacheEnabled(true);
 			}
 			return;
@@ -590,7 +605,7 @@
 		while (true) {
 			ManagedBatchImpl mb = null;
 			synchronized (activeBatches) {
-				if (activeBatchColumnCount == 0 || activeBatchColumnCount * 5 < reserveBatchKB * 4) {
+				if (activeBatchKB == 0 || activeBatchKB < reserveBatchKB * .8) {
 					break;
 				}
 				Iterator<TupleBufferInfo> iter = activeBatches.values().iterator();
@@ -624,43 +639,12 @@
 		//this includes alignment, row/array, and reference overhead
 		for (Expression element : elements) {
 			Class<?> type = element.getType();
-			if (type == DataTypeManager.DefaultDataClasses.STRING) {
-				total += isValueCacheEnabled?100:256; //assumes an "average" string length of approximately 100 chars
-			} else if (type == DataTypeManager.DefaultDataClasses.DATE 
-					|| type == DataTypeManager.DefaultDataClasses.TIME 
-					|| type == DataTypeManager.DefaultDataClasses.TIMESTAMP) {
-				total += isValueCacheEnabled?20:28;
-			} else if (type == DataTypeManager.DefaultDataClasses.LONG 
-					|| type	 == DataTypeManager.DefaultDataClasses.DOUBLE) {
-				total += isValueCacheEnabled?12:16;
-			} else if (type == DataTypeManager.DefaultDataClasses.INTEGER 
-					|| type == DataTypeManager.DefaultDataClasses.FLOAT) {
-				total += isValueCacheEnabled?6:12;
-			} else if (type == DataTypeManager.DefaultDataClasses.CHAR 
-					|| type == DataTypeManager.DefaultDataClasses.SHORT) {
-				total += isValueCacheEnabled?4:10;
-			} else if (type == DataTypeManager.DefaultDataClasses.OBJECT) {
-				total += 1024;
-			} else if (type == DataTypeManager.DefaultDataClasses.NULL) {
-				//it's free
-			} else if (type == DataTypeManager.DefaultDataClasses.BYTE) {
-				total += 2; //always value cached
-			} else if (type == DataTypeManager.DefaultDataClasses.BOOLEAN) {
-				total += 1; //always value cached
-			} else {
-				total += 512; //assumes buffer overhead in the case of lobs
-				//however the account for lobs is misleading as the lob
-				//references are not actually removed from memory
-			}
+			total += SizeUtility.getSize(isValueCacheEnabled, type);
 		}
 		total += 8*elements.size() + 36;  // column list / row overhead
 		total *= processorBatchSize; 
 		return Math.max(1, total / 1024);
 	}
-	
-    public void setMaxReserveBatchColumns(int maxReserve) {
-    	this.maxReserveBatchColumns = maxReserve;
-	}
 
 	public void shutdown() {
 	}
@@ -698,4 +682,9 @@
 			id = referent.getId();
 		}
 	}
+	
+	public void setUseWeakReferences(boolean useWeakReferences) {
+		this.useWeakReferences = useWeakReferences;
+	}
+	
 }

Copied: branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/SizeUtility.java (from rev 3382, trunk/engine/src/main/java/org/teiid/common/buffer/impl/SizeUtility.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/SizeUtility.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/common/buffer/impl/SizeUtility.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,205 @@
+/*
+ * 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 org.teiid.common.buffer.impl;
+
+import java.lang.reflect.Array;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.core.types.DataTypeManager;
+
+
+/**
+ * Utility methods to determine the size of Java objects, particularly with 
+ * respect to the Teiid runtime types.
+ * 
+ * The sizes are loosely based on expected heap size and are generally optimistic.
+ * Actual object allocation efficiency can be quite poor.  
+ */
+public final class SizeUtility {
+	public static final int REFERENCE_SIZE = 8;
+	
+	private long bigIntegerEstimate;
+	private long bigDecimalEstimate;
+	
+	public SizeUtility() {
+		boolean isValueCacheEnabled = DataTypeManager.isValueCacheEnabled();
+		bigIntegerEstimate = getSize(isValueCacheEnabled, DataTypeManager.DefaultDataClasses.BIG_INTEGER);
+		bigDecimalEstimate = getSize(isValueCacheEnabled, DataTypeManager.DefaultDataClasses.BIG_DECIMAL);
+	}
+	
+    public long getBatchSize(TupleBatch data) {
+    	return getBatchSize(DataTypeManager.isValueCacheEnabled(), data);
+    }
+	
+    private long getBatchSize(boolean accountForValueCache, TupleBatch data) {
+        int colLength = data.getDataTypes().length;
+        int rowLength = data.getRowCount();
+    
+        // Array overhead for row array
+        long size = 16 + alignMemory(rowLength * REFERENCE_SIZE); 
+        // array overhead for all the columns ( 8 object overhead + 4 ref + 4 int)
+        size += (rowLength * (48 + alignMemory(colLength * REFERENCE_SIZE))); 
+        for (int col = 0; col < colLength; col++) {
+            Class<?> type = DataTypeManager.getDataTypeClass(data.getDataTypes()[col]);
+                        
+            if (type == DataTypeManager.DefaultDataClasses.STRING 
+            		|| type == DataTypeManager.DefaultDataClasses.OBJECT
+            		|| type == DataTypeManager.DefaultDataClasses.BIG_INTEGER
+            		|| type == DataTypeManager.DefaultDataClasses.BIG_DECIMAL) {
+            	int estRow = 0;
+                for (int row = 0; row < rowLength; row++) {
+                	boolean updateEst = row == estRow;
+                    size += getSize(data.getTuples().get(row).get(col), updateEst, accountForValueCache);
+                    if (updateEst) {
+                    	estRow = estRow * 2 + 1;
+                    }
+                }
+            } else {
+            	size += getSize(accountForValueCache, type) * rowLength;
+            }
+        }
+        return size;
+    }
+    
+    static int getSize(boolean isValueCacheEnabled,
+			Class<?> type) {
+		if (type == DataTypeManager.DefaultDataClasses.STRING) {
+			return isValueCacheEnabled?100:256; //assumes an "average" string length of approximately 100 chars
+		} else if (type == DataTypeManager.DefaultDataClasses.DATE 
+				|| type == DataTypeManager.DefaultDataClasses.TIME 
+				|| type == DataTypeManager.DefaultDataClasses.TIMESTAMP) {
+			return isValueCacheEnabled?20:28;
+		} else if (type == DataTypeManager.DefaultDataClasses.LONG 
+				|| type	 == DataTypeManager.DefaultDataClasses.DOUBLE) {
+			return isValueCacheEnabled?12:16;
+		} else if (type == DataTypeManager.DefaultDataClasses.INTEGER 
+				|| type == DataTypeManager.DefaultDataClasses.FLOAT) {
+			return isValueCacheEnabled?6:12;
+		} else if (type == DataTypeManager.DefaultDataClasses.CHAR 
+				|| type == DataTypeManager.DefaultDataClasses.SHORT) {
+			return isValueCacheEnabled?4:10;
+		} else if (type == DataTypeManager.DefaultDataClasses.OBJECT) {
+			return 1024;
+		} else if (type == DataTypeManager.DefaultDataClasses.NULL) {
+			return 0; //it's free
+		} else if (type == DataTypeManager.DefaultDataClasses.BYTE
+				|| type == DataTypeManager.DefaultDataClasses.BOOLEAN) {
+			return 1; //should always be value cached, but there's a small chance it's not
+		} else if (type == DataTypeManager.DefaultDataClasses.BIG_INTEGER){
+			return isValueCacheEnabled?75:100;
+		} else if (type == DataTypeManager.DefaultDataClasses.BIG_DECIMAL) {
+		 	return isValueCacheEnabled?150:200;
+		}
+		return 512; //assumes buffer overhead in the case of lobs
+		//however the account for lobs is misleading as the lob
+		//references are not actually removed from memory
+	}
+    
+    /**
+     * Get size of object
+     * @return Size in bytes
+     */
+    protected long getSize(Object obj, boolean updateEstimate, boolean accountForValueCache) {
+        if(obj == null) {
+            return 0;
+        }
+
+        Class<?> type = DataTypeManager.determineDataTypeClass(obj);
+        if(type == DataTypeManager.DefaultDataClasses.STRING) {
+            int length = ((String)obj).length();
+            if (length > 0) {
+                return alignMemory(40 + (2 * length));
+            }
+            return 40;
+        } else if(obj instanceof Iterable<?>) {
+        	Iterable<?> i = (Iterable<?>)obj;
+        	long total = 16;
+        	for (Object object : i) {
+				total += getSize(object, true, false) + REFERENCE_SIZE;
+			}
+        	return total;
+        } else if(type == DataTypeManager.DefaultDataClasses.BIG_DECIMAL) {
+        	if (!updateEstimate) {
+        		return bigDecimalEstimate;
+        	}
+            int bitLength = ((BigDecimal)obj).unscaledValue().bitLength();
+            //TODO: this does not account for the possibility of a cached string
+            long result = 88 + alignMemory(4 + (bitLength >> 3));
+            if (updateEstimate) {
+            	bigDecimalEstimate = (bigDecimalEstimate + result)/2;
+            }
+            return result;
+        } else if(type == DataTypeManager.DefaultDataClasses.BIG_INTEGER) {
+        	if (!updateEstimate) {
+        		return bigIntegerEstimate;
+        	}
+            int bitLength = ((BigInteger)obj).bitLength();
+            long result = 40 + alignMemory(4 + (bitLength >> 3));
+            if (updateEstimate) {
+            	bigIntegerEstimate = (bigIntegerEstimate + result)/2;
+            }
+            return result;
+        } else if(obj.getClass().isArray()) {
+        	Class<?> componentType = obj.getClass().getComponentType(); 
+        	if (!componentType.isPrimitive()) {
+	            Object[] rows = (Object[]) obj;
+	            long total = 16 + alignMemory(rows.length * REFERENCE_SIZE); // Array overhead
+	            for(int i=0; i<rows.length; i++) {
+	                total += getSize(rows[i], true, false);
+	            }
+	            return total;
+        	}
+        	int length = Array.getLength(obj);
+        	int primitiveSize = 8;
+        	if (componentType == boolean.class) {
+        		primitiveSize = 4;
+        	} else if (componentType == byte.class) {
+        		primitiveSize = 1;
+        	} else if (componentType == short.class) {
+        		primitiveSize = 2;
+        	} else if (componentType == int.class || componentType == float.class) {
+        		primitiveSize = 4;
+        	}
+        	return alignMemory(length * primitiveSize) + 16;
+        }        	
+		return getSize(accountForValueCache, type);
+    }
+    
+    /**
+     * Most current VMs have memory alignment that places objects into heap space that is a multiple of 8 Bytes.
+     * This utility method helps with calculating the aligned size of an object.
+     * @param numBytes
+     * @return
+     * @since 4.2
+     */
+    private static long alignMemory(long numBytes) {
+        long remainder = numBytes % 8;
+        if (remainder != 0) {
+            numBytes += (8 - remainder);
+        }
+        return numBytes;
+    }
+    
+}
\ No newline at end of file

Modified: branches/as7/engine/src/main/java/org/teiid/core/id/IDGenerator.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/IDGenerator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/IDGenerator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,306 +22,17 @@
 
 package org.teiid.core.id;
 
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
 
-import org.teiid.core.CorePlugin;
-
-
 /**
  * IDGenerator
  */
 public class IDGenerator {
     
-    private static final IDGenerator INSTANCE = new IDGenerator();
-
-    /**
-     * Obtain the shared instance of this class.
-     * @return the statically shared instance of this class.
-     */
-    public static IDGenerator getInstance() {
-        return INSTANCE;
-    }
-
-    /** ObjectIDFactory instances keyed by protocol */
-    private final Map factories;
-    private final Set protocols;
+	private int id;
+	
+	public int nextInt() {
+		return id++;
+	}
     
-    private ObjectIDFactory defaultFactory;
-
-    public IDGenerator() {
-        this.factories = new HashMap();
-        this.protocols = new HashSet();
-        
-        // Initialize default factory ...
-        final ObjectIDFactory newDefaultFactory = new UUIDFactory();
-        addFactory( newDefaultFactory );
-        if ( !this.hasDefaultFactory() ) {
-            this.setDefaultFactory(newDefaultFactory);
-        }
-    }
-    
-    /**
-     * Method that creates and adds to this generator all the built-in factories, and if there is no default
-     * factory, set the default factory to the {@link UUIDFactory}. 
-     * This method may be called multiple times without side effect.
-     */
-    public void addBuiltInFactories() {
-        // Add the UUID factory as the default ...
-        final ObjectIDFactory newDefaultFactory = new UUIDFactory();
-        addFactory( newDefaultFactory );
-        if ( !this.hasDefaultFactory() ) {
-            this.setDefaultFactory(newDefaultFactory);
-        }
-        addFactory( new IntegerIDFactory() );
-        addFactory( new LongIDFactory() );
-        addFactory( new StringIDFactory() );
-    }
-    
-    /**
-     * Supply to this generator a new factory for a type of {@link ObjectID}.
-     * This method has no effect if the factory is null, or if this generator already knows
-     * about the factory.
-     * @param factory the new factory
-     */
-    public void addFactory( final ObjectIDFactory factory ) {
-        if ( factory == null ) {
-            return;
-        }
-        final String protocol = factory.getProtocol();
-        
-        // See if the factory is already known ...
-        if ( !this.factories.containsKey(protocol) ) {
-            this.factories.put(protocol,factory);
-        }
-        this.protocols.add(protocol);
-    }
-    
-    /**
-     * Remove a factory from this generator.
-     * This method has no effect if the supplied protocol doesn't match the protocol of any descriptor
-     * known to this generator.
-     * @param protocol the protocol for which the factory is to be removed
-     * @return whether a factory was found and removed for the supplied protocol
-     */
-    public boolean removeFactory(String protocol) {
-        if ( protocol == null ) {
-            return false;
-        }
-        final Object previous = this.factories.remove(protocol);
-        if ( previous != null ) {
-            this.protocols.remove(protocol);
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Method to obtain the collection of {@link ObjectIDFactory} instances that each describe
-     * one of the types of {@link ObjectID}s that are available to this generator.
-     * @return the collection of {@link ObjectIDFactory} instances.
-     */
-    public Collection getFactories() {
-        // Currently, we get the collection of values from the 'factories' map.  This is okay,
-        // because although not terribly efficient, this method is not intended to be called very
-        // frequently
-        return factories.values();
-    }
-    
-    /**
-     * Method to obtain the collection of {@link ObjectIDFactory} instances that each describe
-     * one of the types of {@link ObjectID}s that are available to this generator.
-     * @return the collection of {@link ObjectIDFactory} instances.
-     */
-    public ObjectIDFactory getFactory( final String protocol ) {
-        return (ObjectIDFactory) this.factories.get(protocol);
-    }
-    
-    /**
-     * Method to obtain the set of {@link java.lang.String String} protocols.  This is a utility that merely obtains the
-     * protocols from the factories.
-     * @return the Set of String protocols; never null
-     */
-    public Set getProtocols() {
-        return factories.keySet();
-    }
-    
-    /**
-     * Return whether there is a factory that is used by default for the {@link #create()} method is invoked.
-     * @return true if there is a default factory, or false otherwise
-     */
-    public boolean hasDefaultFactory() {
-        return defaultFactory != null;
-    }
-
-    /**
-     * Get the factory that is used by default for the {@link #create()} method is invoked.
-     * @return the default factory, or null if there is no default factory
-     */
-    public ObjectIDFactory getDefaultFactory() {
-        return defaultFactory;
-    }
-
-    /**
-     * Set the factory that should be used by default for the {@link #create()} method is invoked.
-     * @param factory the factory that should be used by default; may be null if no default is to be allowed.
-     */
-    public void setDefaultFactory(final ObjectIDFactory factory) {
-        defaultFactory = factory;
-    }
-
-    /**
-     * Set the factory that should be used by default for the {@link #create()} method is invoked.
-     * @param protocol the protocol for factory that should be used by default; may be null if no default
-     * is to be allowed.
-     */
-    public void setDefaultFactory(final String protocol) {
-        final ObjectIDFactory factory = getFactory(protocol);   // null if protocol doesn't match
-        defaultFactory = factory;
-    }
-
-    /**
-     * Create a new {@link ObjectID} using the default factory
-     * @return the new ObjectID
-     */
-    public ObjectID create() {
-        if ( this.defaultFactory != null ) {
-            return this.defaultFactory.create();
-        }
-        // Invalid protocol
-        throw new IllegalArgumentException(CorePlugin.Util.getString("IDGenerator.No_default_id_factory_has_been_defined")); //$NON-NLS-1$
-    }
-    
-    /**
-     * Create a new {@link ObjectID} for the type specified by the protocol
-     * @param protocol the protocol of the type of {@link ObjectID} to be created; may not be null
-     * @return the new ObjectID
-     */
-    public ObjectID create( final String protocol ) {
-        if (protocol == null) {
-            final String msg = CorePlugin.Util.getString("IDGenerator.The_protocol_may_not_be_null"); //$NON-NLS-1$
-            throw new IllegalArgumentException(msg);
-        }
-        // Get the factory ...
-        final ObjectIDFactory factory = (ObjectIDFactory) this.factories.get(protocol);
-        if ( factory != null ) {
-            // Create the new ObjectID ...
-            return factory.create();
-        }
-        // Invalid protocol
-        throw new IllegalArgumentException(CorePlugin.Util.getString("IDGenerator.The_specified_ObjectID_protocol___8",protocol)); //$NON-NLS-1$ 
-    }
-    
-    /**
-     * Convenience method for obtaining the stringified form of an ObjectID.
-     * @param id
-     * @return
-     */
-    public String toString( final ObjectID id ) {
-        return id.toString();
-    }
-    
-    /**
-     * Convenience method for obtaining the stringified form of an ObjectID.
-     * @param id
-     * @return
-     */
-    public String toString( final ObjectID id, final char delim ) {
-        return id.toString(delim);
-    }
-    
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param id the stringified id of the form <code>protocol:value</code>, where
-     * <code>protocol</code> defines the protocol of the ID, and <code>value</code
-     * contains the global identifier value; may never be null
-     * @return the ObjectID instance for the stringified ID
-     * @throws InvalidIDException if the specified string does not contain a valid ObjectID
-     * or if the protocol is unknown
-     */
-    public ObjectID stringToObject(String id) throws InvalidIDException {
-        if (id == null) {
-            final String msg = CorePlugin.Util.getString("IDGenerator.The_stringified_ID_may_not_be_null"); //$NON-NLS-1$
-            throw new IllegalArgumentException(msg);
-        }
-
-        // Parse the string
-        final ParsedObjectID parsedID = ParsedObjectID.parsedStringifiedObjectID(id,this.protocols);
-
-        // Find the appropriate factory and parse the id ...
-        final ObjectIDFactory factory = (ObjectIDFactory) this.factories.get(parsedID.getProtocol());
-        ObjectID result = null;
-        if ( factory != null ) {
-            result = factory.stringWithoutProtocolToObject(parsedID.getRemainder());
-        }
-        if ( result == null ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("IDGenerator.The_stringified_ObjectID_has_an_unknown_protocol___16") + parsedID.getProtocol()); //$NON-NLS-1$
-        }
-        return result;
-    }
-    
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param id the stringified id of the form <code>protocol:value</code>, where
-     * <code>protocol</code> defines the protocol of the ID, and <code>value</code
-     * contains the global identifier value; may never be null
-     * @return the ObjectID instance for the stringified ID
-     * @throws InvalidIDException if the specified string does not contain a valid ObjectID
-     * or if the protocol is unknown
-     */
-    public ObjectID stringToObject(String id, String protocol) throws InvalidIDException {
-        if (id == null) {
-            final String msg = CorePlugin.Util.getString("IDGenerator.The_stringified_ID_may_not_be_null"); //$NON-NLS-1$
-            throw new IllegalArgumentException(msg);
-        }
-
-        // Parse the string
-        final ParsedObjectID parsedID = ParsedObjectID.parsedStringifiedObjectID(id,protocol);
-
-        // Find the appropriate factory and parse the id ...
-        final ObjectIDFactory factory = (ObjectIDFactory) this.factories.get(parsedID.getProtocol());
-        ObjectID result = null;
-        if ( factory != null ) {
-            result = factory.stringWithoutProtocolToObject(parsedID.getRemainder());
-        }
-        if ( result == null ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("IDGenerator.The_stringified_ObjectID_has_an_unknown_protocol___16") + parsedID.getProtocol()); //$NON-NLS-1$
-        }
-        return result;
-    }
-    
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param id the stringified id of the form <code>protocol:value</code>, where
-     * <code>protocol</code> defines the protocol of the ID, and <code>value</code
-     * contains the global identifier value; may never be null
-     * @return the ObjectID instance for the stringified ID
-     * @throws InvalidIDException if the specified string does not contain a valid ObjectID
-     * or if the protocol is unknown
-     */
-    public ObjectID stringToObject(String id, char delim) throws InvalidIDException {
-        if (id == null) {
-            final String msg = CorePlugin.Util.getString("IDGenerator.The_stringified_ID_may_not_be_null"); //$NON-NLS-1$
-            throw new IllegalArgumentException(msg);
-        }
-
-        // Parse the string
-        final ParsedObjectID parsedID = ParsedObjectID.parsedStringifiedObjectID(id,delim);
-
-        // Find the appropriate factory and parse the id ...
-        final ObjectIDFactory factory = (ObjectIDFactory) this.factories.get(parsedID.getProtocol());
-        ObjectID result = null;
-        if ( factory != null ) {
-            result = factory.stringWithoutProtocolToObject(parsedID.getRemainder());
-        }
-        if ( result == null ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("IDGenerator.The_stringified_ObjectID_has_an_unknown_protocol___16") + parsedID.getProtocol()); //$NON-NLS-1$
-        }
-        return result;
-    }
-    
 }
 

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/IntegerID.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/IntegerID.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/IntegerID.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,125 +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 org.teiid.core.id;
-
-import java.io.Serializable;
-
-import org.teiid.core.util.Assertion;
-
-
-public class IntegerID implements ObjectID, Serializable {
-
-    public static final String PROTOCOL = "mmint"; //$NON-NLS-1$
-    private int id;
-
-    protected IntegerID(int id) {
-	    this.id = id;
-    }
-    /**
-     * Get hash code for object
-     * @return Hash code
-     */
-    public int hashCode() {
-        return this.id;
-    }
-
-    /**
-    /**
-     * Returns true if the specified object is semantically equal to this instance.
-     * Note:  this method is consistent with <code>compareTo()</code>.
-     * <p>
-     * @param obj the object that this instance is to be compared to.
-     * @return whether the object is equal to this object.
-     */
-    public boolean equals(Object obj) {
-        // Check if instances are identical ...
-        if ( this == obj ) {
-            return true;
-        }
-
-        // Check if object can be compared to this one
-        // (this includes checking for null ) ...
-        //if ( this.getClass().isInstance(obj) ) {
-        if ( obj instanceof IntegerID ) {
-            IntegerID that = (IntegerID) obj;
-            return ( this.id == that.id );
-		}
-
-        // Otherwise not comparable ...
-        return false;
-    }
-    /**
-     * Compares this object to another. If the specified object is not an instance of
-     * the LongID class, then this method throws a
-     * ClassCastException (as instances are comparable only to instances of the same
-     * class).
-     * Note:  this method <i>is</i> consistent with <code>equals()</code>, meaning
-     * that <code>(compare(x, y)==0) == (x.equals(y))</code>.
-     * <p>
-     * @param obj the object that this instance is to be compared to; may not be null.
-     * @return a negative integer, zero, or a positive integer as this object
-     *      is less than, equal to, or greater than the specified object, respectively.
-     * @throws ClassCastException if the specified object's type prevents it
-     *      from being compared to this instance.
-     */
-    public int compareTo(Object obj) {
-        IntegerID that = (IntegerID) obj;     // May throw ClassCastException
-        Assertion.isNotNull(obj);
-
-        long diff = this.id - that.id;
-        if ( diff < 0 ) {
-            return -1;
-        }
-        if ( diff > 0 ) {
-            return 1;
-        }
-        return 0;
-    }
-
-    /**
-     * Returns a string representing the current state of the object.
-     * @return the string representation of this instance.
-     */
-    public String toString(){
-        return PROTOCOL + ObjectID.DELIMITER + this.id;
-    }
-    /**
-     * @see org.teiid.core.id.ObjectID#toString(char)
-     */
-    public String toString(char delim) {
-        return PROTOCOL + delim + this.id;
-    }
-
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    public String getProtocol() {
-	    return PROTOCOL;
-    }
-
-    public int getValue() {
-        return this.id;
-    }
-}
-

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/IntegerIDFactory.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/IntegerIDFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/IntegerIDFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,116 +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 org.teiid.core.id;
-
-import java.io.Serializable;
-
-import org.teiid.core.CorePlugin;
-
-public class IntegerIDFactory implements ObjectIDFactory, Serializable {
-    private int lastID = 0;
-    public IntegerIDFactory() {
-    }
-
-    /**
-     * Return the description for the type of ObjectID described by this object.
-     * @return the description
-     */
-    public String getDescription() {
-        return CorePlugin.Util.getString("IntegerIDFactory.Description"); //$NON-NLS-1$
-    }
-
-    protected int getNextValue() {
-        return ++lastID;
-    }
-
-    /**
-     * Create a new ObjectID instance using this protocol.
-     * @return the new instance
-     */
-    public ObjectID create(){
-	    return new IntegerID( getNextValue() );
-    }
-    /**
-     * Return whether the specified ObjectID instance is valid.  Only ObjectID instances
-     * that are for this protocol will be passed in.
-     * <p>
-     * This implementation only checks whether the ObjectID is an instance of a LongID.
-     * @param id the ID that is to be validated, and which is never null
-     * @return true if the instance is valid for this protocol, or false if
-     * it is not valid.
-     */
-    public boolean validate(ObjectID id) {
-        if ( id instanceof IntegerID ) {
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param value the stringified id (the result of {@link ObjectID#toString()}),
-     * and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringToObject(String value) throws InvalidIDException {
-        final ParsedObjectID parsedID = ParsedObjectID.parsedStringifiedObjectID(value,IntegerID.PROTOCOL);
-        try {
-	        return new IntegerID( Integer.parseInt(parsedID.getRemainder()) );
-        } catch ( NumberFormatException e ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("IntegerIDFactory.The_specified_ID_value_is_invalid",value,getProtocol())); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * This method is called by the {@link IDGenerator#stringToObject(String)} method, which
-     * must process the protocol to determine the correct parser to use.  As such, it guarantees
-     * that the parser that receives this call can assume that the protocol was equal to the
-     * protocol returned by the parser's {@link ObjectIDDescriptor#getProtocol()}.
-     * @param value the stringified id with the protocol and ObjectID.DELIMITER already
-     * removed, and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringWithoutProtocolToObject(String value) throws InvalidIDException {
-        try {
-            return new IntegerID( Integer.parseInt(value) );
-        } catch ( NumberFormatException e ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("IntegerIDFactory.The_specified_ID_value_is_invalid",value,getProtocol())); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    public String getProtocol() {
-	    return IntegerID.PROTOCOL;
-    }
-}
-

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/InvalidIDException.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/InvalidIDException.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/InvalidIDException.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,70 +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 org.teiid.core.id;
-
-import org.teiid.core.CorePlugin;
-import org.teiid.core.TeiidException;
-
-/**
- * Exception which occurs if an error occurs within the server that is not
- * business-related.  For instance, if a service or bean is not available
- * or communication fails.
- */
-public class InvalidIDException extends TeiidException {
-    private static final String INVALID_ID_MESSAGE = CorePlugin.Util.getString("InvalidIDException.Invalid_ID_1"); //$NON-NLS-1$
-
-    /**
-     * No-Arg Constructor
-     */
-    public InvalidIDException(  ) {
-        super( );
-    }
-
-
-    /**
-     * Construct an instance of InvalidIDException.
-     * @param message
-     */
-    public InvalidIDException(String message) {
-        super(message);
-    }
-
-    /**
-     * Construct an instance of InvalidIDException.
-     * @param e
-     */
-    public InvalidIDException(Throwable e) {
-        super(e,INVALID_ID_MESSAGE);
-    }
-
-
-    /**
-     * Construct an instance of InvalidIDException.
-     * @param e
-     * @param message
-     */
-    public InvalidIDException(Throwable e, String message) {
-        super(e, message);
-    }
-
-}

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/LongID.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/LongID.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/LongID.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,126 +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 org.teiid.core.id;
-
-import java.io.Serializable;
-
-import org.teiid.core.util.Assertion;
-
-
-public class LongID implements ObjectID, Serializable {
-    public static final String PROTOCOL = "mmlong"; //$NON-NLS-1$
-
-    private long id;
-
-    protected LongID(long id) {
-	    this.id = id;
-    }
-    /**
-     * Get hash code for object
-     * @return Hash code
-     */
-    public int hashCode() {
-        return (int) this.id;
-    }
-
-    /**
-    /**
-     * Returns true if the specified object is semantically equal to this instance.
-     * Note:  this method is consistent with <code>compareTo()</code>.
-     * <p>
-     * @param obj the object that this instance is to be compared to.
-     * @return whether the object is equal to this object.
-     */
-    public boolean equals(Object obj) {
-        // Check if instances are identical ...
-        if ( this == obj ) {
-            return true;
-        }
-
-        // Check if object can be compared to this one
-        // (this includes checking for null ) ...
-        //if ( this.getClass().isInstance(obj) ) {
-        if ( obj instanceof LongID ) {
-            LongID that = (LongID) obj;
-            return ( this.id == that.id );
-		}
-
-        // Otherwise not comparable ...
-        return false;
-    }
-    /**
-     * Compares this object to another. If the specified object is not an instance of
-     * the LongID class, then this method throws a
-     * ClassCastException (as instances are comparable only to instances of the same
-     * class).
-     * Note:  this method <i>is</i> consistent with <code>equals()</code>, meaning
-     * that <code>(compare(x, y)==0) == (x.equals(y))</code>.
-     * <p>
-     * @param obj the object that this instance is to be compared to; may not be null.
-     * @return a negative integer, zero, or a positive integer as this object
-     *      is less than, equal to, or greater than the specified object, respectively.
-     * @throws ClassCastException if the specified object's type prevents it
-     *      from being compared to this instance.
-     */
-    public int compareTo(Object obj) {
-        LongID that = (LongID) obj;     // May throw ClassCastException
-        Assertion.isNotNull(obj);
-
-        long diff = this.id - that.id;
-        if ( diff < 0 ) {
-            return -1;
-        }
-        if ( diff > 0 ) {
-            return 1;
-        }
-        return 0;
-    }
-
-    /**
-     * Returns a string representing the current state of the object.
-     * @return the string representation of this instance.
-     */
-    public String toString(){
-        return PROTOCOL + ObjectID.DELIMITER + this.id;
-    }
-    
-    /**
-     * @see org.teiid.core.id.ObjectID#toString(char)
-     */
-    public String toString(char delim) {
-        return PROTOCOL + delim + this.id;
-    }
-
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    public String getProtocol() {
-	    return PROTOCOL;
-    }
-
-    public long getValue() {
-        return this.id;
-    }
-}
-

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/LongIDFactory.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/LongIDFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/LongIDFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,117 +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 org.teiid.core.id;
-
-import java.io.Serializable;
-
-import org.teiid.core.CorePlugin;
-
-
-public class LongIDFactory implements ObjectIDFactory, Serializable {
-    private long lastID = 0;
-    public LongIDFactory() {
-    }
-
-    /**
-     * Return the description for the type of ObjectID described by this object.
-     * @return the description
-     */
-    public String getDescription() {
-        return CorePlugin.Util.getString("LongIDFactory.Description"); //$NON-NLS-1$
-    }
-
-    protected long getNextValue() {
-        return ++lastID;
-    }
-
-    /**
-     * Create a new ObjectID instance using this protocol.
-     * @return the new instance
-     */
-    public ObjectID create(){
-	    return new LongID( getNextValue() );
-    }
-    /**
-     * Return whether the specified ObjectID instance is valid.  Only ObjectID instances
-     * that are for this protocol will be passed in.
-     * <p>
-     * This implementation only checks whether the ObjectID is an instance of a LongID.
-     * @param id the ID that is to be validated, and which is never null
-     * @return true if the instance is valid for this protocol, or false if
-     * it is not valid.
-     */
-    public boolean validate(ObjectID id) {
-        if ( id instanceof LongID ) {
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * This method is called by the {@link IDGenerator#stringToObject(String)} method, which
-     * must process the protocol to determine the correct parser to use.  As such, it guarantees
-     * that the parser that receives this call can assume that the protocol was equal to the
-     * protocol returned by the parser's {@link ObjectIDDescriptor#getProtocol()}.
-     * @param value the stringified id with the protocol and ObjectID.DELIMITER already
-     * removed, and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringWithoutProtocolToObject(String value) throws InvalidIDException {
-        try {
-	        return new LongID( Long.parseLong(value) );
-        } catch ( NumberFormatException e ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("LongIDFactory.The_specified_ID_value_is_invalid",value,getProtocol())); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param value the stringified id (the result of {@link ObjectID#toString()}),
-     * and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringToObject(String value) throws InvalidIDException {
-        final ParsedObjectID parsedID = ParsedObjectID.parsedStringifiedObjectID(value,LongID.PROTOCOL);
-        try {
-            return new LongID( Long.parseLong(parsedID.getRemainder()) );
-        } catch ( NumberFormatException e ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("LongIDFactory.The_specified_ID_value_is_invalid",value,getProtocol())); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    public String getProtocol() {
-	    return LongID.PROTOCOL;
-    }
-}
-

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/ObjectID.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/ObjectID.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/ObjectID.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,63 +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 org.teiid.core.id;
-
-
-
-public interface ObjectID extends Comparable {
-
-    char DELIMITER = ':';
-
-    /**
-     * Compares this object to another. If the specified object is not an instance of
-     * the ObjectID class, then this method throws a
-     * ClassCastException (as instances are comparable only to instances of the same
-     * class).
-     * Note:  this method <i>is</i> consistent with <code>equals()</code>, meaning
-     * that <code>(compare(x, y)==0) == (x.equals(y))</code>.
-     * <p>
-     * @param obj the object that this instance is to be compared to; may not be null.
-     * @return a negative integer, zero, or a positive integer as this object
-     *      is less than, equal to, or greater than the specified object, respectively.
-     * @throws ClassCastException if the specified object's type prevents it
-     *      from being compared to this instance.
-     */
-    int compareTo(Object obj);
-    /**
-     * Returns a string representing the current state of the object.
-     * @return the string representation of this instance.
-     */
-    String toString();
-    /**
-     * Returns a string representing the current state of the object.
-     * @param delim the delimiter that should be used
-     * @return the string representation of this instance.
-     */
-    String toString( char delim );
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    String getProtocol();
-}
-

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/ObjectIDFactory.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/ObjectIDFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/ObjectIDFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,76 +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 org.teiid.core.id;
-
-
-/**
- * The ObjectIDDescriptor defines the interface that is used to describe a particular type of 
- * {@link ObjectID}.
- */
-public interface ObjectIDFactory {
-    
-    /**
-     * Return the protocol for the type of ObjectID described by this object.
-     * @return the protocol
-     */
-    String getProtocol();
-    
-    /**
-     * Return the description for the type of ObjectID described by this object.
-     * @return the description
-     */
-    String getDescription();
-    
-    /**
-     * Create a new GlobalUID instance using this protocol.
-     * @return the new instance
-     */
-    ObjectID create();
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param value the stringified id (the result of {@link ObjectID#toString()}),
-     * and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    ObjectID stringToObject(String value) throws InvalidIDException;
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * This method is called by the {@link IDGenerator#stringToObject(String)} method, which
-     * must process the protocol to determine the correct parser to use.  As such, it guarantees
-     * that the parser that receives this call can assume that the protocol was equal to the
-     * protocol returned by the parser's {@link ObjectIDDescriptor#getProtocol()}.
-     * @param value the stringified id with the protocol and ObjectID.DELIMITER already
-     * removed, and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    ObjectID stringWithoutProtocolToObject(String value) throws InvalidIDException;
-
-}

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/ParsedObjectID.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/ParsedObjectID.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/ParsedObjectID.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,88 +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 org.teiid.core.id;
-import java.util.Iterator;
-import java.util.Set;
-
-import org.teiid.core.CorePlugin;
-
-
-/**
- * ParsedObjectID
- */
-public class ParsedObjectID {
-    private static final int DELIMITER_LENGTH = 1;
-    private final String protocol;
-    private final String remainder;
-    
-    protected ParsedObjectID( final String protocol, final String remainder ) {
-        this.protocol = protocol;
-        this.remainder = remainder;
-    } 
-    
-    public String getProtocol() {
-        return protocol;
-    }
-    
-    public String getRemainder() {
-        return remainder;
-    }
-    
-    public static ParsedObjectID parsedStringifiedObjectID( final String id, final Set protocols ) throws InvalidIDException {
-        final Iterator iter = protocols.iterator();
-        while (iter.hasNext()) {
-            final String protocol = (String)iter.next();
-            if ( id.startsWith(protocol) ) {
-                return new ParsedObjectID(protocol,id.substring(protocol.length()+DELIMITER_LENGTH));
-            }
-        }
-        throw new InvalidIDException(CorePlugin.Util.getString("ParsedObjectID.The_stringified_ObjectID_does_not_have_a_protocol")); //$NON-NLS-1$
-    }
-
-    public static ParsedObjectID parsedStringifiedObjectID( final String id ) throws InvalidIDException {
-        return parsedStringifiedObjectID(id,ObjectID.DELIMITER);
-    }
-
-    public static ParsedObjectID parsedStringifiedObjectID( final String id, final char delim ) throws InvalidIDException {
-        int index = -1;
-        if ( id != null ) {
-            // Obtain the protocol from the string
-            index = id.indexOf(delim);
-        }
-        if ( index == -1 ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("ParsedObjectID.The_stringified_ObjectID_does_not_have_a_protocol")); //$NON-NLS-1$
-        }
-        return new ParsedObjectID(id.substring(0,index),id.substring(index+DELIMITER_LENGTH));
-    }
-
-    public static ParsedObjectID parsedStringifiedObjectID( final String id, final String expectedProtocol ) throws InvalidIDException {
-        if ( expectedProtocol == null ) {
-            return new ParsedObjectID("",id); //$NON-NLS-1$
-        }
-        if ( id.startsWith(expectedProtocol) ) {
-            return new ParsedObjectID(expectedProtocol,id.substring(expectedProtocol.length()+DELIMITER_LENGTH));
-        }
-        throw new InvalidIDException(CorePlugin.Util.getString("ParsedObjectID.The_stringified_ObjectID_does_not_have_the_required_protocol_{0}",expectedProtocol)); //$NON-NLS-1$
-    }
-
-}

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/StringID.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/StringID.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/StringID.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,120 +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 org.teiid.core.id;
-
-import java.io.Serializable;
-
-import org.teiid.core.util.Assertion;
-
-
-public class StringID implements ObjectID, Serializable {
-    public static final String PROTOCOL = "strid"; //$NON-NLS-1$
-
-    private String id;
-
-    protected StringID(String id) {
-	    this.id = id;
-    }
-    protected StringID(long id) {
-	    this.id = Long.toString(id);
-    }
-    /**
-     * Get hash code for object
-     * @return Hash code
-     */
-    public int hashCode() {
-        return id.hashCode();
-    }
-
-    /**
-    /**
-     * Returns true if the specified object is semantically equal to this instance.
-     * Note:  this method is consistent with <code>compareTo()</code>.
-     * <p>
-     * @param obj the object that this instance is to be compared to.
-     * @return whether the object is equal to this object.
-     */
-    public boolean equals(Object obj) {
-        // Check if instances are identical ...
-        if ( this == obj ) {
-            return true;
-        }
-
-        // Check if object can be compared to this one
-        // (this includes checking for null ) ...
-        //if ( this.getClass().isInstance(obj) ) {
-        if ( obj instanceof StringID ) {
-            StringID that = (StringID) obj;
-            return ( this.id.equals( that.id ) );
-		}
-
-        // Otherwise not comparable ...
-        return false;
-    }
-    /**
-     * Compares this object to another. If the specified object is not an instance of
-     * the StringID class, then this method throws a
-     * ClassCastException (as instances are comparable only to instances of the same
-     * class).
-     * Note:  this method <i>is</i> consistent with <code>equals()</code>, meaning
-     * that <code>(compare(x, y)==0) == (x.equals(y))</code>.
-     * <p>
-     * @param obj the object that this instance is to be compared to; may not be null.
-     * @return a negative integer, zero, or a positive integer as this object
-     *      is less than, equal to, or greater than the specified object, respectively.
-     * @throws ClassCastException if the specified object's type prevents it
-     *      from being compared to this instance.
-     */
-    public int compareTo(Object obj) {
-        StringID that = (StringID) obj;     // May throw ClassCastException
-        Assertion.isNotNull(obj);
-        return this.id.compareTo(that.id);
-    }
-
-    /**
-     * Returns a string representing the current state of the object.
-     * @return the string representation of this instance.
-     */
-    public String toString(){
-        return PROTOCOL + ObjectID.DELIMITER + this.id;
-    }
-    /**
-     * @see org.teiid.core.id.ObjectID#toString(char)
-     */
-    public String toString(char delim) {
-        return PROTOCOL + delim + this.id;
-    }
-
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    public String getProtocol() {
-	    return PROTOCOL;
-    }
-
-    protected String getValue() {
-        return this.id;
-    }
-}
-

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/StringIDFactory.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/StringIDFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/StringIDFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,116 +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 org.teiid.core.id;
-
-import org.teiid.core.CorePlugin;
-
-
-
-public class StringIDFactory implements ObjectIDFactory {
-    private long lastID = 0;
-    public StringIDFactory() {
-    }
-
-    /**
-     * Return the description for the type of ObjectID described by this object.
-     * @return the description
-     */
-    public String getDescription() {
-        return CorePlugin.Util.getString("StringIDFactory.Description"); //$NON-NLS-1$
-    }
-
-    protected long getNextValue() {
-        return ++lastID;
-    }
-
-    /**
-     * Create a new ObjectID instance using this protocol.
-     * @return the new instance
-     */
-    public ObjectID create(){
-	    return new StringID( getNextValue() );
-    }
-    /**
-     * Return whether the specified ObjectID instance is valid.  Only ObjectID instances
-     * that are for this protocol will be passed in.
-     * <p>
-     * This implementation only checks whether the ObjectID is an instance of a StringID.
-     * @param id the ID that is to be validated, and which is never null
-     * @return true if the instance is valid for this protocol, or false if
-     * it is not valid.
-     */
-    public boolean validate(ObjectID id) {
-        if ( id instanceof StringID ) {
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * This method is called by the {@link IDGenerator#stringToObject(String)} method, which
-     * must process the protocol to determine the correct parser to use.  As such, it guarantees
-     * that the parser that receives this call can assume that the protocol was equal to the
-     * protocol returned by the parser's {@link ObjectIDDescriptor#getProtocol()}.
-     * @param value the stringified id with the protocol and ObjectID.DELIMITER already
-     * removed, and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringWithoutProtocolToObject(String value) throws InvalidIDException {
-        try {
-            return new StringID( value );
-        } catch ( NumberFormatException e ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("StringIDFactory.The_specified_ID_value_is_invalid",value,getProtocol())); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param value the stringified id (the result of {@link ObjectID#toString()}),
-     * and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringToObject(String value) throws InvalidIDException {
-        final ParsedObjectID parsedID = ParsedObjectID.parsedStringifiedObjectID(value,LongID.PROTOCOL);
-        try {
-            return new StringID( parsedID.getRemainder() );
-        } catch ( NumberFormatException e ) {
-            throw new InvalidIDException(CorePlugin.Util.getString("StringIDFactory.The_specified_ID_value_is_invalid",value,getProtocol())); //$NON-NLS-1$
-        }
-    }
-
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    public String getProtocol() {
-	    return StringID.PROTOCOL;
-    }
-}
-

Modified: branches/as7/engine/src/main/java/org/teiid/core/id/UUID.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/UUID.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/UUID.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,10 +24,7 @@
 
 import java.io.Serializable;
 
-import org.teiid.core.CorePlugin;
-import org.teiid.core.util.Assertion;
 
-
 /**
  * <p>This class represents a universally unique identifier, consisting of
  * two long integral values. </p> 
@@ -35,10 +32,11 @@
  * <p>This identifier is supposed to be unique both spatially and temporally.
  * It is based on version 4 IETF variant random UUIDs. </p>
  */
-public class UUID implements ObjectID, Serializable {
+public class UUID implements Serializable {
+	
+	private static final long serialVersionUID = 4730187208307761197L;
 
-    private static final String NOT_UUID_MESSAGE = CorePlugin.Util.getString("UUID.ID_must_be_of_type_UUID_1"); //$NON-NLS-1$
-    private static final String UNPARSABLE_MESSAGE = CorePlugin.Util.getString("UUID.ID_must_be_of_type_UUID_to_parse_2"); //$NON-NLS-1$
+	char DELIMITER = ':';
     /**
      * The variants allowed by the UUID specification.
      */
@@ -78,42 +76,6 @@
     }
     
     /**
-     * Return the first part of the UUID as a long.
-     * @return first part of the UUID as a long
-     */
-    public static long getPart1(ObjectID id) {
-    	Assertion.assertTrue((id instanceof UUID), UNPARSABLE_MESSAGE);
-    	
-    	UUID uuid = (UUID)id;
-	    return uuid.uuid.getMostSignificantBits();
-    }
-    
-    /**
-     * Return the first part of the UUID as a long.
-     * @return first part of the UUID as a long
-     */
-    public static long getPart2(ObjectID id) {
-    	Assertion.assertTrue((id instanceof UUID), UNPARSABLE_MESSAGE);
-    	
-    	UUID uuid = (UUID)id;
-    	return uuid.uuid.getLeastSignificantBits();
-    }
-    
-    public static int getVariant(ObjectID id ) {
-        Assertion.assertTrue((id instanceof UUID), NOT_UUID_MESSAGE);
-        
-        UUID uuid = (UUID)id;
-        return uuid.uuid.variant();
-    }
-
-    public static int getVersion(ObjectID id ) {
-        Assertion.assertTrue((id instanceof UUID), NOT_UUID_MESSAGE);
-        
-        UUID uuid = (UUID)id;
-        return uuid.uuid.version();
-    }
-
-    /**
      * Return the name of the protocol that this factory uses.
      * @return the protocol name
      */
@@ -179,7 +141,7 @@
      * @return the string representation of this instance.
      */
     public String toString(){
-        return toString(ObjectID.DELIMITER);
+        return toString(DELIMITER);
     }
 
     /**
@@ -206,20 +168,4 @@
         return this.cachedExportableFormUuidString;
     }
 
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param value the stringified id with the protocol and ObjectID.DELIMITER already
-     * removed, and which is never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     */
-    public static ObjectID stringToObject(String value) throws InvalidIDException {
-        try {
-            return new UUID(java.util.UUID.fromString(value));
-        } catch ( IllegalArgumentException e ) {
-            throw new InvalidIDException(
-                CorePlugin.Util.getString("UUID.InvalidFormatForProtocol",value,PROTOCOL)); //$NON-NLS-1$
-        }
-    }
-
 }

Deleted: branches/as7/engine/src/main/java/org/teiid/core/id/UUIDFactory.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/core/id/UUIDFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/core/id/UUIDFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,132 +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 org.teiid.core.id;
-
-import org.teiid.core.CorePlugin;
-
-/**
- * <p>This class is a factory for generating universally unique identifiers
- * (UUID's). </p>
- *
- * <h3>Output format for UUIDs</h3>
- * <p>UUIDs are output in the following 36-character format:
- * <pre>
- *    xxxxxxxx-yyyy-zzzz-cccc-nnnnnnnnnnnn
- * </pre>
- * where x=least significant time component, y=middle significant time component,
- * z=most significant time component multiplexed with version, c=clock sequence
- * multiplexed with variant, and n=node component (random number).
- * </p>
- *
- * <p>The generated ID's conform somewhat to the (now expired) IETF internet
- * draft standard, "UUIDs and GUIDs", DCE spec on UUIDs. </p>
- *
- * <ul>
- *   <li>
- *   <a href="http://hegel.ittc.ukans.edu/topics/internet/internet-drafts/draft-l/draft-leach-uuids-guids-01.txt">
- *      UUIDs and GUIDs, P. Leach, R. Salz, 02/05/1998</a>
- *   </li>
- *   <li>
- *   <a href="http://www.opengroup.org/onlinepubs/009629399/apdxa.htm">
- *      DCE Universal Unique Identifier</a>.
- *   </li>
- * </ul></p>
- *
- * <p>All references in this code to bit positions as "least significant" and
- * "most significant" refer to the bits moving from right to left, respectively.
- * </p>
- */
-public class UUIDFactory implements ObjectIDFactory {
-    
-    // -------------------------------------------------------------------------
-    //                           C O N S T R U C T O R
-    // -------------------------------------------------------------------------
-    
-    public UUIDFactory() {
-    }
-    
-    // -------------------------------------------------------------------------
-    //                       P U B L I C     M E T H O D S
-    // -------------------------------------------------------------------------
-    
-    /**
-     * Return the description for the type of ObjectID described by this object.
-     * @return the description
-     */
-    public String getDescription() {
-        return CorePlugin.Util.getString("UUIDFactory.Description"); //$NON-NLS-1$
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * This method is called by the {@link IDGenerator#stringToObject(String)} method, which
-     * must process the protocol to determine the correct parser to use.  As such, it guarantees
-     * that the parser that receives this call can assume that the protocol was equal to the
-     * protocol returned by the parser's {@link ObjectIDDescriptor#getProtocol()}.
-     * @param value the stringified id with the protocol and ObjectID.DELIMITER already
-     * removed, and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringWithoutProtocolToObject(String value) throws InvalidIDException {
-        return UUID.stringToObject(value);
-    }
-
-    /**
-     * Attempt to convert the specified string to the appropriate ObjectID instance.
-     * @param value the stringified id (the result of {@link ObjectID#toString()}),
-     * and should never null or zero length
-     * @return the ObjectID instance for the stringified ID if this factory is able
-     * to parse the string, or null if the factory is unaware of the specified format.
-     * @throws InvalidIDException if the parser is aware of this protocol, but it is of the wrong
-     * format for this type of ObjectID.
-     */
-    public ObjectID stringToObject(String value) throws InvalidIDException {
-        final ParsedObjectID parsedID = ParsedObjectID.parsedStringifiedObjectID(value,UUID.PROTOCOL);
-        return UUID.stringToObject(parsedID.getRemainder());
-    }
-
-    /**
-     * Return the name of the protocol that this factory uses.
-     * @return the protocol name
-     */
-    public String getProtocol() {
-	    return UUID.PROTOCOL;
-    }
-
-    // -------------------------------------------------------------------------
-    //                   G E N E R A T I O N    M E T H O D S
-    // -------------------------------------------------------------------------
-    
-    /**
-     * <p>Create a new ObjectID instance using this protocol. </p>
-     * @return Universally unique ID (UUID)
-     */
-    public ObjectID create() {
-        return new UUID(java.util.UUID.randomUUID());
-    }
-
-}
-

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/CapabilitiesConverter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/CapabilitiesConverter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/CapabilitiesConverter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -99,11 +99,18 @@
         tgtCaps.setCapabilitySupport(Capability.QUERY_ORDERBY_NULL_ORDERING, srcCaps.supportsOrderByNullOrdering());
         tgtCaps.setCapabilitySupport(Capability.INSERT_WITH_ITERATOR, srcCaps.supportsInsertWithIterator());
         tgtCaps.setCapabilitySupport(Capability.COMMON_TABLE_EXPRESSIONS, srcCaps.supportsCommonTableExpressions());
-        List functions = srcCaps.getSupportedFunctions();
+        tgtCaps.setCapabilitySupport(Capability.ADVANCED_OLAP, srcCaps.supportsAdvancedOlapOperations());
+        tgtCaps.setCapabilitySupport(Capability.ELEMENTARY_OLAP, srcCaps.supportsAdvancedOlapOperations());
+        tgtCaps.setCapabilitySupport(Capability.WINDOW_FUNCTION_ORDER_BY_AGGREGATES, srcCaps.supportsWindowOrderByWithAggregates());
+        tgtCaps.setCapabilitySupport(Capability.QUERY_AGGREGATES_ARRAY, srcCaps.supportsArrayAgg());
+        tgtCaps.setCapabilitySupport(Capability.CRITERIA_SIMILAR, srcCaps.supportsSimilarTo());
+        tgtCaps.setCapabilitySupport(Capability.CRITERIA_LIKE_REGEX, srcCaps.supportsLikeRegex());
+        
+        List<String> functions = srcCaps.getSupportedFunctions();
         if(functions != null && functions.size() > 0) {
-            Iterator iter = functions.iterator();
+            Iterator<String> iter = functions.iterator();
             while(iter.hasNext()) {
-                String func = (String) iter.next();
+                String func = iter.next();
                 tgtCaps.setFunctionSupport(func.toLowerCase(), true);
             }
         }


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/CapabilitiesConverter.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -113,7 +113,7 @@
     public MetadataStore getMetadata(String modelName, Map<String, Datatype> datatypes, Properties importProperties) throws TranslatorException {
 		MetadataFactory factory = new MetadataFactory(modelName, datatypes, importProperties);
 		Object connectionFactory = getConnectionFactory();
-		Object connection = executionFactory.getConnection(connectionFactory);
+		Object connection = executionFactory.getConnection(connectionFactory, null);
 		Object unwrapped = null;
 		
 		if (connection instanceof WrappedConnection) {

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorWorkItem.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -100,6 +100,7 @@
                 );
         this.securityContext.setUser(requestMsg.getWorkContext().getSubject());
         this.securityContext.setBatchSize(this.requestMsg.getFetchSize());
+        this.securityContext.setSession(requestMsg.getWorkContext().getSession());
         
         this.connector = manager.getExecutionFactory();
     	VDBMetaData vdb = requestMsg.getWorkContext().getVDB();
@@ -195,7 +196,7 @@
     	LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {this.requestMsg.getAtomicRequestID(), "Processing NEW request:", this.requestMsg.getCommand()}); //$NON-NLS-1$                                     
     	try {
 	    	this.connectionFactory = this.manager.getConnectionFactory();
-	        this.connection = this.connector.getConnection(this.connectionFactory);
+	        this.connection = this.connector.getConnection(this.connectionFactory, securityContext);
 
 	        Object unwrapped = null;
 			if (connection instanceof WrappedConnection) {

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/ExecutionContextImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,6 +30,7 @@
 
 import javax.security.auth.Subject;
 
+import org.teiid.adminapi.Session;
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.core.util.HashCodeUtil;
 import org.teiid.translator.ExecutionContext;
@@ -64,6 +65,7 @@
     
     private int batchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
 	private List<Exception> warnings = new LinkedList<Exception>();
+	private Session session;
     
     public ExecutionContextImpl(String vdbName, int vdbVersion,  Serializable executionPayload, 
                                 String originalConnectionID, String connectorName, String requestId, String partId, String execCount) {
@@ -204,4 +206,13 @@
 		warnings.clear();
 		return result;
 	}
+	
+	@Override
+	public Session getSession() {
+		return this.session;
+	}
+	
+	public void setSession(Session session) {
+		this.session = session;
+	}
 }

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/LanguageBridgeFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -31,6 +31,7 @@
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.client.metadata.ParameterInfo;
 import org.teiid.common.buffer.TupleSource;
+import org.teiid.core.CoreConstants;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidRuntimeException;
@@ -62,6 +63,7 @@
 import org.teiid.language.SubqueryComparison;
 import org.teiid.language.SubqueryIn;
 import org.teiid.language.TableReference;
+import org.teiid.language.WindowSpecification;
 import org.teiid.language.With;
 import org.teiid.language.WithItem;
 import org.teiid.language.Argument.Direction;
@@ -70,8 +72,8 @@
 import org.teiid.language.SubqueryComparison.Quantifier;
 import org.teiid.metadata.Procedure;
 import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.FunctionMethod.PushDown;
 import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TempMetadataID;
 import org.teiid.query.sql.lang.BatchedUpdateCommand;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.CompareCriteria;
@@ -114,7 +116,9 @@
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
+import org.teiid.query.sql.symbol.SelectSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.translator.TranslatorException;
 
 
@@ -178,9 +182,9 @@
 
     /* Query */
     Select translate(Query query) {
-        List symbols = query.getSelect().getSymbols();
+        List<SelectSymbol> symbols = query.getSelect().getSymbols();
         List<DerivedColumn> translatedSymbols = new ArrayList<DerivedColumn>(symbols.size());
-        for (Iterator i = symbols.iterator(); i.hasNext();) {
+        for (Iterator<SelectSymbol> i = symbols.iterator(); i.hasNext();) {
             SingleElementSymbol symbol = (SingleElementSymbol)i.next();
             String alias = null;
             if(symbol instanceof AliasSymbol) {
@@ -188,24 +192,17 @@
                 symbol = ((AliasSymbol)symbol).getSymbol();
             }
 
-            org.teiid.language.Expression iExp = null;
-            if(symbol instanceof ElementSymbol) {
-                iExp = translate((ElementSymbol)symbol);
-            } else if(symbol instanceof AggregateSymbol) {
-                iExp = translate((AggregateSymbol)symbol);
-            } else if(symbol instanceof ExpressionSymbol) {
-                iExp = translate(((ExpressionSymbol)symbol).getExpression());
-            }
+            org.teiid.language.Expression iExp = translate(symbol);
 
             DerivedColumn selectSymbol = new DerivedColumn(alias, iExp);
             translatedSymbols.add(selectSymbol);
         }
     	List<TableReference> items = null;
     	if (query.getFrom() != null) {
-	    	List clauses = query.getFrom().getClauses();
+	    	List<FromClause> clauses = query.getFrom().getClauses();
 	        items = new ArrayList<TableReference>(clauses.size());
-	        for (Iterator i = clauses.iterator(); i.hasNext();) {
-	            items.add(translate((FromClause)i.next()));
+	        for (Iterator<FromClause> i = clauses.iterator(); i.hasNext();) {
+	            items.add(translate(i.next()));
 	        }
     	}
 		Select q = new Select(translatedSymbols, query
@@ -366,15 +363,17 @@
         if(criteria.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
             escapeChar = new Character(criteria.getEscapeChar());
         }
-        return new Like(translate(criteria.getLeftExpression()),
+        Like like = new Like(translate(criteria.getLeftExpression()),
                                     translate(criteria.getRightExpression()), 
                                     escapeChar, 
                                     criteria.isNegated());
+        like.setMode(criteria.getMode());
+        return like;
     }
 
     In translate(SetCriteria criteria) {
         Collection expressions = criteria.getValues();
-        List translatedExpressions = new ArrayList();
+        List<org.teiid.language.Expression> translatedExpressions = new ArrayList<org.teiid.language.Expression>();
         for (Iterator i = expressions.iterator(); i.hasNext();) {
             translatedExpressions.add(translate((Expression)i.next()));
         }
@@ -422,13 +421,13 @@
         return new SubqueryComparison(translate(criteria.getLeftExpression()),
                                   operator,
                                   quantifier,
-                                  translate((QueryCommand)criteria.getCommand()));
+                                  translate(criteria.getCommand()));
     }
 
     SubqueryIn translate(SubquerySetCriteria criteria) {
         return new SubqueryIn(translate(criteria.getExpression()),
                                   criteria.isNegated(),
-                                  translate((QueryCommand)criteria.getCommand()));
+                                  translate(criteria.getCommand()));
     }
 
     Not translate(NotCriteria criteria) {
@@ -458,10 +457,10 @@
             Ordering direction = items.get(i).isAscending() ? Ordering.ASC: Ordering.DESC;
             
             SortSpecification orderByItem = null;                                
-            if(items.get(i).isUnrelated() || (!set && symbol instanceof ElementSymbol)){
+            if(!set && (items.get(i).isUnrelated() || symbol instanceof ElementSymbol)){
             	orderByItem = new SortSpecification(direction, translate(symbol));                                
             } else {
-            	orderByItem = new SortSpecification(direction, new ColumnReference(null, symbol.getOutputName(), null, symbol.getType()));
+            	orderByItem = new SortSpecification(direction, new ColumnReference(null, SingleElementSymbol.getShortName(symbol.getOutputName()), null, symbol.getType()));
             }
             orderByItem.setNullOrdering(items.get(i).getNullOrdering());
             translatedItems.add(orderByItem);
@@ -481,13 +480,36 @@
             return translate((ScalarSubquery)expr);
         } else if (expr instanceof SearchedCaseExpression) {
             return translate((SearchedCaseExpression)expr);
-        } else if (expr instanceof SingleElementSymbol) {
-            return translate((SingleElementSymbol)expr);
+        } else if (expr instanceof ElementSymbol) {
+            return translate((ElementSymbol)expr);
+        } else if (expr instanceof AggregateSymbol) {
+            return translate((AggregateSymbol)expr);
+        } else if (expr instanceof ExpressionSymbol) {
+            return translate((ExpressionSymbol)expr);
         } else if (expr instanceof Criteria) {
         	return translate((Criteria)expr);
+        } else if (expr instanceof WindowFunction) {
+        	return translate((WindowFunction)expr);
         }
         throw new AssertionError();
     }
+    
+    org.teiid.language.WindowFunction translate(WindowFunction windowFunction) {
+    	org.teiid.language.WindowFunction result = new org.teiid.language.WindowFunction();
+    	result.setFunction(translate(windowFunction.getFunction()));
+    	WindowSpecification ws = new WindowSpecification();
+    	ws.setOrderBy(translate(windowFunction.getWindowSpecification().getOrderBy(), false));
+    	List<Expression> partition = windowFunction.getWindowSpecification().getPartition();
+    	if (partition != null) {
+	    	ArrayList<org.teiid.language.Expression> partitionList = new ArrayList<org.teiid.language.Expression>(partition.size());
+	    	for (Expression ex : partition) {
+	    		partitionList.add(translate(ex));
+	    	}
+	    	ws.setPartition(partitionList);
+    	}
+    	result.setWindowSpecification(ws);
+    	return result;
+    }
 
     Literal translate(Constant constant) {
         Literal result = new Literal(constant.getValue(), constant.getType());
@@ -506,8 +528,15 @@
         String name = function.getName();
         if (function.getFunctionDescriptor() != null) {
         	name = function.getFunctionDescriptor().getName();
+        	//check for translator pushdown functions, and use the name in source if possible
+        	if (function.getFunctionDescriptor().getPushdown() == PushDown.MUST_PUSHDOWN 
+        			&& function.getFunctionDescriptor().getSchema().equalsIgnoreCase(CoreConstants.SYSTEM_MODEL)
+        			&& function.getFunctionDescriptor().getMethod().getNameInSource() != null) {
+        		name = function.getFunctionDescriptor().getMethod().getNameInSource();
+        	}
+        } else {
+        	name = SingleElementSymbol.getShortName(name);
         }
-        name = SingleElementSymbol.getShortName(name);
 
         //if there is any ambiguity in the function name it will be up to the translator logic to check the 
         //metadata
@@ -533,48 +562,35 @@
         return new org.teiid.language.ScalarSubquery(translate(ss.getCommand()));
     }
 
-    org.teiid.language.Expression translate(SingleElementSymbol symbol) {
-        if (symbol == null) return null;
-        if (symbol instanceof ElementSymbol) {
-            return translate((ElementSymbol)symbol);
-        } else if (symbol instanceof AggregateSymbol) {
-            return translate((AggregateSymbol)symbol);
-        } else if (symbol instanceof ExpressionSymbol) {
-            return translate((ExpressionSymbol)symbol);
-        }
-        throw new AssertionError();
-    }
-
     org.teiid.language.Expression translate(AliasSymbol symbol) {
         return translate(symbol.getSymbol());
     }
 
     ColumnReference translate(ElementSymbol symbol) {
-        ColumnReference element = new ColumnReference(translate(symbol.getGroupSymbol()), symbol.getOutputName(), null, symbol.getType());
+        ColumnReference element = new ColumnReference(translate(symbol.getGroupSymbol()), SingleElementSymbol.getShortName(symbol.getOutputName()), null, symbol.getType());
         if (element.getTable().getMetadataObject() == null) {
             return element;
         }
 
         Object mid = symbol.getMetadataID();
         
-        if(! (mid instanceof TempMetadataID)) { 
-            element.setMetadataObject(metadataFactory.getElement(mid));
-        }
+        element.setMetadataObject(metadataFactory.getElement(mid));
         return element;
     }
 
     AggregateFunction translate(AggregateSymbol symbol) {
-        return new AggregateFunction(symbol.getAggregateFunction().name(), 
+    	AggregateFunction af = new AggregateFunction(symbol.getAggregateFunction().name(), 
                                 symbol.isDistinct(), 
                                 translate(symbol.getExpression()),
                                 symbol.getType());
+    	af.setCondition(translate(symbol.getCondition()));
+    	return af;
     }
 
     org.teiid.language.Expression translate(ExpressionSymbol symbol) {
         return translate(symbol.getExpression());
     }
 
-
     /* Insert */
     org.teiid.language.Insert translate(Insert insert) {
         List<ElementSymbol> elements = insert.getVariables();
@@ -717,9 +733,6 @@
         }
         fullGroup = removeSchemaName(fullGroup);
         NamedTable group = new NamedTable(fullGroup, alias, null);
-		if (symbol.getMetadataID() instanceof TempMetadataID) {
-			return group;
-		}
         try {
 			group.setMetadataObject(metadataFactory.getGroup(symbol.getMetadataID()));
 		} catch (QueryMetadataException e) {
@@ -741,10 +754,10 @@
     
     /* Batched Updates */
     BatchedUpdates translate(BatchedUpdateCommand command) {
-        List updates = command.getUpdateCommands();
+        List<Command> updates = command.getUpdateCommands();
         List<org.teiid.language.Command> translatedUpdates = new ArrayList<org.teiid.language.Command>(updates.size());
-        for (Iterator i = updates.iterator(); i.hasNext();) {
-            translatedUpdates.add(translate((Command)i.next()));
+        for (Iterator<Command> i = updates.iterator(); i.hasNext();) {
+            translatedUpdates.add(translate(i.next()));
         }
         return new BatchedUpdates(translatedUpdates);
     }
@@ -759,7 +772,10 @@
             rowOffset = ((Integer)c1.getValue()).intValue();
         }
         Literal c2 = (Literal)translate(limit.getRowLimit());
-        int rowLimit = ((Integer)c2.getValue()).intValue();
+        int rowLimit = Integer.MAX_VALUE;
+        if (c2 != null) {
+        	rowLimit = ((Integer)c2.getValue()).intValue();
+        }
         return new org.teiid.language.Limit(rowOffset, rowLimit);
     }
 }

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/datamgr/RuntimeMetadataImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -79,7 +79,7 @@
     }
 
 	public Table getGroup(Object groupId) throws QueryMetadataException, TeiidComponentException {
-		if (!metadata.isVirtualGroup(groupId) && groupId instanceof Table) {
+		if (groupId instanceof Table && !metadata.isVirtualGroup(groupId)) {
 			return (Table)groupId;
 		}
 		return null;

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,7 +26,6 @@
 import javax.resource.spi.work.WorkEvent;
 import javax.resource.spi.work.WorkListener;
 
-import org.teiid.core.TeiidRuntimeException;
 import org.teiid.logging.LogManager;
 
 
@@ -43,23 +42,14 @@
     
     private ThreadState threadState = ThreadState.MORE_WORK;
     private volatile boolean isProcessing;
-    private boolean useCallingThread;
     
-    public AbstractWorkItem(boolean useCallingThread) {
-    	this.useCallingThread = useCallingThread;
-    }
-    
     public void run() {
-    	do {
-			startProcessing();
-			try {
-				process();
-			} finally {
-				if (!endProcessing()) {
-					break;
-				}
-			}
-    	} while (!isDoneProcessing());
+		startProcessing();
+		try {
+			process();
+		} finally {
+			endProcessing();
+		}
     }
     
     synchronized ThreadState getThreadState() {
@@ -79,10 +69,7 @@
     	this.threadState = ThreadState.WORKING;
 	}
     
-    /**
-     * @return true if processing should be continued
-     */
-    final private synchronized boolean endProcessing() {
+    private synchronized void endProcessing() {
     	isProcessing = false;
     	logTrace("end processing"); //$NON-NLS-1$
     	switch (this.threadState) {
@@ -92,21 +79,20 @@
 	        		this.threadState = ThreadState.DONE;
 	        	} else {
 		    		this.threadState = ThreadState.IDLE;
-		    		return pauseProcessing();
+		    		pauseProcessing();
 	        	}
 	    		break;
 	    	case MORE_WORK:
 	    		if (isDoneProcessing()) {
 	    			logTrace("done processing - ignoring more"); //$NON-NLS-1$
 	        		this.threadState = ThreadState.DONE;
-	        	} else if (!this.useCallingThread) {
-        			resumeProcessing();
+	        	} else {
+	        		resumeProcessing();
 	        	}
 	    		break;
     		default:
     			throw new IllegalStateException("Should not END on " + this.threadState); //$NON-NLS-1$
     	}
-    	return useCallingThread;
     }
     
     protected boolean isIdle() {
@@ -117,8 +103,9 @@
     	moreWork(true);
     }
     
-    final protected synchronized void moreWork(boolean ignoreDone) {
+    protected synchronized void moreWork(boolean ignoreDone) {
     	logTrace("more work"); //$NON-NLS-1$
+    	this.notifyAll();
     	switch (this.threadState) {
 	    	case WORKING:
 	    		this.threadState = ThreadState.MORE_WORK;
@@ -127,15 +114,7 @@
 	    		break;
 	    	case IDLE:
 	    		this.threadState = ThreadState.MORE_WORK;
-        		if (this.useCallingThread) {
-        			if (isProcessing) {
-        				this.notifyAll(); //notify the waiting caller
-        			} else {
-        				run(); //restart with the calling thread
-        			}
-        		} else {
-        			resumeProcessing();
-        		}
+	    		resumeProcessing();
 	    		break;
 			default:
 				if (!ignoreDone) {
@@ -151,33 +130,8 @@
     
     protected abstract void process();
 
-	protected boolean pauseProcessing() {
-		if (useCallingThread && !shouldPause()) {
-			return false;
-		}
-		while (useCallingThread && this.getThreadState() == ThreadState.IDLE) {
-			try {
-				this.wait(); //the lock should already be held
-			} catch (InterruptedException e) {
-				interrupted(e);
-			}
-		}
-		return useCallingThread;
+	protected void pauseProcessing() {
 	}
-	
-	/**
-	 * only called for synch processing
-	 */
-	protected boolean shouldPause() {
-		return false;
-	}
-
-	/**
-	 * only called for synch processing
-	 */
-	protected void interrupted(InterruptedException e) {
-		throw new TeiidRuntimeException(e);
-	}
     
     protected abstract void resumeProcessing();
 	


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AbstractWorkItem.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidationVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,15 +28,17 @@
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import org.teiid.CommandContext;
+import org.teiid.PolicyDecider;
 import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.DataPolicy.Context;
 import org.teiid.adminapi.DataPolicy.PermissionType;
-import org.teiid.adminapi.impl.DataPolicyMetadata;
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.core.CoreConstants;
 import org.teiid.core.TeiidComponentException;
@@ -73,44 +75,19 @@
 
 public class AuthorizationValidationVisitor extends AbstractValidationVisitor {
     
-	public enum Context {
-		CREATE,
-		DROP,
-		QUERY,
-		INSERT,
-		UPDATE,
-		DELETE,
-		FUNCTION,
-		ALTER,
-		STORED_PROCEDURE;
-    }
-    
-    private HashMap<String, DataPolicy> allowedPolicies;
-    private String userName;
-    private boolean allowCreateTemporaryTablesDefault = true;
-    private boolean allowFunctionCallsByDefault = true;
+    private CommandContext commandContext;
+    private PolicyDecider decider;
 
-    public AuthorizationValidationVisitor(HashMap<String, DataPolicy> policies, String user) {
-        this.allowedPolicies = policies;
-        this.userName = user;
+    public AuthorizationValidationVisitor(PolicyDecider decider, CommandContext commandContext) {
+        this.decider = decider;
+        this.commandContext = commandContext;
     }
-    
-    public void setAllowCreateTemporaryTablesDefault(
-			boolean allowCreateTemporaryTablesDefault) {
-		this.allowCreateTemporaryTablesDefault = allowCreateTemporaryTablesDefault;
-	}
-    
-    public void setAllowFunctionCallsByDefault(boolean allowFunctionCallsDefault) {
-		this.allowFunctionCallsByDefault = allowFunctionCallsDefault;
-	}
 
     // ############### Visitor methods for language objects ##################
     
     @Override
     public void visit(Create obj) {
-    	Set<String> resources = Collections.singleton(obj.getTable().getName());
-    	Collection<GroupSymbol> symbols = Arrays.asList(obj.getTable());
-    	validateTemp(resources, symbols, Context.CREATE);
+    	validateTemp(PermissionType.CREATE, obj.getTable(), Context.CREATE);
     }
     
     @Override
@@ -128,46 +105,32 @@
     	validateEntitlements(Arrays.asList(obj.getTarget()), DataPolicy.PermissionType.ALTER, Context.ALTER);
     }
 
-	private void validateTemp(Set<String> resources,
-			Collection<GroupSymbol> symbols, Context context) {
+	private void validateTemp(DataPolicy.PermissionType action, GroupSymbol symbol, Context context) {
+		String resource = symbol.getNonCorrelationName();
+		Set<String> resources = Collections.singleton(resource);
 		logRequest(resources, context);
         
-    	boolean allowed = false;
-    	for(DataPolicy p:this.allowedPolicies.values()) {
-			DataPolicyMetadata policy = (DataPolicyMetadata)p;
-			
-			if (policy.isAllowCreateTemporaryTables() == null) {
-				if (allowCreateTemporaryTablesDefault) {
-					allowed = true;
-					break;
-				}
-			} else if (policy.isAllowCreateTemporaryTables()) {
-				allowed = true;
-				break;
-			}
-		}
+    	boolean allowed = decider.isTempAccessable(action, resource, context, commandContext);
     	
     	logResult(resources, context, allowed);
     	if (!allowed) {
 		    handleValidationError(
-			        QueryPlugin.Util.getString("ERR.018.005.0095", userName, "CREATE_TEMPORARY_TABLES"), //$NON-NLS-1$  //$NON-NLS-2$
-			        symbols);
+			        QueryPlugin.Util.getString("ERR.018.005.0095", commandContext.getUserName(), "CREATE_TEMPORARY_TABLES"), //$NON-NLS-1$  //$NON-NLS-2$
+			        Arrays.asList(symbol));
     	}
 	}
 
 	private void logRequest(Set<String> resources, Context context) {
 		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
 	        // Audit - request
-	    	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-request", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
+	    	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-request", resources.toArray(new String[resources.size()]), commandContext); //$NON-NLS-1$
 	    	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
         }
 	}
     
     @Override
     public void visit(Drop obj) {
-    	Set<String> resources = Collections.singleton(obj.getTable().getName());
-    	Collection<GroupSymbol> symbols = Arrays.asList(obj.getTable());
-    	validateTemp(resources, symbols, Context.CREATE);
+    	validateTemp(PermissionType.DROP, obj.getTable(), Context.DROP);
     }
     
     public void visit(Delete obj) {
@@ -204,7 +167,7 @@
 			} catch (TeiidProcessingException e) {
 				handleException(e, obj);
 			}
-    	} else if (!allowFunctionCallsByDefault) {
+    	} else {
     		String schema = obj.getFunctionDescriptor().getSchema();
     		if (schema != null && !isSystemSchema(schema)) {
     			Map<String, Function> map = new HashMap<String, Function>();
@@ -220,8 +183,11 @@
      * Validate insert entitlements
      */
     protected void validateEntitlements(Insert obj) {
+    	List<LanguageObject> insert = new LinkedList<LanguageObject>();
+    	insert.add(obj.getGroup());
+    	insert.addAll(obj.getVariables());
         validateEntitlements(
-            obj.getVariables(),
+        		insert,
             DataPolicy.PermissionType.CREATE,
             Context.INSERT);
     }
@@ -243,7 +209,10 @@
 
         // The variables from the changes must be checked for UPDATE entitlement
         // validateEntitlements on all the variables used in the update.
-        validateEntitlements(obj.getChangeList().getClauseMap().keySet(), DataPolicy.PermissionType.UPDATE, Context.UPDATE);
+        List<LanguageObject> updated = new LinkedList<LanguageObject>();
+        updated.add(obj.getGroup());
+        updated.addAll(obj.getChangeList().getClauseMap().keySet());
+        validateEntitlements(updated, DataPolicy.PermissionType.UPDATE, Context.UPDATE);
     }
 
     /**
@@ -270,9 +239,10 @@
         Into intoObj = obj.getInto();
         if ( intoObj != null ) {
             GroupSymbol intoGroup = intoObj.getGroup();
-            List<ElementSymbol> intoElements = null;
+            Collection<LanguageObject> intoElements = new LinkedList<LanguageObject>();
+            intoElements.add(intoGroup);
             try {
-                intoElements = ResolverUtil.resolveElementsInGroup(intoGroup, getMetadata());
+                intoElements.addAll(ResolverUtil.resolveElementsInGroup(intoGroup, getMetadata()));
             } catch (QueryMetadataException err) {
                 handleException(err, intoGroup);
             } catch (TeiidComponentException err) {
@@ -284,7 +254,7 @@
         }
 
         // Validate this query's entitlements
-        Collection entitledObjects = GroupCollectorVisitor.getGroups(obj, true);
+        Collection<LanguageObject> entitledObjects = new ArrayList<LanguageObject>(GroupCollectorVisitor.getGroupsIgnoreInlineViews(obj, true));
         if (!isXMLCommand(obj)) {
             entitledObjects.addAll(ElementCollectorVisitor.getElements(obj, true));
         }
@@ -311,7 +281,7 @@
      * @param auditContext The {@link AuthorizationService} to use when resource auditing is done.
      */
     protected void validateEntitlements(Collection<? extends LanguageObject> symbols, DataPolicy.PermissionType actionCode, Context auditContext) {
-        Map<String, LanguageObject> nameToSymbolMap = new HashMap<String, LanguageObject>();
+        Map<String, LanguageObject> nameToSymbolMap = new LinkedHashMap<String, LanguageObject>();
         for (LanguageObject symbol : symbols) {
             try {
                 String fullName = null;
@@ -325,6 +295,9 @@
                     GroupSymbol group = (GroupSymbol)symbol;
                     metadataID = group.getMetadataID();
                     if (metadataID instanceof TempMetadataID && !group.isProcedure()) {
+                    	if (group.isTempTable()) {
+                    		validateTemp(actionCode, group, auditContext);
+                    	}
                         continue;
                     }
                 }
@@ -367,32 +340,17 @@
 	    // is not authorized in the exception message
 	    
 	    handleValidationError(
-	        QueryPlugin.Util.getString("ERR.018.005.0095", userName, actionCode), //$NON-NLS-1$                    
+	        QueryPlugin.Util.getString("ERR.018.005.0095", commandContext.getUserName(), actionCode), //$NON-NLS-1$                    
 	        inaccessibleSymbols);
 	}
 
     /**
-     * Out of resources specified, return the subset for which the specified not have authorization to access.
+     * Out of the resources specified, return the subset for which the specified not have authorization to access.
      */
     public Set<String> getInaccessibleResources(DataPolicy.PermissionType action, Set<String> resources, Context context) {
         logRequest(resources, context);
         
-        HashSet<String> results = new HashSet<String>(resources);
-        
-		for(DataPolicy p:this.allowedPolicies.values()) {
-			DataPolicyMetadata policy = (DataPolicyMetadata)p;
-			
-			if (results.isEmpty()) {
-				break;
-			}
-			
-			Iterator<String> i = results.iterator();
-			while (i.hasNext()) {				
-				if (policy.allows(i.next(), action)) {
-					i.remove();
-				}
-			}
-		}
+		Set<String> results = decider.getInaccessibleResources(action, resources, context, commandContext);
 
 		logResult(resources, context, results.isEmpty());
         return results;
@@ -402,10 +360,10 @@
 			boolean granted) {
 		if (LogManager.isMessageToBeRecorded(LogConstants.CTX_AUDITLOGGING, MessageLevel.DETAIL)) {
 	        if (granted) {
-	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-granted all", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
+	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-granted all", resources.toArray(new String[resources.size()]), commandContext); //$NON-NLS-1$
 	        	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
 	        } else {
-	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-denied", this.userName, resources.toArray(new String[resources.size()])); //$NON-NLS-1$
+	        	AuditMessage msg = new AuditMessage(context.name(), "getInaccessibleResources-denied", resources.toArray(new String[resources.size()]), commandContext); //$NON-NLS-1$
 	        	LogManager.logDetail(LogConstants.CTX_AUDITLOGGING, msg);
 	        }
 		}

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/AuthorizationValidator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,14 +26,18 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.sql.lang.Command;
+import org.teiid.query.util.CommandContext;
 
 /**
  * Defines a validator that checks for proper authorization.  
  */
 public interface AuthorizationValidator {
 	
-	void validate(Command command, QueryMetadataInterface metadata,
-			DQPWorkContext workContext) throws QueryValidatorException, TeiidComponentException;
+	void validate(Command command, QueryMetadataInterface metadata, CommandContext commandContext) throws QueryValidatorException, TeiidComponentException;
 	
-	boolean hasRole(String roleName, DQPWorkContext workContext);
+	boolean hasRole(String roleName, CommandContext commandContext);
+	
+	boolean isEnabled();
+	
+	void setEnabled(boolean enabled);
 }

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/CachedResults.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/CachedResults.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/CachedResults.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,7 +41,6 @@
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.query.QueryPlugin;
-import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.parser.ParseInfo;
 import org.teiid.query.parser.QueryParser;
@@ -58,8 +57,6 @@
 	private transient Command command;
 	private transient TupleBuffer results;
 
-	private AnalysisRecord analysisRecord;
-
 	private String[] types;
 	private CacheHint hint;
 	private int batchSize;
@@ -73,14 +70,6 @@
 		return this.uuid;
 	}
 	
-	public AnalysisRecord getAnalysisRecord() {
-		return analysisRecord;
-	}
-	
-	public void setAnalysisRecord(AnalysisRecord analysisRecord) {
-		this.analysisRecord = analysisRecord;
-	}
-	
 	public TupleBuffer getResults() {
 		return results;
 	}
@@ -125,39 +114,48 @@
 
 	@Override
 	public synchronized boolean restore(Cache cache, BufferManager bufferManager) {
-		try {
-			if (this.results == null) {
-				if (this.hasLobs) {
-					return false;
-				}
+		if (this.results == null) {
+			if (this.hasLobs) {
+				return false; //the lob store is local only and not distributed
+			}
+			TupleBuffer buffer = null;
+			try {
 				List<ElementSymbol> schema = new ArrayList<ElementSymbol>(types.length);
 				for (String type : types) {
 					ElementSymbol es = new ElementSymbol("x"); //$NON-NLS-1$
 					es.setType(DataTypeManager.getDataTypeClass(type));
 					schema.add(es);
 				}
-				TupleBuffer buffer = bufferManager.createTupleBuffer(schema, "cached", TupleSourceType.FINAL); //$NON-NLS-1$
+				buffer = bufferManager.createTupleBuffer(schema, "cached", TupleSourceType.FINAL); //$NON-NLS-1$
 				buffer.setBatchSize(this.batchSize);
+				buffer.setId(this.uuid);
 				if (this.hint != null) {
 					buffer.setPrefersMemory(this.hint.getPrefersMemory());
 				}
 				
 				for (int row = 1; row <= this.rowCount; row+=this.batchSize) {
 					TupleBatch batch = (TupleBatch)cache.get(uuid+","+row); //$NON-NLS-1$
-					if (batch != null) {					
-						buffer.addTupleBatch(batch, true);
-					}					
+					if (batch == null) {					
+						LogManager.logInfo(LogConstants.CTX_DQP, QueryPlugin.Util.getString("not_found_cache")); //$NON-NLS-1$
+						buffer.remove();
+						return false;
+					}		
+					buffer.addTupleBatch(batch, true);
+					cache.remove(uuid+","+row); //$NON-NLS-1$
 				}
 				this.results = buffer;	
 				bufferManager.addTupleBuffer(this.results);
 				this.results.close();
+				this.accessInfo.restore();
+			} catch (TeiidException e) {
+				LogManager.logWarning(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("unexpected_exception_restoring_results")); //$NON-NLS-1$
+				if (buffer != null) {
+					buffer.remove();
+				}
+				return false;
 			}
-			this.accessInfo.restore();
-			return true;
-		} catch (TeiidException e) {
-			LogManager.logDetail(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("not_found_cache")); //$NON-NLS-1$
 		}
-		return false;
+		return true;
 	}	
 	
 	@Override

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPConfiguration.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,7 +23,6 @@
 
 import org.teiid.cache.CacheConfiguration;
 import org.teiid.client.RequestMessage;
-import org.teiid.metadata.MetadataRepository;
 
 
 public class DQPConfiguration{
@@ -123,38 +122,15 @@
      * @return <code>true</code> if server-side role checking is enabled.
      */
     public boolean getUseDataRoles() {
-        return useDataRoles;
+        return this.authorizationValidator != null && this.authorizationValidator.isEnabled();
     }
 
 	public void setUseDataRoles(boolean useEntitlements) {
-		this.useDataRoles = useEntitlements;
+		if (this.authorizationValidator != null) {
+			this.authorizationValidator.setEnabled(useEntitlements);
+		}
 	}
 
-	/**
-     * Whether temporary table usage is enabled by default.
-     * @return <code>true</code> if temporary table usage is enabled by default.
-     */
-    public boolean isAllowCreateTemporaryTablesByDefault() {
-		return allowCreateTemporaryTablesByDefault;
-	}
-	
-	public void setAllowCreateTemporaryTablesByDefault(
-			boolean allowCreateTemporaryTablesByDefault) {
-		this.allowCreateTemporaryTablesByDefault = allowCreateTemporaryTablesByDefault;
-	}
-	
-	/**
-     * Whether functions are callable by default
-     * @return <code>true</code> if function usage is enabled by default.
-     */
-    public boolean isAllowFunctionCallsByDefault() {
-		return allowFunctionCallsByDefault;
-	}
-	
-    public void setAllowFunctionCallsByDefault(boolean allowFunctionCallsDefault) {
-		this.allowFunctionCallsByDefault = allowFunctionCallsDefault;
-	}
-	
 	public int getQueryThresholdInSecs() {
 		return queryThresholdInSecs;
 	}
@@ -204,10 +180,6 @@
 		this.authorizationValidator = authorizationValidator;
 	}
 	
-	public MetadataRepository getMetadataRepository() {
-		return null;
-	}
-	
 	public CacheConfiguration getPreparedPlanCacheConfig() {
 		return preparedPlanCacheConfig;
 	}

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPCore.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,6 +28,7 @@
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.FutureTask;
@@ -43,10 +44,11 @@
 import org.teiid.adminapi.impl.CacheStatisticsMetadata;
 import org.teiid.adminapi.impl.RequestMetadata;
 import org.teiid.adminapi.impl.TransactionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
 import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
 import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.CacheConfiguration.Policy;
 import org.teiid.cache.CacheFactory;
-import org.teiid.cache.CacheConfiguration.Policy;
 import org.teiid.client.DQP;
 import org.teiid.client.RequestMessage;
 import org.teiid.client.ResultsMessage;
@@ -58,24 +60,29 @@
 import org.teiid.client.xa.XidImpl;
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.Streamable;
+import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
 import org.teiid.dqp.internal.process.ThreadReuseExecutor.PrioritizedRunnable;
 import org.teiid.dqp.message.AtomicRequestMessage;
 import org.teiid.dqp.message.RequestID;
 import org.teiid.dqp.service.BufferService;
 import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionContext.Scope;
 import org.teiid.dqp.service.TransactionService;
-import org.teiid.dqp.service.TransactionContext.Scope;
 import org.teiid.events.EventDistributor;
 import org.teiid.logging.CommandLogMessage;
+import org.teiid.logging.CommandLogMessage.Event;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.logging.MessageLevel;
-import org.teiid.logging.CommandLogMessage.Event;
 import org.teiid.metadata.MetadataRepository;
 import org.teiid.query.QueryPlugin;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.optimizer.relational.RelationalPlanner;
 import org.teiid.query.tempdata.TempTableDataManager;
 import org.teiid.query.tempdata.TempTableStore;
 
@@ -94,9 +101,11 @@
 		private long creationTime = System.currentTimeMillis();
 		private DQPWorkContext workContext = DQPWorkContext.getWorkContext();
 		private List<CompletionListener<T>> completionListeners = new LinkedList<CompletionListener<T>>();
+		private String parentName;
 
 		public FutureWork(final Callable<T> processor, int priority) {
 			super(processor);
+			this.parentName = Thread.currentThread().getName();
 			this.priority = priority;
 		}
 		
@@ -106,6 +115,12 @@
 		}
 		
 		@Override
+		public void run() {
+			LogManager.logDetail(LogConstants.CTX_DQP, "Running task for parent thread", parentName); //$NON-NLS-1$
+			super.run();
+		}
+		
+		@Override
 		public int getPriority() {
 			return priority;
 		}
@@ -166,9 +181,12 @@
 				requests.remove(requestID);
 			}
 		}
-		
 	}
 	
+	public static interface ContextProvider {
+		DQPWorkContext getContext(String vdbName, int vdbVersion);
+	}
+	
 	private ThreadReuseExecutor processWorkerPool;
     
     // Resources
@@ -345,6 +363,7 @@
 			}
 		}
         if (runInThread) {
+        	workItem.useCallingThread = true;
         	workItem.run();
         }
         return resultsFuture;
@@ -674,9 +693,6 @@
 	public void start(DQPConfiguration config) {
 		this.config = config;
         this.authorizationValidator = config.getAuthorizationValidator();
-        if (this.authorizationValidator == null) {
-        	this.authorizationValidator = new DataRoleAuthorizationValidator(config.getUseDataRoles(), config.isAllowCreateTemporaryTablesByDefault(), config.isAllowFunctionCallsByDefault());
-        }
         this.chunkSize = config.getLobChunkSizeInKB() * 1024;
 
         //get buffer manager
@@ -725,8 +741,92 @@
         processorDataManager.setMetadataRepository(metadataRepository);
 		dataTierMgr = new TempTableDataManager(processorDataManager, this.bufferManager, this.processWorkerPool, this.rsCache, this.matTables, this.cacheFactory);
         dataTierMgr.setEventDistributor(eventDistributor);
+                
+        LogManager.logDetail(LogConstants.CTX_DQP, "DQPCore started maxThreads", this.config.getMaxThreads(), "maxActivePlans", this.maxActivePlans, "source concurrency", this.userRequestSourceConcurrency); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 	}
 	
+	public void synchronizeInternalMaterializedViews(final ContextProvider contextProvider) {
+        if (!cacheFactory.isReplicated() || matTables == null) {
+        	return;
+        }
+        Set<CacheID> keys = this.matTables.replicatableKeys();
+        for (final CacheID key:keys) {
+        	refreshMatView(contextProvider, key.getVDBKey().getName(), key.getVDBKey().getVersion(), key.getSql());
+        }
+	}
+	
+	public void refreshMatView(final ContextProvider contextProvider, final String vdbName, final int vdbVersion, final String viewName) {
+        if (!cacheFactory.isReplicated() || matTables == null) {
+        	return;
+        }
+        
+        final DQPWorkContext context = contextProvider.getContext(vdbName, vdbVersion); 
+        
+		final VDBMetaData vdb = context.getVDB();
+		if (vdb == null) {
+			return;
+		}
+		
+		final TempTableStore globalStore = vdb.getAttachment(TempTableStore.class);
+		if (globalStore == null) {
+			return;
+		}        
+		DQPWorkContext.setWorkContext(context);
+		
+		Runnable work = new Runnable() {
+			@Override
+			public void run() {
+				QueryMetadataInterface metadata = vdb.getAttachment(QueryMetadataInterface.class);
+				TempTableStore tempStore = new TempTableStore("internal"); //$NON-NLS-1$
+				TempMetadataAdapter tma = new TempMetadataAdapter(metadata, tempStore.getMetadataStore());
+				try {
+					dataTierMgr.refreshMatView(vdb.getName(), vdb.getVersion(), viewName, tma, globalStore);
+				} catch (TeiidException e) {
+					LogManager.logError(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("error_refresh", viewName )); //$NON-NLS-1$
+				}						
+			}
+		};
+		addWork(work);
+	}
+	
+	public void updateMatViewRow(final ContextProvider contextProvider, final String vdbName, final int vdbVersion, final String schema,
+			final String viewName, final List<?> tuple, final boolean delete) {
+		
+        if (!cacheFactory.isReplicated() || matTables == null) {
+        	return;
+        }
+        
+        final DQPWorkContext context = contextProvider.getContext(vdbName, vdbVersion); 
+        
+		final VDBMetaData vdb = context.getVDB();
+		if (vdb == null) {
+			return;
+		}
+		
+		final TempTableStore globalStore = vdb.getAttachment(TempTableStore.class);
+		if (globalStore == null) {
+			return;
+		}        
+		
+		Runnable work = new Runnable() {
+			@Override
+			public void run() {
+				context.runInContext(new Runnable() {
+					@Override
+					public void run() {
+						try {
+							dataTierMgr.updateMatViewRow(globalStore, RelationalPlanner.MAT_PREFIX + (schema + '.' + viewName).toUpperCase(), tuple, delete);
+						} catch (TeiidException e) {
+							LogManager.logError(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("DQPCore.unable_to_process_event")); //$NON-NLS-1$
+						}					
+					}
+				});
+			}
+		};
+		addWork(work);		
+		
+	}
+
 	public void setBufferService(BufferService service) {
 		this.bufferService = service;
 	}
@@ -918,5 +1018,4 @@
 	SessionAwareCache<PreparedPlan> getPrepPlanCache() {
 		return prepPlanCache;
 	}
-	
 }
\ No newline at end of file

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -188,11 +188,8 @@
 	}
 	
 	public void runInContext(final Runnable runnable) {
-		DQPWorkContext.setWorkContext(this);
-		boolean associated = false;
-		if (securityHelper != null && this.getSubject() != null) {
-			associated = securityHelper.assosiateSecurityContext(this.getSecurityDomain(), this.getSecurityContext());			
-		}
+		DQPWorkContext previous = DQPWorkContext.getWorkContext();
+		boolean associated = attachDQPWorkContext();
 		try {
 			runnable.run();
 		} finally {
@@ -200,9 +197,21 @@
 				securityHelper.clearSecurityContext(this.getSecurityDomain());			
 			}
 			DQPWorkContext.releaseWorkContext();
+			if (previous != null) {
+				previous.attachDQPWorkContext();
+			}
 		}
 	}
 
+	private boolean attachDQPWorkContext() {
+		DQPWorkContext.setWorkContext(this);
+		boolean associated = false;
+		if (securityHelper != null && this.getSubject() != null) {
+			associated = securityHelper.assosiateSecurityContext(this.getSecurityDomain(), this.getSecurityContext());			
+		}
+		return associated;
+	}
+
 	public HashMap<String, DataPolicy> getAllowedDataPolicies() {
 		if (this.policies == null) {
 	    	this.policies = new HashMap<String, DataPolicy>();
@@ -217,6 +226,10 @@
 		}
         return this.policies;
     }
+	
+	public void setPolicies(HashMap<String, DataPolicy> policies) {
+		this.policies = policies;
+	}
     
 	private boolean matchesPrincipal(Set<String> userRoles, DataPolicy policy) {
 		if (policy.isAnyAuthenticated()) {


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DQPWorkContext.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Deleted: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRoleAuthorizationValidator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,64 +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 org.teiid.dqp.internal.process;
-
-import org.teiid.api.exception.query.QueryValidatorException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.sql.lang.Command;
-
-/**
- * The default Teiid authorization validator
- */
-public class DataRoleAuthorizationValidator implements AuthorizationValidator {
-	
-	private boolean useEntitlements;
-	private boolean allowCreateTemporaryTablesByDefault;
-	private boolean allowFunctionCallsByDefault;
-	
-	public DataRoleAuthorizationValidator(boolean useEntitlements,
-			boolean allowCreateTemporaryTablesByDefault, boolean allowFunctionCallsByDefault) {
-		this.useEntitlements = useEntitlements;
-		this.allowCreateTemporaryTablesByDefault = allowCreateTemporaryTablesByDefault;
-		this.allowFunctionCallsByDefault = allowFunctionCallsByDefault;
-	}
-
-	@Override
-	public void validate(Command command, QueryMetadataInterface metadata, DQPWorkContext workContext) throws QueryValidatorException, TeiidComponentException {
-		if (useEntitlements && !workContext.getVDB().getDataPolicies().isEmpty()) {
-			AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(workContext.getAllowedDataPolicies(), workContext.getUserName());
-			visitor.setAllowCreateTemporaryTablesDefault(allowCreateTemporaryTablesByDefault);
-			visitor.setAllowFunctionCallsByDefault(allowFunctionCallsByDefault);
-			Request.validateWithVisitor(visitor, metadata, command);
-		}		
-	}
-	
-	@Override
-	public boolean hasRole(String roleName, DQPWorkContext workContext) {
-		if (!useEntitlements) {
-			return true;
-		}
-		return workContext.getAllowedDataPolicies().containsKey(roleName);
-	}
-
-}

Copied: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRolePolicyDecider.java (from rev 3382, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DataRolePolicyDecider.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRolePolicyDecider.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataRolePolicyDecider.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,76 @@
+package org.teiid.dqp.internal.process;
+
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import org.teiid.CommandContext;
+import org.teiid.PolicyDecider;
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.DataPolicy.Context;
+import org.teiid.adminapi.DataPolicy.PermissionType;
+import org.teiid.adminapi.impl.DataPolicyMetadata;
+
+public class DataRolePolicyDecider implements PolicyDecider {
+
+    private boolean allowCreateTemporaryTablesByDefault = true;
+    private boolean allowFunctionCallsByDefault = true;
+
+	@Override
+	public Set<String> getInaccessibleResources(PermissionType action,
+			Set<String> resources, Context context, CommandContext commandContext) {
+		if (action == PermissionType.EXECUTE && context == Context.FUNCTION && allowFunctionCallsByDefault) {
+			return Collections.emptySet();
+		}
+		LinkedHashSet<String> results = new LinkedHashSet<String>(resources);
+		for(DataPolicy p:commandContext.getAllowedDataPolicies().values()) {
+			DataPolicyMetadata policy = (DataPolicyMetadata)p;
+			
+			if (results.isEmpty()) {
+				break;
+			}
+			
+			Iterator<String> i = results.iterator();
+			while (i.hasNext()) {				
+				if (policy.allows(i.next(), action)) {
+					i.remove();
+				}
+			}
+		}
+		return results;
+	}
+
+	@Override
+	public boolean hasRole(String roleName, CommandContext context) {
+		return context.getAllowedDataPolicies().containsKey(roleName);
+	}
+
+	@Override
+	public boolean isTempAccessable(PermissionType action, String resource,
+			Context context, CommandContext commandContext) {
+    	for(DataPolicy p:commandContext.getAllowedDataPolicies().values()) {
+			DataPolicyMetadata policy = (DataPolicyMetadata)p;
+			
+			if (policy.isAllowCreateTemporaryTables() != null) {
+				return policy.isAllowCreateTemporaryTables();
+			}
+		}
+    	return allowCreateTemporaryTablesByDefault;
+	}
+	
+    public void setAllowCreateTemporaryTablesByDefault(
+			boolean allowCreateTemporaryTablesByDefault) {
+		this.allowCreateTemporaryTablesByDefault = allowCreateTemporaryTablesByDefault;
+	}
+    
+    public void setAllowFunctionCallsByDefault(boolean allowFunctionCallsDefault) {
+		this.allowFunctionCallsByDefault = allowFunctionCallsDefault;
+	}
+    
+    @Override
+    public boolean validateCommand(CommandContext commandContext) {
+    	return !commandContext.getVdb().getDataPolicies().isEmpty();
+    }
+
+}

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,6 +33,7 @@
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.TreeMap;
 
 import javax.sql.rowset.serial.SerialClob;
 
@@ -60,6 +61,8 @@
 import org.teiid.dqp.message.RequestID;
 import org.teiid.dqp.service.BufferService;
 import org.teiid.events.EventDistributor;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
 import org.teiid.metadata.AbstractMetadataRecord;
 import org.teiid.metadata.Column;
 import org.teiid.metadata.ColumnStats;
@@ -120,13 +123,34 @@
 	private enum SystemAdminProcs {
 		SETTABLESTATS,
 		SETCOLUMNSTATS,
-		SETPROPERTY
+		SETPROPERTY,
+		LOGMSG,
+		ISLOGGABLE
 	}
 	
 	private enum SystemProcs {
 		GETXMLSCHEMAS
 	}
 	
+	private static final TreeMap<String, Integer> levelMap = new TreeMap<String, Integer>(String.CASE_INSENSITIVE_ORDER);
+	static {
+		levelMap.put("OFF", MessageLevel.NONE); //$NON-NLS-1$
+		levelMap.put("FATAL", MessageLevel.CRITICAL); //$NON-NLS-1$
+		levelMap.put("ERROR", MessageLevel.ERROR); //$NON-NLS-1$
+		levelMap.put("WARN", MessageLevel.WARNING); //$NON-NLS-1$
+		levelMap.put("INFO", MessageLevel.INFO); //$NON-NLS-1$
+		levelMap.put("DEBUG", MessageLevel.DETAIL); //$NON-NLS-1$
+		levelMap.put("TRACE", MessageLevel.TRACE); //$NON-NLS-1$
+	}
+	
+	public static int getLevel(String level) throws TeiidProcessingException {
+		Integer intLevel = levelMap.get(level);
+		if (intLevel == null) {
+			throw new TeiidProcessingException(QueryPlugin.Util.getString("FunctionMethods.unknown_level", level, levelMap.keySet())); //$NON-NLS-1$
+		}
+		return intLevel;
+	}
+	
 	// Resources
 	private DQPCore requestMgr;
     private BufferService bufferService;
@@ -361,6 +385,26 @@
 			if (StringUtil.startsWithIgnoreCase(proc.getProcedureCallableName(), CoreConstants.SYSTEM_ADMIN_MODEL)) {
 				final SystemAdminProcs sysProc = SystemAdminProcs.valueOf(proc.getProcedureCallableName().substring(CoreConstants.SYSTEM_ADMIN_MODEL.length() + 1).toUpperCase());
 				switch (sysProc) {
+				case LOGMSG:
+				case ISLOGGABLE:
+					String level = (String)((Constant)proc.getParameter(2).getExpression()).getValue();
+					String logContext = (String)((Constant)proc.getParameter(3).getExpression()).getValue();
+					Object message = null;
+					if (sysProc == SystemAdminProcs.LOGMSG) {
+						message = ((Constant)proc.getParameter(4).getExpression()).getValue();
+					}
+					int msgLevel = getLevel(level);
+					boolean logged = false;
+					if (LogManager.isMessageToBeRecorded(logContext, msgLevel)) {
+						if (message != null) {
+							LogManager.log(msgLevel, logContext, message);
+						}
+						logged = true;
+					}
+					if (proc.returnParameters()) {
+						rows.add(Arrays.asList(logged));
+					}
+					return new CollectionTupleSource(rows.iterator());
 				case SETPROPERTY:
 					try {
 						String uuid = (String)((Constant)proc.getParameter(2).getExpression()).getValue();
@@ -385,10 +429,12 @@
 						if (eventDistributor != null) {
 							eventDistributor.setProperty(vdbName, vdbVersion, uuid, key, strVal);
 						}
-						if (result == null) {
-							rows.add(Arrays.asList((Clob)null));
-						} else {
-							rows.add(Arrays.asList(new ClobType(new SerialClob(result.toCharArray()))));
+						if (proc.returnParameters()) {
+							if (result == null) {
+								rows.add(Arrays.asList((Clob)null));
+							} else {
+								rows.add(Arrays.asList(new ClobType(new SerialClob(result.toCharArray()))));
+							}
 						}
 						return new CollectionTupleSource(rows.iterator());
 					} catch (SQLException e) {


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierManagerImpl.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -244,7 +244,7 @@
 							workItem.moreWork();
     					}
     				}, 10, e.getRetryDelay());
-    				throw BlockedException.INSTANCE;
+    				throw BlockedException.block(aqr.getAtomicRequestID(), "Blocking on DataNotAvailableException"); //$NON-NLS-1$
     			} 
     			receiveResults(results);
     		}
@@ -295,7 +295,7 @@
 			addWork();
 		}
 		if (!futureResult.isDone()) {
-			throw BlockedException.INSTANCE;
+			throw BlockedException.block(aqr.getAtomicRequestID(), "Blocking on source query"); //$NON-NLS-1$
 		}
 		FutureWork<AtomicResultsMessage> currentResults = futureResult;
 		futureResult = null;
@@ -409,7 +409,7 @@
 		if (exception.getCause() instanceof TeiidProcessingException) {
 			throw (TeiidProcessingException)exception.getCause();
 		}
-		throw new TeiidProcessingException(exception);
+		throw new TeiidProcessingException(exception, this.getConnectorName() + ": " + exception.getMessage()); //$NON-NLS-1$
 	}
 
 	void receiveResults(AtomicResultsMessage response) {


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DataTierTupleSource.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Copied: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DefaultAuthorizationValidator.java (from rev 3382, trunk/engine/src/main/java/org/teiid/dqp/internal/process/DefaultAuthorizationValidator.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DefaultAuthorizationValidator.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/DefaultAuthorizationValidator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,77 @@
+/*
+ * 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 org.teiid.dqp.internal.process;
+
+import org.teiid.PolicyDecider;
+import org.teiid.api.exception.query.QueryValidatorException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.util.CommandContext;
+
+/**
+ * The default Teiid authorization validator
+ */
+public class DefaultAuthorizationValidator implements AuthorizationValidator {
+	
+	private boolean enabled = true;
+	private PolicyDecider policyDecider;
+	
+	public DefaultAuthorizationValidator() {
+	}
+
+	@Override
+	public void validate(Command command, QueryMetadataInterface metadata, CommandContext commandContext) throws QueryValidatorException, TeiidComponentException {
+		if (enabled && policyDecider.validateCommand(commandContext)) {
+			AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(this.policyDecider, commandContext);
+			Request.validateWithVisitor(visitor, metadata, command);
+		}		
+	}
+	
+	@Override
+	public boolean hasRole(String roleName, CommandContext commandContext) {
+		if (!enabled) {
+			return true;
+		}
+		return this.policyDecider.hasRole(roleName, commandContext);
+	}
+	
+	public void setPolicyDecider(PolicyDecider policyDecider) {
+		this.policyDecider = policyDecider;
+	}
+	
+	public PolicyDecider getPolicyDecider() {
+		return policyDecider;
+	}
+	
+	@Override
+	public boolean isEnabled() {
+		return enabled;
+	}
+	
+	@Override
+	public void setEnabled(boolean enabled) {
+		this.enabled = enabled;
+	}
+	
+}


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/LobWorkItem.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/MetaDataProcessor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/MetaDataProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/MetaDataProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -58,6 +58,7 @@
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.query.sql.symbol.AggregateSymbol.Type;
 import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
 import org.teiid.query.tempdata.TempTableStore;
@@ -180,12 +181,12 @@
             this.metadata = tempFacade; 
         }
         
-        List projectedSymbols = originalCommand.getProjectedSymbols();
+        List<SingleElementSymbol> projectedSymbols = originalCommand.getProjectedSymbols();
         columnMetadata = new Map[projectedSymbols.size()];
         
-        Iterator symbolIter = projectedSymbols.iterator();
+        Iterator<SingleElementSymbol> symbolIter = projectedSymbols.iterator();
         for(int i=0; symbolIter.hasNext(); i++) {
-            SingleElementSymbol symbol = (SingleElementSymbol) symbolIter.next();
+            SingleElementSymbol symbol = symbolIter.next();
             String shortColumnName = SingleElementSymbol.getShortName(symbol.getOutputName());
             if(symbol instanceof AliasSymbol) {
                 symbol = ((AliasSymbol)symbol).getSymbol();
@@ -231,6 +232,8 @@
             return createElementMetadata(label, (ElementSymbol) symbol);        
         } else if(symbol instanceof AggregateSymbol) {
             return createAggregateMetadata(label, (AggregateSymbol) symbol);
+        } else if (symbol instanceof WindowFunction) {
+        	return createAggregateMetadata(label, ((WindowFunction) symbol).getFunction());
         }
         return createTypedMetadata(label, symbol);            
     }
@@ -387,6 +390,10 @@
 
     public Map<Integer, Object> getDefaultColumn(String tableName, String columnName, 
         Class<?> javaType) {
+    	return getDefaultColumn(tableName, columnName, columnName, javaType);
+    }
+    
+    public Map<Integer, Object> getDefaultColumn(String tableName, String columnName, String columnLabel, Class<?> javaType ) {
             
         Map<Integer, Object> column = new HashMap<Integer, Object>();
         
@@ -395,7 +402,7 @@
         column.put(ResultsMetadataConstants.VIRTUAL_DATABASE_VERSION, vdbVersion);
         column.put(ResultsMetadataConstants.GROUP_NAME, tableName);
         column.put(ResultsMetadataConstants.ELEMENT_NAME, columnName);
-        column.put(ResultsMetadataConstants.ELEMENT_LABEL, columnName);
+        column.put(ResultsMetadataConstants.ELEMENT_LABEL, columnLabel);
         column.put(ResultsMetadataConstants.AUTO_INCREMENTING, Boolean.FALSE);
         column.put(ResultsMetadataConstants.CASE_SENSITIVE, Boolean.FALSE);
         column.put(ResultsMetadataConstants.NULLABLE, ResultsMetadataConstants.NULL_TYPES.NULLABLE);  


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/MetaDataProcessor.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -158,8 +158,6 @@
             processPlan = cachedPlan.clone();
             //already in cache. obtain the values from cache
             analysisRecord = prepPlan.getAnalysisRecord();
-            
-            createCommandContext();
         }
         
         if (requestMsg.isBatchedUpdate()) {


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/PreparedStatementRequest.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/Request.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/Request.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,7 +43,6 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.id.IDGenerator;
-import org.teiid.core.id.IntegerIDFactory;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.util.Assertion;
 import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
@@ -150,7 +149,6 @@
         this.processorDataManager = processorDataManager;
         this.transactionService = transactionService;
         this.tempTableStore = tempTableStore;
-        idGenerator.setDefaultFactory(new IntegerIDFactory());
         this.workContext = workContext;
         this.requestId = workContext.getRequestID(this.requestMsg.getExecutionId());
         this.connectorManagerRepo = workContext.getVDB().getAttachment(ConnectorManagerRepository.class);
@@ -205,9 +203,9 @@
         this.metadata = tma;
     }
     
-    protected void createCommandContext() throws QueryValidatorException {
-    	boolean returnsResultSet = userCommand.returnsResultSet();
-    	this.returnsUpdateCount = !(userCommand instanceof StoredProcedure) && !returnsResultSet;
+    protected void createCommandContext(Command command) throws QueryValidatorException {
+    	boolean returnsResultSet = command.returnsResultSet();
+    	this.returnsUpdateCount = !(command instanceof StoredProcedure) && !returnsResultSet;
     	if ((this.requestMsg.getResultsMode() == ResultsMode.UPDATECOUNT && !returnsUpdateCount) 
     			|| (this.requestMsg.getResultsMode() == ResultsMode.RESULTSET && !returnsResultSet)) {
         	throw new QueryValidatorException(QueryPlugin.Util.getString(this.requestMsg.getResultsMode()==ResultsMode.RESULTSET?"Request.no_result_set":"Request.result_set")); //$NON-NLS-1$ //$NON-NLS-2$
@@ -252,6 +250,11 @@
         context.setResultSetCacheEnabled(this.resultSetCacheEnabled);
         context.setUserRequestSourceConcurrency(this.userRequestConcurrency);
         context.setSubject(workContext.getSubject());
+        this.context.setSession(workContext.getSession());
+        this.context.setRequestId(this.requestId);
+        this.context.setDQPWorkContext(this.workContext);
+        this.context.setTransactionService(this.transactionService);
+        this.context.setTransactionContext(this.transactionContext);
     }
     
     @Override
@@ -260,7 +263,10 @@
         if (!DATA_ROLE.equalsIgnoreCase(roleType)) {
             return false;
         }
-        return authorizationValidator.hasRole(roleName, workContext);
+        if (this.authorizationValidator == null) {
+        	return true;
+        }
+        return authorizationValidator.hasRole(roleName, context);
     }
     
     public void setUserRequestConcurrency(int userRequestConcurrency) {
@@ -381,11 +387,9 @@
         this.analysisRecord = new AnalysisRecord(requestMsg.getShowPlan() != ShowPlan.OFF, requestMsg.getShowPlan() == ShowPlan.DEBUG);
                 
         resolveCommand(command);
-        
+
         validateAccess(userCommand);
         
-        createCommandContext();
-
         Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(command, true);
         for (GroupSymbol groupSymbol : groups) {
 			if (groupSymbol.isTempTable()) {
@@ -464,7 +468,10 @@
 	}
 
 	protected void validateAccess(Command command) throws QueryValidatorException, TeiidComponentException {
-		this.authorizationValidator.validate(command, metadata, workContext);
+		createCommandContext(command);
+		if (this.authorizationValidator != null) {
+			this.authorizationValidator.validate(command, metadata, context);
+		}
 	}
 	
 }


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/Request.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -58,6 +58,7 @@
 import org.teiid.dqp.service.TransactionContext;
 import org.teiid.dqp.service.TransactionService;
 import org.teiid.dqp.service.TransactionContext.Scope;
+import org.teiid.jdbc.SQLStates;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.logging.MessageLevel;
@@ -161,8 +162,10 @@
     /**The time when command begins processing on the server.*/
     private long processingTimestamp = System.currentTimeMillis();
     
+    protected boolean useCallingThread;
+    private volatile boolean hasThread;
+    
     public RequestWorkItem(DQPCore dqpCore, RequestMessage requestMsg, Request request, ResultsReceiver<ResultsMessage> receiver, RequestID requestID, DQPWorkContext workContext) {
-    	super(workContext.useCallingThread() || requestMsg.isSync());
         this.requestMsg = requestMsg;
         this.requestID = requestID;
         this.processorTimeslice = dqpCore.getProcessorTimeSlice();
@@ -195,24 +198,65 @@
 	protected boolean isDoneProcessing() {
 		return isClosed;
 	}
+		
+	@Override
+	public void run() {
+		hasThread = true;
+		try {
+			while (!isDoneProcessing()) {
+				super.run();
+				if (!useCallingThread) {
+					break;
+				}
+				//should use the calling thread
+				synchronized (this) {
+					if (this.resultsReceiver == null) {
+						break; //allow results to be processed by calling thread
+					}
+					if (this.getThreadState() == ThreadState.MORE_WORK) {
+						continue;
+					}
+					try {
+						wait();
+					} catch (InterruptedException e) {
+						try {
+							requestCancel();
+						} catch (TeiidComponentException e1) {
+							throw new TeiidRuntimeException(e1);
+						}
+					}
+				}
+			}
+		} finally {
+			hasThread = false;
+		}
+	}
 
 	@Override
 	protected void resumeProcessing() {
-		if (doneProducingBatches && !closeRequested && !isCanceled) {
-			this.run(); // just run in the IO thread
-		} else {
+		if (!this.useCallingThread) {
 			dqpCore.addWork(this);
 		}
 	}
 	
-	@Override
-	protected void interrupted(InterruptedException e) {
-		try {
-			this.requestCancel();
-		} catch (TeiidComponentException e1) {
-			throw new TeiidRuntimeException(e1);
+	/**
+	 * Special call from request threads to allow resumption of processing by
+	 * the calling thread.
+	 */
+	public void doMoreWork() {
+		boolean run = false;
+		synchronized (this) {
+			moreWork();
+			if (!useCallingThread || this.getThreadState() != ThreadState.MORE_WORK) {
+				return;
+			}
+			run = !hasThread;
 		}
-		super.interrupted(e);
+		if (run) {
+			//run outside of the lock
+			LogManager.logDetail(LogConstants.CTX_DQP, "Restarting processing using the calling thread", requestID); //$NON-NLS-1$
+			run();
+		}
 	}
 	
 	@Override
@@ -223,7 +267,7 @@
                 state = ProcessingState.PROCESSING;
         		processNew();
                 if (isCanceled) {
-                	this.processingException = new TeiidProcessingException(QueryPlugin.Util.getString("QueryProcessor.request_cancelled", this.requestID)); //$NON-NLS-1$
+                	this.processingException = new TeiidProcessingException(SQLStates.QUERY_CANCELED, QueryPlugin.Util.getString("QueryProcessor.request_cancelled", this.requestID)); //$NON-NLS-1$
                     state = ProcessingState.CLOSE;
                 } 
         	}
@@ -292,10 +336,12 @@
 	}
 
 	private void suspend() {
-		try {
-			this.transactionService.suspend(this.transactionContext);
-		} catch (XATransactionException e) {
-			LogManager.logDetail(LogConstants.CTX_DQP, e, "Error suspending active transaction"); //$NON-NLS-1$
+		if ((this.transactionState != TransactionState.NONE) && this.transactionContext.getTransaction() != null) {
+			try {
+				this.transactionService.suspend(this.transactionContext);
+			} catch (XATransactionException e) {
+				LogManager.logDetail(LogConstants.CTX_DQP, e, "Error suspending active transaction"); //$NON-NLS-1$
+			}
 		}
 	}
 
@@ -410,7 +456,6 @@
 					CachedResults cr = rsCache.get(cacheId);
 					if (cr != null) {
 						this.resultsBuffer = cr.getResults();
-						this.analysisRecord = cr.getAnalysisRecord();
 						request.initMetadata();
 						this.originalCommand = cr.getCommand(requestMsg.getCommandString(), request.metadata, pi);
 						request.validateAccess(this.originalCommand);
@@ -442,15 +487,17 @@
 					doneProducingBatches();
 				}
 				addToCache();
-				add = sendResultsIfNeeded(batch);
-				if (!added) {
-					super.flushBatchDirect(batch, add);
-					//restrict the buffer size for forward only results
-					if (add && !processor.hasFinalBuffer()
-							&& !batch.getTerminationFlag() 
-							&& this.getTupleBuffer().getManagedRowCount() >= 20 * this.getTupleBuffer().getBatchSize()) {
-						//requestMore will trigger more processing
-						throw BlockedException.INSTANCE;
+				synchronized (lobStreams) {
+					add = sendResultsIfNeeded(batch);
+					if (!added) {
+						super.flushBatchDirect(batch, add);
+						//restrict the buffer size for forward only results
+						if (add && !processor.hasFinalBuffer()
+								&& !batch.getTerminationFlag() 
+								&& this.getTupleBuffer().getManagedRowCount() >= 20 * this.getTupleBuffer().getBatchSize()) {
+							//requestMore will trigger more processing
+							throw BlockedException.block(requestID, "Blocking due to full results buffer."); //$NON-NLS-1$
+						}
 					}
 				}
 			}
@@ -482,7 +529,6 @@
     	Determinism determinismLevel = processor.getContext().getDeterminismLevel();
     	CachedResults cr = new CachedResults();
     	cr.setCommand(originalCommand);
-        cr.setAnalysisRecord(analysisRecord);
         cr.setResults(resultsBuffer, processor.getProcessorPlan());
         if (originalCommand.getCacheHint() != null) {
         	LogManager.logDetail(LogConstants.CTX_DQP, requestID, "Using cache hint", originalCommand.getCacheHint()); //$NON-NLS-1$
@@ -611,6 +657,7 @@
             if (requestMsg.getShowPlan() == ShowPlan.DEBUG) {
             	response.setDebugLog(analysisRecord.getDebugLog());
             }
+            this.analysisRecord = null;
         }
 	}
 
@@ -626,17 +673,25 @@
     	}
 		LogManager.logDetail(LogConstants.CTX_DQP, processingException, "Sending error to client", requestID); //$NON-NLS-1$
         ResultsMessage response = new ResultsMessage(requestMsg);
-        response.setException(processingException);
+        Throwable exception = this.processingException;
+        if (isCanceled) {
+        	exception = addCancelCode(exception); 
+        }
+        response.setException(exception);
         setAnalysisRecords(response);
         receiver.receiveResults(response);
     }
+
+	private Throwable addCancelCode(Throwable exception) {
+		if (exception instanceof TeiidException) {
+			TeiidException te = (TeiidException)exception;
+			if (SQLStates.QUERY_CANCELED.equals(te.getCode())) {
+				return exception;
+			}
+		}
+		return new TeiidProcessingException(exception, SQLStates.QUERY_CANCELED, exception.getMessage());
+	}
     
-    @Override
-    protected boolean shouldPause() {
-    	//if we are waiting on results it's ok to pause
-    	return this.resultsReceiver != null;
-    }
-
     private static List<ParameterInfo> getParameterInfo(StoredProcedure procedure) {
         List<ParameterInfo> paramInfos = new ArrayList<ParameterInfo>();
         
@@ -651,10 +706,10 @@
     public void processLobChunkRequest(String id, int streamRequestId, ResultsReceiver<LobChunk> chunckReceiver) {
     	LobWorkItem workItem = null;
     	synchronized (lobStreams) {
-            workItem = this.lobStreams.get(new Integer(streamRequestId));
+            workItem = this.lobStreams.get(streamRequestId);
             if (workItem == null) {
             	workItem = new LobWorkItem(this, dqpCore, id, streamRequestId);
-            	lobStreams.put(new Integer(streamRequestId), workItem);
+            	lobStreams.put(streamRequestId, workItem);
             }
 		}
     	workItem.setResultsReceiver(chunckReceiver);
@@ -666,7 +721,7 @@
     }
     
     public void removeLobStream(int streamRequestId) {
-        this.lobStreams.remove(new Integer(streamRequestId));
+        this.lobStreams.remove(streamRequestId);
     } 
     
     public boolean requestCancel() throws TeiidComponentException {
@@ -731,12 +786,12 @@
     	if (!this.doneProducingBatches) {
     		this.requestCancel(); //pending work should be canceled for fastest clean up
     	}
-    	this.moreWork();
+    	this.doMoreWork();
     }
     
     public void requestMore(int batchFirst, int batchLast, ResultsReceiver<ResultsMessage> receiver) {
     	this.requestResults(batchFirst, batchLast, receiver);
-    	this.moreWork(); 
+    	this.doMoreWork(); 
     }
     
     public void closeAtomicRequest(AtomicRequestID atomicRequestId) {


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/RequestWorkItem.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/SessionAwareCache.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,6 +24,7 @@
 
 import java.io.Serializable;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -291,6 +292,10 @@
 		void setUserName(String name) {
 			this.userName = name;
 		}
+		
+		public VDBKey getVDBKey() {
+			return vdbInfo;
+		}
 						
 		public boolean equals(Object obj){
 	        if(obj == this) {
@@ -328,4 +333,11 @@
     public void setModTime(long modTime) {
 		this.modTime = modTime;
 	}
+    
+    public Set<CacheID> replicatableKeys() {
+    	if (this.distributedCache == this.localCache) {
+    		return Collections.EMPTY_SET;
+    	}
+    	return this.distributedCache.keys();
+    }
 }


Property changes on: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/multisource
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/internal/process/multisource/MultiSourcePlanToProcessConverter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -209,7 +209,7 @@
             		update = true;
             		GroupingNode groupNode = new GroupingNode(getID());                    
             		AggregateSymbol sumCount = new AggregateSymbol("SumCount", NonReserved.SUM, false, (Expression)accessNode.getElements().get(0)); //$NON-NLS-1$          		
-            		List<Expression> outputElements = new ArrayList<Expression>(1);            		
+            		List<SingleElementSymbol> outputElements = new ArrayList<SingleElementSymbol>(1);            		
             		outputElements.add(sumCount); 
             		groupNode.setElements(outputElements);
             		groupNode.addChild(unionNode);
@@ -218,8 +218,8 @@
             		
             		Expression intSum = ResolverUtil.getConversion(sumCount, DataTypeManager.getDataTypeName(sumCount.getType()), DataTypeManager.DefaultDataTypes.INTEGER, false, metadata.getFunctionLibrary());
             		
-            		Expression rowCount = new ExpressionSymbol("RowCount", intSum); //$NON-NLS-1$            		
-            		outputElements = new ArrayList<Expression>(1);            		
+            		ExpressionSymbol rowCount = new ExpressionSymbol("RowCount", intSum); //$NON-NLS-1$            		
+            		outputElements = new ArrayList<SingleElementSymbol>(1);            		
             		outputElements.add(rowCount);             		
             		projectNode.setElements(outputElements);
             		projectNode.setSelectSymbols(outputElements);

Modified: branches/as7/engine/src/main/java/org/teiid/dqp/service/SessionService.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/dqp/service/SessionService.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/dqp/service/SessionService.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,13 +23,17 @@
 package org.teiid.dqp.service;
 
 import java.util.Collection;
+import java.util.List;
 import java.util.Properties;
 
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
 import javax.security.auth.login.LoginException;
 
 import org.teiid.adminapi.impl.SessionMetadata;
 import org.teiid.client.security.InvalidSessionException;
 import org.teiid.dqp.internal.process.DQPCore;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
 import org.teiid.security.Credentials;
 
 
@@ -138,5 +142,12 @@
     SessionMetadata getActiveSession(String sessionID);
     
 	void setDqp(DQPCore dqp);
+	
+	LoginContext createLoginContext(String securityDomain, String user, String password) throws LoginException;
 
+	AuthenticationType getAuthType();
+	
+	String getKrb5SecurityDomain();
+	
+	void assosiateSubjectInContext(String securityDomain, Subject subject); 
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/analysis/AnalysisRecord.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/analysis/AnalysisRecord.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/analysis/AnalysisRecord.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -53,7 +53,7 @@
  * <li>Debug trace information, if requested</LI>
  * </ul>
  */
-public class AnalysisRecord implements Serializable {
+public class AnalysisRecord {
 	
     // Common 
     public static final String PROP_OUTPUT_COLS = "Output Columns"; //$NON-NLS-1$

Modified: branches/as7/engine/src/main/java/org/teiid/query/eval/Evaluator.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/eval/Evaluator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/eval/Evaluator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,8 +40,11 @@
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
 
+import javax.xml.transform.stream.StreamResult;
+
+import net.sf.saxon.om.NodeInfo;
+import net.sf.saxon.query.QueryResult;
 import net.sf.saxon.trans.XPathException;
 
 import org.teiid.api.exception.query.ExpressionEvaluationException;
@@ -50,6 +53,7 @@
 import org.teiid.core.ComponentNotFoundException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.BlobType;
 import org.teiid.core.types.ClobImpl;
 import org.teiid.core.types.ClobType;
@@ -63,11 +67,13 @@
 import org.teiid.core.types.XMLType.Type;
 import org.teiid.core.types.basic.StringToSQLXMLTransform;
 import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.language.Like.MatchMode;
 import org.teiid.metadata.FunctionMethod.PushDown;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.function.FunctionDescriptor;
 import org.teiid.query.function.FunctionLibrary;
 import org.teiid.query.function.source.XMLSystemFunctions;
+import org.teiid.query.function.source.XMLSystemFunctions.XmlConcat;
 import org.teiid.query.processor.ProcessorDataManager;
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.lang.AbstractSetCriteria;
@@ -109,14 +115,42 @@
 import org.teiid.query.sql.symbol.XMLNamespaces.NamespaceItem;
 import org.teiid.query.sql.util.ValueIterator;
 import org.teiid.query.sql.util.ValueIteratorSource;
+import org.teiid.query.sql.util.VariableContext;
 import org.teiid.query.util.CommandContext;
 import org.teiid.query.xquery.saxon.SaxonXQueryExpression;
+import org.teiid.query.xquery.saxon.XQueryEvaluator;
 import org.teiid.query.xquery.saxon.SaxonXQueryExpression.Result;
+import org.teiid.query.xquery.saxon.SaxonXQueryExpression.RowProcessor;
 import org.teiid.translator.WSConnection.Util;
 
 public class Evaluator {
 
-    private final class SequenceReader extends Reader {
+    private final class XMLQueryRowProcessor implements RowProcessor {
+		XmlConcat concat; //just used to get a writer
+		Type type;
+		private javax.xml.transform.Result result;
+		
+		private XMLQueryRowProcessor() throws TeiidProcessingException {
+			concat = new XmlConcat(context.getBufferManager());
+			result = new StreamResult(concat.getWriter());
+		}
+
+		@Override
+		public void processRow(NodeInfo row) {
+			if (type == null) {
+				type = SaxonXQueryExpression.getType(row);
+			} else {
+				type = Type.CONTENT;
+			}
+			try {
+				QueryResult.serialize(row, result, SaxonXQueryExpression.DEFAULT_OUTPUT_PROPERTIES);
+			} catch (XPathException e) {
+				throw new TeiidRuntimeException(e);
+			}
+		}
+	}
+
+	private final class SequenceReader extends Reader {
 		private LinkedList<Reader> readers;
 		private Reader current = null;
 		
@@ -170,9 +204,15 @@
 		}
 	}
 
-	private final static char[] REGEX_RESERVED = new char[] {'$', '(', ')', '*', '.', '?', '[', '\\', ']', '^', '{', '|', '}'}; //in sorted order
-    private final static MatchCriteria.PatternTranslator LIKE_TO_REGEX = new MatchCriteria.PatternTranslator(".*", ".", REGEX_RESERVED, '\\');  //$NON-NLS-1$ //$NON-NLS-2$
-
+	public final static char[] REGEX_RESERVED = new char[] {'$', '(', ')', '*', '+', '.', '?', '[', '\\', ']', '^', '{', '|', '}'}; //in sorted order
+    private final static MatchCriteria.PatternTranslator LIKE_TO_REGEX = new MatchCriteria.PatternTranslator(new char[] {'%', '_'}, new String[] {".*", "."},  REGEX_RESERVED, '\\', Pattern.DOTALL);  //$NON-NLS-1$ //$NON-NLS-2$
+    
+    private final static char[] SIMILAR_REGEX_RESERVED = new char[] {'$', '.', '\\', '^'}; //in sorted order
+    public final static MatchCriteria.PatternTranslator SIMILAR_TO_REGEX = new MatchCriteria.PatternTranslator(
+    		new char[] {'%', '(', ')', '*', '?', '+', '[', ']', '_', '{', '|', '}'}, 
+    		new String[] {"([a]|[^a])*", "(", ")", "*", "?", "+", //$NON-NLS-1$ //$NON-NLS-2$  //$NON-NLS-3$ //$NON-NLS-4$  //$NON-NLS-5$ //$NON-NLS-6$
+    				"[", "]", "([a]|[^a])", "{", "|", "}"},  SIMILAR_REGEX_RESERVED, '\\', 0);  //$NON-NLS-1$ //$NON-NLS-2$  //$NON-NLS-3$ //$NON-NLS-4$  //$NON-NLS-5$ //$NON-NLS-6$  
+    
     private Map elements;
     
     protected ProcessorDataManager dataMgr;
@@ -371,27 +411,31 @@
             return null;
         }
         
-        result = match(rightValue, criteria.getEscapeChar(), leftValue);
+        result = match(rightValue, criteria.getEscapeChar(), leftValue, criteria.getMode());
         
         return Boolean.valueOf(result ^ criteria.isNegated());
 	}
 
-	private boolean match(String pattern, char escape, CharSequence search)
+	private boolean match(String pattern, char escape, CharSequence search, MatchMode mode)
 		throws ExpressionEvaluationException {
 
-		StringBuffer rePattern = LIKE_TO_REGEX.translate(pattern, escape);
+		Pattern patternRegex = null;
+		switch (mode) {
+		case LIKE:
+			patternRegex = LIKE_TO_REGEX.translate(pattern, escape);
+			break;
+		case SIMILAR:
+			patternRegex = SIMILAR_TO_REGEX.translate(pattern, escape);
+			break;
+		case REGEX:
+			patternRegex = MatchCriteria.getPattern(pattern, pattern, 0);
+			break;
+		default:
+			throw new AssertionError();
+		}
 		
-		// Insert leading and trailing characters to ensure match of full string
-		rePattern.insert(0, '^');
-		rePattern.append('$');
-
-		try {
-            Pattern patternRegex = Pattern.compile(rePattern.toString(), Pattern.DOTALL);
-            Matcher matcher = patternRegex.matcher(search);
-            return matcher.matches();
-		} catch(PatternSyntaxException e) {
-            throw new ExpressionEvaluationException(e, "ERR.015.006.0014", QueryPlugin.Util.getString("ERR.015.006.0014", new Object[]{pattern, e.getMessage()})); //$NON-NLS-1$ //$NON-NLS-2$
-		}
+        Matcher matcher = patternRegex.matcher(search);
+        return matcher.matches();
 	}
 
 	private Boolean evaluate(AbstractSetCriteria criteria, List<?> tuple)
@@ -427,7 +471,8 @@
         	valueIter = new CollectionValueIterator(((SetCriteria)criteria).getValues());
         } else if (criteria instanceof DependentSetCriteria){
         	ContextReference ref = (ContextReference)criteria;
-    		ValueIteratorSource vis = (ValueIteratorSource)getContext(criteria).getVariableContext().getGlobalValue(ref.getContextSymbol());
+        	VariableContext vc = getContext(criteria).getVariableContext();
+    		ValueIteratorSource vis = (ValueIteratorSource)vc.getGlobalValue(ref.getContextSymbol());
     		Set<Object> values;
     		try {
     			values = vis.getCachedSet(ref.getValueExpression());
@@ -437,6 +482,7 @@
         	if (values != null) {
         		return values.contains(leftValue);
         	}
+    		vis.setUnused(true);
         	//there are too many values to justify a linear search or holding
         	//them in memory
         	return true;
@@ -756,13 +802,33 @@
 	private Object evaluateXMLQuery(List<?> tuple, XMLQuery xmlQuery)
 			throws BlockedException, TeiidComponentException,
 			FunctionExecutionException {
-		boolean emptyOnEmpty = true;
-		if (xmlQuery.getEmptyOnEmpty() != null)  {
-			emptyOnEmpty = xmlQuery.getEmptyOnEmpty();
-		}   
+		boolean emptyOnEmpty = xmlQuery.getEmptyOnEmpty() == null || xmlQuery.getEmptyOnEmpty();
 		Result result = null;
 		try {
-			result = evaluateXQuery(xmlQuery.getXQueryExpression(), xmlQuery.getPassing(), tuple);
+			XMLQueryRowProcessor rp = null;
+			if (xmlQuery.getXQueryExpression().isStreaming()) {
+				rp = new XMLQueryRowProcessor();
+			}
+			try {
+				result = evaluateXQuery(xmlQuery.getXQueryExpression(), xmlQuery.getPassing(), tuple, rp);
+			} catch (TeiidRuntimeException e) {
+				if (e.getCause() instanceof XPathException) {
+					throw (XPathException)e.getCause();
+				}
+				throw e;
+			}
+			if (rp != null) {
+				XMLType.Type type = rp.type;
+				if (type == null) {
+					if (!emptyOnEmpty) {
+						return null;
+					}
+					type = Type.CONTENT;
+				}
+				XMLType val = rp.concat.close();
+				val.setType(rp.type);
+				return val;
+			}
 			return xmlQuery.getXQueryExpression().createXMLType(result.iter, this.context.getBufferManager(), emptyOnEmpty);
 		} catch (TeiidProcessingException e) {
 			throw new FunctionExecutionException(e, QueryPlugin.Util.getString("Evaluator.xmlquery", e.getMessage())); //$NON-NLS-1$
@@ -856,7 +922,7 @@
 		   }
 	}
 	
-	public Result evaluateXQuery(SaxonXQueryExpression xquery, List<DerivedColumn> cols, List<?> tuple) 
+	public Result evaluateXQuery(SaxonXQueryExpression xquery, List<DerivedColumn> cols, List<?> tuple, RowProcessor processor) 
 	throws BlockedException, TeiidComponentException, TeiidProcessingException {
 		HashMap<String, Object> parameters = new HashMap<String, Object>();
 		Object contextItem = null;
@@ -868,7 +934,7 @@
 				parameters.put(passing.getAlias(), value);
 			}
 		}
-		return xquery.evaluateXQuery(contextItem, parameters);
+		return XQueryEvaluator.evaluateXQuery(xquery, contextItem, parameters, processor, context);
 	}
 
 	private Evaluator.NameValuePair<Object>[] getNameValuePairs(List<?> tuple, List<DerivedColumn> args, boolean xmlNames)


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/eval/Evaluator.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java:3149-3171
   + /branches/7.4.x/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java:3149-3171
/trunk/engine/src/main/java/org/teiid/query/function/FunctionDescriptor.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/query/function/FunctionMethods.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/function/FunctionMethods.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/function/FunctionMethods.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -56,6 +56,7 @@
 import org.teiid.core.types.InputStreamFactory.BlobInputStreamFactory;
 import org.teiid.core.types.InputStreamFactory.ClobInputStreamFactory;
 import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.language.SQLConstants;
 import org.teiid.language.SQLConstants.NonReserved;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.util.CommandContext;
@@ -694,14 +695,30 @@
 		return new Integer(str.indexOf(sub, start.intValue() - 1) + 1);
 	}
 
+	public static String trim(String trimSpec, String trimChar, String string) throws FunctionExecutionException {
+		if (trimChar.length() != 1) {
+			throw new FunctionExecutionException(QueryPlugin.Util.getString("SQLParser.Invalid_char", "trim char", trimChar)); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		if (!trimSpec.equalsIgnoreCase(SQLConstants.Reserved.LEADING)) {
+			string = rightTrim(string, trimChar.charAt(0));
+		}
+		if (!trimSpec.equalsIgnoreCase(SQLConstants.Reserved.TRAILING)) {
+			string = leftTrim(string, trimChar.charAt(0));
+		}
+		return string;
+	}
+	
 	// ================== Function = lefttrim =====================
 
 	private static final char SPACE = ' ';
 
-	public static Object leftTrim(String string) {
+	public static String leftTrim(String string, char trimChar) {
 		for(int i=0; i<string.length(); i++) {
-			if(string.charAt(i) != SPACE) {
+			if(string.charAt(i) != trimChar) {
 				// end of trim, return what's left
+				if (i==0) {
+					return string;
+				}
 				return new String(string.substring(i));
 			}
 		}
@@ -709,13 +726,21 @@
 		// All spaces, so trim it all
 		return ""; //$NON-NLS-1$
 	}
+	
+	
+	public static String leftTrim(String string) {
+		return leftTrim(string, SPACE);
+	}
 
 	// ================== Function = righttrim =====================
 
-	public static Object rightTrim(String string) {
+	public static String rightTrim(String string, char trimChar) {
 		for(int i=string.length()-1; i>=0; i--) {
-			if(string.charAt(i) != SPACE) {
+			if(string.charAt(i) != trimChar) {
 				// end of trim, return what's left
+				if (i==string.length()-1) {
+					return string;
+				}
 				return new String(string.substring(0, i+1));
 			}
 		}
@@ -723,6 +748,10 @@
 		// All spaces, so trim it all
 		return ""; //$NON-NLS-1$
 	}
+	
+	public static Object rightTrim(String string) {
+		return rightTrim(string, SPACE);
+	}
 
 	// ================== Function = replace =====================
 


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/function/FunctionTree.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/main/java/org/teiid/query/function/FunctionTree.java:3149-3171
   + /branches/7.4.x/engine/src/main/java/org/teiid/query/function/FunctionTree.java:3149-3171
/trunk/engine/src/main/java/org/teiid/query/function/FunctionTree.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/AggregateFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -39,10 +39,15 @@
 public abstract class AggregateFunction {
 
 	private int expressionIndex = -1;
+	private int conditionIndex = -1;
 	
 	public void setExpressionIndex(int expressionIndex) {
 		this.expressionIndex = expressionIndex;
 	}
+	
+	public void setConditionIndex(int conditionIndex) {
+		this.conditionIndex = conditionIndex;
+	}
 
     /**
      * Called to initialize the function.  In the future this may expand
@@ -58,18 +63,21 @@
     public abstract void reset();
 
     public void addInput(List<?> tuple) throws TeiidComponentException, TeiidProcessingException {
+    	if (conditionIndex != -1 && !Boolean.TRUE.equals(tuple.get(conditionIndex))) {
+			return;
+    	}
     	if (expressionIndex == -1) {
     		addInputDirect(null, tuple);
     		return;
     	}
     	Object input = tuple.get(expressionIndex);
-    	if (!filter(input)) {
+    	if (input != null || respectsNull()) {
     		addInputDirect(input, tuple);
     	}
     }
     
-    boolean filter(Object value) {
-    	return value == null; 
+    public boolean respectsNull() {
+    	return false;
     }
     
     /**

Modified: branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ArrayAgg.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ArrayAgg.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ArrayAgg.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -62,10 +62,10 @@
 	public void reset() {
 		this.result = null;
 	}
+	
+	@Override
+	public boolean respectsNull() {
+		return true;
+	}
 
-	@Override
-    boolean filter(Object value) {
-		// handle the null values too.
-    	return false; 
-    }	
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/ConstantFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,8 +40,8 @@
     }
     
     @Override
-    boolean filter(Object input) {
-    	return false;
+    public boolean respectsNull() {
+    	return true;
     }
 
     /**

Copied: branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/RankingFunction.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/function/aggregate/RankingFunction.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/RankingFunction.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/function/aggregate/RankingFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,72 @@
+/*
+ * 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 org.teiid.query.function.aggregate;
+
+import java.util.List;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.sql.symbol.AggregateSymbol.Type;
+
+/**
+ * computes rank/dense_rank
+ */
+public class RankingFunction extends AggregateFunction {
+	
+	private int count = 0;
+	private int lastCount = 0;
+	private Type type;
+	
+	public RankingFunction(Type function) {
+		this.type = function;
+	}
+
+	@Override
+	public void reset() {
+		count = 0;
+		lastCount = 0;
+	}
+	
+	@Override
+	public void addInputDirect(Object input, List<?> tuple)
+			throws FunctionExecutionException, ExpressionEvaluationException,
+			TeiidComponentException {
+		if (type == Type.RANK) {
+			count++;
+		}
+	}
+	
+	@Override
+	public Object getResult() throws FunctionExecutionException,
+			ExpressionEvaluationException, TeiidComponentException {
+		if (type == Type.DENSE_RANK) {
+			count++;
+			return count;
+		}
+		int result = ++lastCount;
+		lastCount = count;
+		return result;
+	}
+
+}

Modified: branches/as7/engine/src/main/java/org/teiid/query/function/source/SystemSource.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/function/source/SystemSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/function/source/SystemSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,8 +29,8 @@
 
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.metadata.FunctionParameter;
+import org.teiid.metadata.FunctionMethod.Determinism;
 import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.metadata.FunctionMethod.Determinism;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.function.FunctionLibrary;
 import org.teiid.query.function.FunctionMetadataSource;
@@ -196,7 +196,18 @@
         addUuidFunction();
         addArrayGet();
         addArrayLength();
+        addTrimFunction();
     }
+    
+    private void addTrimFunction() {
+        functions.add(
+            new FunctionMethod(SourceSystemFunctions.TRIM, QueryPlugin.Util.getString("SystemSource.trim_desc"), STRING, FUNCTION_CLASS, SourceSystemFunctions.TRIM,//$NON-NLS-1$ 
+                new FunctionParameter[] {
+            		new FunctionParameter("spec", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.trim_arg1")),//$NON-NLS-1$ //$NON-NLS-2$
+            		new FunctionParameter("trimChar", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.trim_arg2")),//$NON-NLS-1$ //$NON-NLS-2$
+                    new FunctionParameter("string", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.trim_arg3")) }, //$NON-NLS-1$ //$NON-NLS-2$
+                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, QueryPlugin.Util.getString("SystemSource.trim_result")) ) );   //$NON-NLS-1$ //$NON-NLS-2$
+    }
 
     private void addArrayLength() {
     	functions.add(new FunctionMethod(SourceSystemFunctions.ARRAY_LENGTH, QueryPlugin.Util.getString("SystemSource.array_length_desc"), MISCELLANEOUS, PushDown.CAN_PUSHDOWN, FUNCTION_CLASS, SourceSystemFunctions.ARRAY_LENGTH, //$NON-NLS-1$ 

Modified: branches/as7/engine/src/main/java/org/teiid/query/function/source/XMLSystemFunctions.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/function/source/XMLSystemFunctions.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/function/source/XMLSystemFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -401,6 +401,7 @@
 		private Writer writer;
 		private FileStoreInputStreamFactory fsisf;
 		private FileStore fs;
+		private Type type;
 		
 		public XmlConcat(BufferManager bm) throws TeiidProcessingException {
 			fs = bm.createFileStore("xml"); //$NON-NLS-1$
@@ -417,6 +418,13 @@
 		}
 		
 		public void addValue(Object object) throws TeiidProcessingException {
+			if (type == null) {
+				if (object instanceof XMLType) {
+					type = ((XMLType)object).getType();
+				}
+			} else {
+				type = Type.CONTENT;
+			}
 			try {
 				convertValue(writer, eventWriter, eventFactory, object);
 			} catch (IOException e) {
@@ -431,6 +439,10 @@
 			}
 		}
 		
+		public Writer getWriter() {
+			return writer;
+		}
+		
 		public XMLType close() throws TeiidProcessingException {
 			try {
 				eventWriter.flush();
@@ -443,7 +455,11 @@
 				throw new TeiidProcessingException(e);
 			}
 	        XMLType result = new XMLType(new SQLXMLImpl(fsisf));
-	        result.setType(Type.CONTENT);
+	        if (type == null) {
+	        	result.setType(Type.CONTENT);
+	        } else {
+	        	result.setType(type);
+	        }
 	        return result;
 		}
 		

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingAttribute.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,15 +26,12 @@
 
 
 /** 
- * A Mapping node which denotes a attribuite node.
+ * A Mapping node which denotes a attribute node.
  */
 public class MappingAttribute extends MappingNode {
     // Element symbol in the resultset source
     ElementSymbol symbol;
     
-    // Position of the element in the resultset source
-    int position = -1;  
-
     // namespace of the attribute
     Namespace namespace;
     

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingBaseNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,7 +23,6 @@
 package org.teiid.query.mapping.xml;
 
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
 
 import org.teiid.core.TeiidRuntimeException;
@@ -205,11 +204,11 @@
         return false;
     }
     
-    public List getStagingTables() {
-        return (List)getProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES);
+    public List<String> getStagingTables() {
+        return (List<String>)getProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES);
     }
     
-    public void setStagingTables(List tables) {
+    public void setStagingTables(List<String> tables) {
         if (tables != null) {
             setProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES, tables);
         }
@@ -222,9 +221,9 @@
         if (tablename == null) {
             return;
         }
-        List tables = getStagingTables();
-        if (tables == null || tables == Collections.EMPTY_LIST) {
-            tables = new ArrayList();
+        List<String> tables = getStagingTables();
+        if (tables == null || tables.isEmpty()) {
+            tables = new ArrayList<String>();
         }
         tables.add(tablename);
         setProperty(MappingNodeConstants.Properties.TEMP_GROUP_NAMES, tables);

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingCriteriaNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,8 +22,6 @@
 
 package org.teiid.query.mapping.xml;
 
-import java.util.List;
-
 import org.teiid.query.sql.lang.Criteria;
 
 
@@ -34,7 +32,6 @@
  */
 public class MappingCriteriaNode extends MappingBaseNode{
     boolean defalt;
-    List criteriaGroups;
     Criteria criteriaNode;
     
     public MappingCriteriaNode(String criteria, boolean defalt) {
@@ -87,23 +84,6 @@
         return this.criteriaNode;
     }
     
-    /**
-     * Groups that are referenced inthe criteria string. This is set by ValidateMappedCriteriaVisitor
-     * class during the preplan.
-     * @param criteriaGroups
-     */
-    public void setGroupsInCriteria(List criteriaGroups) {
-        this.criteriaGroups = criteriaGroups;
-    }
-
-    /**
-     * @deprecated - may not be needed
-     * @return
-     */
-    public List getGroupsInCriteria() {
-        return this.criteriaGroups;
-    }
-    
     /** 
      * @see org.teiid.query.mapping.xml.MappingNode#isExcluded()
      */

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingDocument.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,11 +22,6 @@
 
 package org.teiid.query.mapping.xml;
 
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.query.QueryPlugin;
 
@@ -160,26 +155,10 @@
     /** 
      * @see org.teiid.query.mapping.xml.MappingNode#clone()
      */
-    public Object clone() {
-        // I found this as cheap way of cloneing for now fast, may be we will
-        // do all the object cloneing later..
-        try {
-            MappingOutputter out = new MappingOutputter();
-            StringWriter stream = new StringWriter();
-            out.write(this, new PrintWriter(stream));
-            MappingLoader loader = new MappingLoader();
-            MappingDocument doc =  loader.loadDocument(new ByteArrayInputStream(stream.toString().getBytes()));
-
-            // Copy the values of the instance variables.
-            doc.formatted = this.formatted;
-            doc.encoding = this.encoding;
-            doc.name = this.name;
-            
-            return doc;
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        } catch(MappingException e) {
-            throw new RuntimeException(e);
-        }
-    }    
+    public MappingDocument clone() {
+		MappingDocument clone = (MappingDocument) super.clone();
+		clone.root = (MappingBaseNode) clone.getChildren().iterator().next();
+		return clone;
+    }  
+    
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingElement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -39,9 +39,6 @@
     // Element symbol in the resultset source
     ElementSymbol symbol;
     
-    // Position of the element in the resultset source
-    int position = -1;  
-    
     Namespace namespace;
     
     public MappingElement(String name) {

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,12 +25,13 @@
 import java.io.PrintStream;
 import java.io.Serializable;
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 
+import org.teiid.core.TeiidRuntimeException;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.sql.symbol.ElementSymbol;
 
@@ -42,14 +43,16 @@
  */
 public abstract class MappingNode implements Cloneable, Serializable {
 
-    /** The parent of this node, null if root. */
+	private static final long serialVersionUID = 6761829541871178451L;
+
+	/** The parent of this node, null if root. */
     private MappingNode parent;
 
     /** Child nodes, usually just 1 or 2, but occasionally more */
-    private LinkedList children = new LinkedList();
+    private List<MappingNode> children = new LinkedList<MappingNode>();
 
     /** node properties, as defined in NodeConstants.Properties. */
-    private Map nodeProperties;
+    private Map<MappingNodeConstants.Properties, Object> nodeProperties;
 
     /** default constructor */
     public MappingNode(){
@@ -89,8 +92,8 @@
             }
         }
         
-        for (Iterator i = root.getChildren().iterator(); i.hasNext();) {
-            MappingNode child = (MappingNode)i.next();
+        for (Iterator<MappingNode> i = root.getChildren().iterator(); i.hasNext();) {
+            MappingNode child = i.next();
             MappingNode found = findNode(child, partialName);
             if (found != null) {
                 return found;
@@ -104,7 +107,7 @@
      * Set the parent of this node.  This method is restricted, as
      * it should be called only when {@link #addChild adding a child node}
      */
-    private void setParent( MappingNode parent ) {
+    void setParent( MappingNode parent ) {
         this.parent = parent;
     }
 
@@ -112,7 +115,7 @@
      * Get the children contained by this node, or an empty List
      * @return children; if no children, return empty List (never null)
      */
-    public List getChildren(){
+    public List<MappingNode> getChildren(){
         return this.children;
     }
 
@@ -120,11 +123,11 @@
      * Get all children of this node of a specified target node type.  The value
      * of node type should be one of {@link #ATTRIBUTE} or {@link #ELEMENT}.
      */
-    public List getChildren( String type ) {
-        List subset = new ArrayList();
-        Iterator iter = children.iterator();
+    public List<MappingNode> getChildren( String type ) {
+        List<MappingNode> subset = new ArrayList<MappingNode>();
+        Iterator<MappingNode> iter = children.iterator();
         while ( iter.hasNext() ) {
-            MappingNode node = (MappingNode)iter.next();
+            MappingNode node = iter.next();
             if ( node.getProperty(MappingNodeConstants.Properties.NODE_TYPE).equals(type) ) {
                 subset.add( node );
             }
@@ -132,11 +135,11 @@
         return subset;
     }
     
-    public List getNodeChildren() {
-        List subset = new ArrayList();
-        Iterator iter = children.iterator();
+    public List<MappingNode> getNodeChildren() {
+        List<MappingNode> subset = new ArrayList<MappingNode>();
+        Iterator<MappingNode> iter = children.iterator();
         while ( iter.hasNext() ) {
-            MappingNode node = (MappingNode)iter.next();
+            MappingNode node = iter.next();
             if ( !node.getProperty(MappingNodeConstants.Properties.NODE_TYPE).equals(MappingNodeConstants.ATTRIBUTE) ) {
                 subset.add( node );
             }
@@ -162,7 +165,7 @@
      * @param propertyID Integer property key
      * @return Object value
      */
-    public Object getProperty(Integer propertyID) {
+    public Object getProperty(MappingNodeConstants.Properties propertyID) {
         Object value = null;
         if(nodeProperties != null) {
             value = nodeProperties.get(propertyID);
@@ -180,11 +183,11 @@
      * @param propertyID Integer property key
      * @param value Object property value
      */
-    void setProperty(Integer propertyID, Object value) {
+    void setProperty(MappingNodeConstants.Properties propertyID, Object value) {
         if (value != null){
             // Get the default for the property ...
             final Object defaultValue = MappingNodeConstants.Defaults.DEFAULT_VALUES.get(propertyID);
-            final Map props = getNodeProperties();      // props is never null
+            final Map<MappingNodeConstants.Properties, Object> props = getNodeProperties();      // props is never null
             if ( !value.equals(defaultValue) ) {        // we know value is not null
                 // Set the value only if different than the default; note that the 'getProperty'
                 // method is returning the default if there isn't a value
@@ -197,7 +200,7 @@
         }
     }
 
-    void removeProperty(Integer propertyID) {
+    void removeProperty(MappingNodeConstants.Properties propertyID) {
         getNodeProperties().remove(propertyID);
     }
     
@@ -209,9 +212,9 @@
      * object.
      * @see #getProperties
      */
-    public Map getNodeProperties(){
+    public Map<MappingNodeConstants.Properties, Object> getNodeProperties(){
         if(nodeProperties == null) {
-            nodeProperties = new HashMap();
+            nodeProperties = new LinkedHashMap<MappingNodeConstants.Properties, Object>();
         }
         return nodeProperties;
     }
@@ -318,9 +321,9 @@
         str.append(node.getNodeProperties());
         str.append("\n"); //$NON-NLS-1$
 
-        Iterator i = node.getChildren().iterator();
+        Iterator<MappingNode> i = node.getChildren().iterator();
         while (i.hasNext()){
-            buildTreeString((MappingNode)i.next(), str, tabLevel);
+            buildTreeString(i.next(), str, tabLevel);
         }
     }
 
@@ -345,7 +348,7 @@
      * {@link MappingNodeConstants#SEARCH_DOWN} or {@link MappingNodeConstants#SEARCH_DOWN_BREADTH_FIRST}
      * @return MappingNode first node found that has the indicated property and value, or null if none found
      */
-    static MappingNode findFirstNodeWithProperty(Integer propertyKey, Object value, MappingNode node, int searchDirection) {
+    static MappingNode findFirstNodeWithProperty(MappingNodeConstants.Properties propertyKey, Object value, MappingNode node, int searchDirection) {
         return findFirstNodeWithPropertyValue(propertyKey, value, false, node, searchDirection);
     }
     
@@ -365,11 +368,11 @@
      * {@link MappingNodeConstants#SEARCH_DOWN} or {@link MappingNodeConstants#SEARCH_DOWN_BREADTH_FIRST}
      * @return MappingNode first node found that has the indicated property and value, or null if none found
      */
-    static MappingNode findFirstNodeWithPropertyString(Integer propertyKey, String value, MappingNode node, int searchDirection) {
+    static MappingNode findFirstNodeWithPropertyString(MappingNodeConstants.Properties propertyKey, String value, MappingNode node, int searchDirection) {
         return findFirstNodeWithPropertyValue(propertyKey, value, true, node, searchDirection);
     }
 
-    private static MappingNode findFirstNodeWithPropertyValue(Integer propertyKey, Object value, boolean isStringValue, MappingNode node, int searchDirection) {
+    private static MappingNode findFirstNodeWithPropertyValue(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node, int searchDirection) {
         
         if (node == null || propertyKey == null){
             return null;
@@ -389,11 +392,11 @@
         }
     }
 
-    private static MappingNode traverseDownForFirstNodeWithPropertyString(Integer propertyKey, Object value, boolean isStringValue, MappingNode node, boolean breadthFirst) {
+    private static MappingNode traverseDownForFirstNodeWithPropertyString(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node, boolean breadthFirst) {
         if (breadthFirst) {
-            Iterator children = node.getChildren().iterator();
+            Iterator<MappingNode> children = node.getChildren().iterator();
             while (children.hasNext()){
-                MappingNode child = (MappingNode)children.next();
+                MappingNode child = children.next();
                 if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, child)){
                     return child;
                 }
@@ -404,9 +407,9 @@
             }
         }
         
-        Iterator children = node.getChildren().iterator();
+        Iterator<MappingNode> children = node.getChildren().iterator();
         while (children.hasNext()){
-            MappingNode child = (MappingNode)children.next();
+            MappingNode child = children.next();
             
             //recursive call to this method
             MappingNode result = traverseDownForFirstNodeWithPropertyString(propertyKey, value, isStringValue, child, breadthFirst);
@@ -418,7 +421,7 @@
         return null;
     }
     
-    private static boolean checkThisNodeForPropertyValue(Integer propertyKey, Object value, boolean isStringValue, MappingNode node) {
+    private static boolean checkThisNodeForPropertyValue(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node) {
         Object thisValue = node.getProperty(propertyKey);
         if (thisValue != null){
             if (value == null){
@@ -434,7 +437,7 @@
         return false;
     }
 
-    private static MappingNode traverseUpForFirstNodeWithPropertyString(Integer propertyKey, Object value, boolean isStringValue, MappingNode node) {
+    private static MappingNode traverseUpForFirstNodeWithPropertyString(MappingNodeConstants.Properties propertyKey, Object value, boolean isStringValue, MappingNode node) {
         while (node != null){
             if (checkThisNodeForPropertyValue(propertyKey, value, isStringValue, node)){
                 return node;
@@ -477,4 +480,22 @@
     public String getNameInSource() {
         return null;        
     }    
+    
+    public MappingNode clone() {
+    	try {
+			MappingNode clone = (MappingNode) super.clone();
+			clone.children = new ArrayList<MappingNode>(children);
+			for (int i = 0; i < clone.children.size(); i++) {
+				clone.children.set(i, clone.children.get(i).clone());
+				clone.children.get(i).setParent(clone);
+			}
+			return clone;
+		} catch (CloneNotSupportedException e) {
+			throw new TeiidRuntimeException(e);
+		}
+    }
+    
+    public ElementSymbol getElementSymbol() {
+    	return null;
+    }
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingNodeConstants.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -151,18 +151,17 @@
      * Property names for type-specific node properties.  Values will be of
      * type String unless otherwise specified.
      */
-    public static final class Properties {
-        private Properties() { }
+    public enum Properties {
         
         /** The basic name of this node. Will be the element or attribute tag name. */
-        public static final Integer NAME = new Integer(0);
+        NAME,
 
         /** 
          * The namespace prefix, which indicates the namespace for this node. 
          * The namespace must be declared either at this node or an ancestor
          * node; use the {@link #NAMESPACE_DECLARATIONS} property.
          */
-        public static final Integer NAMESPACE_PREFIX = new Integer(1);
+        NAMESPACE_PREFIX,
 
         /** 
          * <p>This property allows for one or more namespace declarations
@@ -182,42 +181,42 @@
          * <pre>&lt;shipDate xsi:nil="true"/&gt;</pre>
          * </p>
          */
-        public static final Integer NAMESPACE_DECLARATIONS = new Integer(2);
+        NAMESPACE_DECLARATIONS,
        
         /**
          * The target node type.  Can take on one of the values {@link #ATTRIBUTE}
          * or {@link #ELEMENT}.
          */        
-        public static final Integer NODE_TYPE = new Integer(4);  // Values: ATTRIBUTE|ELEMENT
+        NODE_TYPE,  // Values: ATTRIBUTE|ELEMENT
 
         /** 
          * <p>The minimum number of times this node must occur in a document.</p>
          * <p>Type: <code>java.lang.Integer</code></p>
          */
-        public static final Integer CARDINALITY_MIN_BOUND = new Integer(5);
+        CARDINALITY_MIN_BOUND,
 
         /** 
          * <p>The maximum number of times this node may occur in a document.</p>
          * <p>Type: <code>java.lang.Integer</code></p>
          */
-        public static final Integer CARDINALITY_MAX_BOUND = new Integer(6);
+        CARDINALITY_MAX_BOUND,
 
         /**
          * An optional constraint that applies for the node.  If a constraint is
          * defined, the input tuple to the node will be compared to the constraint.
          * The node will be processed only if the constraint is satisfied.
          */
-        public static final Integer CRITERIA = new Integer(7);
+        CRITERIA,
         
         /**
          * This property represents a default value for an XML node
          */
-        public static final Integer DEFAULT_VALUE = new Integer(8);
+        DEFAULT_VALUE,
 
         /**
          * This property represents a fixed value for an XML node
          */
-        public static final Integer FIXED_VALUE = new Integer(11);
+        FIXED_VALUE,
 
         /**
          * <p>Value will be of type Boolean.  Indicates that the node is nillable, 
@@ -226,11 +225,11 @@
          * indicates when the element has null content.</p>
          * 
          * <p><b>Note:</b> This property may only be set to true if this node
-         * is an element (i.e. the {@link #NODE_TYPE} property must have 
+         * is an element (i.e. the {@link #NODETYPE} property must have 
          * a value of {@link #ELEMENT}), although this constraint is not
          * enforced anywhere in the MappingNode framework.</p>
          */
-        public static final Integer IS_NILLABLE = new Integer(9);
+        IS_NILLABLE,
 
         /**
          * <p>This node will be completely ignored, not output, not
@@ -238,11 +237,11 @@
          * <p>Type: <code>java.lang.Boolean</code></p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_EXCLUDED}</p>
          */
-        public static final Integer IS_EXCLUDED = new Integer(10);
+        IS_EXCLUDED,
 
 
         /** The name of the result being returned by this node */
-        public static final Integer RESULT_SET_NAME = new Integer(20);
+        RESULT_SET_NAME,
 
         /** 
          * The name(s) of the temporary group(s) to be materialized at this 
@@ -250,18 +249,18 @@
          * <p>Type: <code>java.util.List</code> of </code>java.lang.String</code>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_TEMP_GROUP_NAMES}</p>
          */
-        public static final Integer TEMP_GROUP_NAMES = new Integer(23);
+        TEMP_GROUP_NAMES,
 
         /** The symbol from a result set that maps to this node. */
-        public static final Integer ELEMENT_NAME = new Integer(30);
+        ELEMENT_NAME,
 
 		/** The temporary property to mark whether this node should be included. */
-		public static final Integer IS_INCLUDED = new Integer(15);
+		IS_INCLUDED,
 
         /**
          * The text for a comment.
          */
-        public static final Integer COMMENT_TEXT = new Integer(16);
+        COMMENT_TEXT,
         
         /** 
          * Indicates that the element or attribute is to be considered optional,
@@ -271,7 +270,7 @@
          * <p>Type: <code>java.lang.Boolean</code> 
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_OPTIONAL}</p>
          */
-        public static final Integer IS_OPTIONAL = new Integer(22);
+        IS_OPTIONAL,
         
         /**
          * <p>Indicates the level of text normalization that will be applied
@@ -279,7 +278,7 @@
          * <p>Type: <code>java.lang.String</code></p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_NORMALIZE_TEXT}</p>
          */
-        public static final Integer NORMALIZE_TEXT = new Integer(24);
+        NORMALIZE_TEXT,
         
         /**
          * Specifies the design-time base built-in type for the virtual document node.
@@ -288,7 +287,7 @@
          * is used to determine special translations from the runtime value to the expected
          * XML schema output value string.  
          */
-        public static final Integer BUILT_IN_TYPE = new Integer(25);
+        BUILT_IN_TYPE,
         
         // ========================================================================
         // CHOICE NODE RELATED PROPERTIES
@@ -300,7 +299,7 @@
          * <p>Type: <code>java.lang.Boolean</code></p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_DEFAULT_CHOICE}</p>
          */
-        public static final Integer IS_DEFAULT_CHOICE = new Integer(40);
+        IS_DEFAULT_CHOICE,
         
         /**
          * <p>This property of a choice node indicates that, by 
@@ -313,7 +312,7 @@
          * <p>Type: <code>java.lang.Boolean</code></p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_EXCEPTION_ON_DEFAULT}</p>
          */
-        public static final Integer EXCEPTION_ON_DEFAULT = new Integer(42);
+        EXCEPTION_ON_DEFAULT,
 
         // ========================================================================
         // RECURSI0N RELATED PROPERTIES
@@ -324,7 +323,7 @@
          * <p>Type: <code>java.lang.Boolean</code></p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_RECURSIVE}</p>
          */
-        public static final Integer IS_RECURSIVE = new Integer(59);
+        IS_RECURSIVE,
 
         /**
          * The criteria of a node representing the root of a recursive
@@ -332,7 +331,7 @@
          * recursion should terminate.  i.e. "resultSetName.employeeName = 'Jones'"
          * @see #RECURSION_LIMIT
          */
-        public static final Integer RECURSION_CRITERIA = new Integer(50);
+        RECURSION_CRITERIA,
 
         /**
          * The recursion limit of a recursive XML fragment - if the 
@@ -343,7 +342,7 @@
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_RECURSION_LIMIT}</p>
          * @see #EXCEPTION_ON_RECURSION_LIMIT
          */
-        public static final Integer RECURSION_LIMIT = new Integer(51);
+        RECURSION_LIMIT,
 
         /**
          * If recursion is terminated due to the safeguard {@link #RECURSION_LIMIT} being
@@ -353,7 +352,7 @@
          * @see #RECURSION_CRITERIA
          * @see #RECURSION_LIMIT
          */
-        public static final Integer EXCEPTION_ON_RECURSION_LIMIT = new Integer(52);
+        EXCEPTION_ON_RECURSION_LIMIT,
 
         /**
          * This property should be set on each document node at which a recursive
@@ -363,14 +362,14 @@
          * document).
          * <p>Type: <code>java.lang.String</code></p>
          */
-        public static final Integer RECURSION_ROOT_MAPPING_CLASS = new Integer(53);
+        RECURSION_ROOT_MAPPING_CLASS,
         
         /**
          * Indicates if the node is the root of a recursive XML fragment or not.
          * <p>Type: <code>java.lang.Boolean</code></p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_IS_RECURSIVE_ROOT}</p>
          */
-        public static final Integer IS_RECURSIVE_ROOT = new Integer(54);
+        IS_RECURSIVE_ROOT,
         
         // ==================================================================================
         // DOCUMENT PROPERTIES (read from root node only, applicable to document as a whole)
@@ -381,7 +380,7 @@
          * set at the root MappingNode of the document.</p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_DOCUMENT_ENCODING}</p>
          */
-        public static final Integer DOCUMENT_ENCODING = new Integer(80);
+        DOCUMENT_ENCODING,
         
         /**
          * <p>Indicates whether the document will be outputted as a compressed
@@ -391,14 +390,14 @@
          * <p>Type: <code>java.lang.Boolean</code></p>
          * <p>Default: {@link MappingNodeConstants.Defaults#DEFAULT_FORMATTED_DOCUMENT}</p>
          */
-        public static final Integer FORMATTED_DOCUMENT = new Integer(81);
+        FORMATTED_DOCUMENT,
         
         /**
          * A property to mark to implicity include a node which needs to be 
          * added to result document. The implicit nodes are such nodes which
          * define the encoding information and type defination information.
          */
-        public static final Integer ALWAYS_INCLUDE = new Integer(82); 
+        ALWAYS_INCLUDE, 
         
         /**
          * In the case of the recursive mapping element nodes, the source nodes
@@ -406,13 +405,13 @@
          * (i.e. mapping class in recurive node) is alias to the source node which is
          * above the recursive node.
          */
-        public static final Integer ALIAS_RESULT_SET_NAME = new Integer(83);
+        ALIAS_RESULT_SET_NAME,
      
         /**
          * Result Set Info object which contains the query and the plan for
          * the source node.
          */
-        public static final Integer RESULT_SET_INFO = new Integer(84);        
+        RESULT_SET_INFO,        
     }
 
     // =========================================================================
@@ -487,11 +486,11 @@
          * manner.  Some tags are left out that the MappingOutputter 
          * handles separately.
          */
-        static final List OUTPUTTER_PROPERTY_TAGS;
+        static final List<String> OUTPUTTER_PROPERTY_TAGS;
         
         // Initialize static variables...
         static {
-            List temp = Arrays.asList( new String[]{
+            List<String> temp = Arrays.asList( new String[]{
                 MappingNodeConstants.Tags.NAME, 
                 MappingNodeConstants.Tags.NODE_TYPE, 
                 MappingNodeConstants.Tags.NAMESPACE_PREFIX, 
@@ -535,7 +534,7 @@
      * defined in {@link Properties}
      * @see getPropertyString
      */
-    public static final Integer getPropertyInteger(String property) {
+    public static final MappingNodeConstants.Properties getProperty(String property) {
         if(property.equals(Tags.NAME)) return Properties.NAME;
         else if (property.equals(Tags.NAMESPACE_PREFIX)) return Properties.NAMESPACE_PREFIX;
         else if (property.equals(Tags.NODE_TYPE)) return Properties.NODE_TYPE;
@@ -626,7 +625,7 @@
          * {@link MappingNodeConstants.Properties}.  The {@link MappingNode} class will return
          * these values if none are defined, for each property.
          */
-        public static final Map DEFAULT_VALUES;
+        public static final Map<Properties, Object> DEFAULT_VALUES;
         
         /** The default minimum bound of the cardinality of a node. */
         public static final Integer DEFAULT_CARDINALITY_MINIMUM_BOUND = new Integer(1);
@@ -695,7 +694,7 @@
         public static final Boolean DEFAULT_FORMATTED_DOCUMENT = Boolean.FALSE;
 
         static{
-            HashMap temp = new HashMap();
+            HashMap<Properties, Object> temp = new HashMap<Properties, Object>();
             temp.put(Properties.CARDINALITY_MIN_BOUND, DEFAULT_CARDINALITY_MINIMUM_BOUND);
             temp.put(Properties.CARDINALITY_MAX_BOUND, DEFAULT_CARDINALITY_MAXIMUM_BOUND);
             temp.put(Properties.NODE_TYPE, DEFAULT_NODE_TYPE);

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingOutputter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -129,10 +129,10 @@
      * @throws XMLStreamException 
      */
     void addElementProperties(Map properties ) throws XMLStreamException {
-        Iterator propNames = MappingNodeConstants.Tags.OUTPUTTER_PROPERTY_TAGS.iterator();
+        Iterator<String> propNames = MappingNodeConstants.Tags.OUTPUTTER_PROPERTY_TAGS.iterator();
         while ( propNames.hasNext() ) {
-            String propName = (String)propNames.next();
-            Integer propKey = MappingNodeConstants.getPropertyInteger(propName);
+            String propName = propNames.next();
+            MappingNodeConstants.Properties propKey = MappingNodeConstants.getProperty(propName);
             if ( properties.containsKey(propKey) ) {
                 Object value = properties.get(propKey);
                 addElementProperty( propName, value );

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingRecursiveElement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,8 +22,6 @@
 
 package org.teiid.query.mapping.xml;
 
-import java.util.List;
-
 import org.teiid.query.sql.lang.Criteria;
 
 
@@ -34,7 +32,6 @@
  * upto given depth limit. 
  */
 public class MappingRecursiveElement extends MappingElement {
-    List criteriaGroups;
     Criteria criteriaNode;    
     
     public MappingRecursiveElement(String name, String mappingClass) {
@@ -114,19 +111,6 @@
     }
    
     /**
-     * Groups that are referenced inthe criteria string. This is set by ValidateMappedCriteriaVisitor
-     * class during the preplan.
-     * @param criteriaGroups
-     */
-    public void setGroupsInCriteria(List criteriaGroups) {
-        this.criteriaGroups = criteriaGroups;
-    }
-
-    public List getGroupsInCriteria() {
-        return this.criteriaGroups;
-    }    
-    
-    /**
      * This is parsed and resolved criteria node based on the criteria string. This is set by
      * ValidateMappedCriteriaVisitor class during pre planning.
      * @param node

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/MappingVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,6 +40,9 @@
         return abort;
     }    
     
+    /**
+	 * @param node  
+	 */
     public void visit(MappingNode node) {}
     
     public void visit(MappingDocument doc) {
@@ -80,14 +83,14 @@
      */
     protected void walkChildNodes(MappingNode element) {
 
-        List children = element.getNodeChildren();
-        for(Iterator i=children.iterator(); i.hasNext();) {
+        List<MappingNode> children = element.getNodeChildren();
+        for(Iterator<MappingNode> i=children.iterator(); i.hasNext();) {
             
             if (shouldAbort()) {
                 break;
             }
             
-            MappingNode node = (MappingNode)i.next();            
+            MappingNode node = i.next();            
             node.acceptVisitor(this);
         }
     }    

Modified: branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/mapping/xml/ResultSetInfo.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,6 +29,7 @@
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Insert;
 import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.symbol.ElementSymbol;
 
@@ -45,9 +46,6 @@
     // The result set command
     private Command rsCommand;
     
-    // The bound references for this result set: List<Reference>
-    private List boundReferences;
-
     // The processor plan output for the result set 
     private ProcessorPlan rsPlan;
     
@@ -61,25 +59,25 @@
     
     private Criteria criteria;
     
-    private Set criteriaResultSets = new HashSet();
+    private Set<MappingSourceNode> criteriaResultSets = new HashSet<MappingSourceNode>();
     
     private boolean criteriaRaised = false;
     
-    private boolean stagedResult = false;
-    
-    //joined source node state
-    private boolean joinedWithParent = false;
-    private boolean joinRoot = false;
-    private int mappingClassNumber = 0;
     private ElementSymbol mappingClassSymbol;
+	private boolean inputSet;
+	private boolean isCritNullDependent;
+
+	//auto-staging related info
+	private String stagingRoot;
+	private String tempTable;
+	private Command tempSelect;
+	private Insert tempInsert;
+	private Command tempDrop;
+	private boolean isAutoStaged;
+	private List<ElementSymbol> fkColumns;
     
     public ResultSetInfo(String resultName) {
-        this(resultName, false);
-    }
-    
-    public ResultSetInfo(String resultName, boolean staged) {
         this.resultSetName = resultName;
-        this.stagedResult = staged;
     }    
     
     public String getResultSetName() {
@@ -131,11 +129,11 @@
         this.orderBy = orderBy;
     }
     
-    public Set getCriteriaResultSets() {
+    public Set<MappingSourceNode> getCriteriaResultSets() {
         return this.criteriaResultSets;
     }
 
-    public void addToCriteriaResultSets(Set criteriaResultSets) {
+    public void addToCriteriaResultSets(Set<MappingSourceNode> criteriaResultSets) {
         this.criteriaResultSets.addAll(criteriaResultSets);
     }    
     
@@ -148,17 +146,19 @@
     }    
     
     public Object clone() {
-        ResultSetInfo clone = new ResultSetInfo(this.resultSetName, this.stagedResult);
+        ResultSetInfo clone = new ResultSetInfo(this.resultSetName);
         clone.rsPlan = this.rsPlan;
-        clone.boundReferences = this.boundReferences;
         clone.userRowLimit = this.userRowLimit;
         clone.exceptionOnRowLimit = this.exceptionOnRowLimit;
         clone.rsCommand = (Command)this.rsCommand.clone();
         clone.criteriaRaised = this.criteriaRaised;
-        clone.joinedWithParent = this.joinedWithParent;
-        clone.joinRoot = this.joinRoot;
-        clone.mappingClassNumber = this.mappingClassNumber;
         clone.mappingClassSymbol = this.mappingClassSymbol;
+        clone.tempInsert = this.tempInsert;
+        clone.tempSelect = this.tempSelect;
+        clone.tempTable = this.tempTable;
+        clone.tempDrop = this.tempDrop;
+        clone.isAutoStaged = this.isAutoStaged;
+        clone.fkColumns = this.fkColumns;
         return clone;
     }
     
@@ -166,39 +166,83 @@
         return resultSetName + ", resultSetObject " + rsCommand; //$NON-NLS-1$
     }
 
-    public boolean isJoinedWithParent() {
-        return this.joinedWithParent;
+    public ElementSymbol getMappingClassSymbol() {
+        return this.mappingClassSymbol;
     }
 
-    public void setJoinedWithParent(boolean joinedWithParent) {
-        this.joinedWithParent = joinedWithParent;
+    public void setMappingClassSymbol(ElementSymbol mappingClassSymbol) {
+        this.mappingClassSymbol = mappingClassSymbol;
     }
 
-    public boolean isJoinRoot() {
-        return this.joinRoot;
-    }
+	public boolean hasInputSet() {
+		return inputSet;
+	}
 
-    public void setJoinRoot(boolean joinRoot) {
-        this.joinRoot = joinRoot;
-    }
+	public void setInputSet(boolean inputSet) {
+		this.inputSet = inputSet;
+	}
+	
+	public void setCritNullDependent(boolean isCritNullDependent) {
+		this.isCritNullDependent = isCritNullDependent;
+	}
+	
+	public boolean isCritNullDependent(){
+		return this.isCritNullDependent;
+	}
+	
+	public String getStagingRoot() {
+		return stagingRoot;
+	}
+	
+	public void setStagingRoot(String stagingRoot) {
+		this.stagingRoot = stagingRoot;
+	}
 
-    public int getMappingClassNumber() {
-        return this.mappingClassNumber;
-    }
+	public void setTempSelect(Command tempSelect) {
+		this.tempSelect = tempSelect;
+	}
+	
+	public Command getTempSelect() {
+		return tempSelect;
+	}
+	
+	public void setTempInsert(Insert tempInsert) {
+		this.tempInsert = tempInsert;
+	}
+	
+	public Insert getTempInsert() {
+		return tempInsert;
+	}
+	
+	public Command getTempDrop() {
+		return tempDrop;
+	}
+	
+	public void setTempDrop(Command tempDrop) {
+		this.tempDrop = tempDrop;
+	}
 
-    public void setMappingClassNumber(int mappingClassNumber) {
-        this.mappingClassNumber = mappingClassNumber;
-    }
+	public String getTempTable() {
+		return tempTable;
+	}
+	
+	public void setTempTable(String rsTempTable) {
+		this.tempTable = rsTempTable;
+	}
+	
+	public boolean isAutoStaged() {
+		return isAutoStaged;
+	}
+	
+	public void setAutoStaged(boolean isAutoStaged) {
+		this.isAutoStaged = isAutoStaged;
+	}
 
-    public ElementSymbol getMappingClassSymbol() {
-        return this.mappingClassSymbol;
-    }
+	public void setFkColumns(List<ElementSymbol> fkColumns) {
+		this.fkColumns = fkColumns;
+	}
 
-    public void setMappingClassSymbol(ElementSymbol mappingClassSymbol) {
-        this.mappingClassSymbol = mappingClassSymbol;
-    }
-
-    public boolean isStagedResult() {
-        return this.stagedResult;
-    }
+	public List<ElementSymbol> getFkColumns() {
+		return this.fkColumns;
+	}
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/metadata/CompositeMetadataStore.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -137,9 +137,6 @@
 				}
 			}
 		}
-		if (result.isEmpty()) {
-	        throw new QueryMetadataException(name.substring(1)+TransformationMetadata.NOT_EXISTS_MESSAGE);
-		}
 		return result;
 	}
 
@@ -149,7 +146,7 @@
 
 	public Collection<Table> getXMLTempGroups(Table tableRecord) {
 		ArrayList<Table> results = new ArrayList<Table>();
-		String namePrefix = tableRecord.getFullName() + TransformationMetadata.DELIMITER_STRING;
+		String namePrefix = tableRecord.getName() + TransformationMetadata.DELIMITER_STRING;
 		for (Table table : tableRecord.getParent().getTables().values()) {
 			if (table.getTableType() == Type.XmlStagingTable && table.getName().startsWith(namePrefix)) {
 				results.add(table);

Modified: branches/as7/engine/src/main/java/org/teiid/query/metadata/TempCapabilitiesFinder.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/metadata/TempCapabilitiesFinder.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/metadata/TempCapabilitiesFinder.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -52,6 +52,8 @@
 	    		tempCaps.setCapabilitySupport(Capability.CRITERIA_ISNULL, true);
 	    		tempCaps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
 	    		tempCaps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
+	    		tempCaps.setCapabilitySupport(Capability.CRITERIA_LIKE_REGEX, true);
+	    		tempCaps.setCapabilitySupport(Capability.CRITERIA_SIMILAR, true);
 	    		tempCaps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
     		}
     		return tempCaps;

Modified: branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataAdapter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,9 +33,11 @@
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.StringUtil;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.mapping.xml.MappingNode;
+import org.teiid.query.metadata.TempMetadataID.Type;
 
 
 /**
@@ -154,6 +156,19 @@
         throw new QueryMetadataException(msg);
     }
 
+    @Override
+    public Collection getGroupsForPartialName(String partialGroupName)
+    		throws TeiidComponentException, QueryMetadataException {
+    	Collection groups = super.getGroupsForPartialName(partialGroupName);
+    	ArrayList<String> allGroups = new ArrayList<String>(groups);
+    	for (String name : tempStore.getData().keySet()) {
+    		if (StringUtil.endsWithIgnoreCase(name, partialGroupName) 
+    				&& (name.length() == partialGroupName.length() || (name.length() > partialGroupName.length() && name.charAt(name.length() - partialGroupName.length() - 1) == '.'))) {
+    			allGroups.add(name);
+    		}
+    	}
+    	return allGroups;
+    }
 
     public Object getModelID(Object groupOrElementID)
         throws TeiidComponentException, QueryMetadataException {
@@ -310,7 +325,7 @@
             return true;
         }
         
-        if(groupID instanceof TempMetadataID) {                         
+        if(groupID instanceof TempMetadataID && !(actualMetadata instanceof TempMetadataAdapter)) {                         
             return false;
         }   
                 
@@ -332,7 +347,7 @@
             }
         }
         
-        if(groupID instanceof TempMetadataID) {                         
+        if(groupID instanceof TempMetadataID && !(actualMetadata instanceof TempMetadataAdapter)) {                         
             return null;
         }   
 
@@ -483,7 +498,7 @@
         throws TeiidComponentException, QueryMetadataException {
 
         if(groupID instanceof TempMetadataID) {
-            return false;
+            return ((TempMetadataID)groupID).getMetadataType() == Type.XML;
         }
         return this.actualMetadata.isXMLGroup(groupID);
     }

Modified: branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/metadata/TempMetadataID.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -93,7 +93,8 @@
 	public enum Type {
 		VIRTUAL,
 		TEMP,
-		SCALAR
+		SCALAR,
+		XML
 	}
 	
     private String ID;      // never null, upper cased fully-qualified string

Modified: branches/as7/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/metadata/TransformationMetadata.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -54,7 +54,7 @@
  */
 public class TransformationMetadata extends BasicQueryMetadata implements Serializable {
 	
-	private final class LiveQueryNode extends QueryNode {
+	private static final class LiveQueryNode extends QueryNode {
 		Procedure p;
 		private LiveQueryNode(Procedure p) {
 			super(null);
@@ -65,7 +65,19 @@
 			return p.getQueryPlan();
 		}
 	}
+	
+	private static final class LiveTableQueryNode extends QueryNode {
+		Table t;
+		private LiveTableQueryNode(Table t) {
+			super(null);
+			this.t = t;
+		}
 
+		public String getQuery() {
+			return t.getSelectTransformation();
+		}
+	}
+
 	private final class VirtualFileInputStreamFactory extends
 			InputStreamFactory {
 		private final VirtualFile f;
@@ -158,14 +170,14 @@
     //                     I N T E R F A C E   M E T H O D S
     //==================================================================================
 
-    public Object getElementID(final String elementName) throws TeiidComponentException, QueryMetadataException {
+    public Column getElementID(final String elementName) throws TeiidComponentException, QueryMetadataException {
     	int columnIndex = elementName.lastIndexOf(TransformationMetadata.DELIMITER_STRING);
 		if (columnIndex == -1) {
 			throw new QueryMetadataException(elementName+TransformationMetadata.NOT_EXISTS_MESSAGE);
 		}
 		Table table = this.store.findGroup(elementName.substring(0, columnIndex).toUpperCase());
 		String shortElementName = elementName.substring(columnIndex + 1);
-		for (Column column : (List<Column>)getElementIDsInGroupID(table)) {
+		for (Column column : getElementIDsInGroupID(table)) {
 			if (column.getName().equalsIgnoreCase(shortElementName)) {
 				return column;
 			}
@@ -233,7 +245,7 @@
         return metadataRecord.getName();
     }
 
-    public List getElementIDsInGroupID(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+    public List<Column> getElementIDsInGroupID(final Object groupID) throws TeiidComponentException, QueryMetadataException {
     	ArgCheck.isInstanceOf(Table.class, groupID);
     	return ((Table)groupID).getColumns();
     }
@@ -246,6 +258,10 @@
             	return parent;
             }
         } 
+        if(elementID instanceof ProcedureParameter) {
+        	ProcedureParameter columnRecord = (ProcedureParameter) elementID;
+            return columnRecord.getParent();
+        }
         throw createInvalidRecordTypeException(elementID);
     }
     
@@ -276,7 +292,10 @@
         Collection<StoredProcedureInfo> results = this.procedureCache.get(canonicalName);
         
         if (results == null) {
-        	Collection<Procedure> procRecords = getMetadataStore().getStoredProcedure(canonicalName); 
+        	Collection<Procedure> procRecords = getMetadataStore().getStoredProcedure(canonicalName);
+        	if (procRecords.isEmpty()) {
+        		return null;
+        	}
         	results = new ArrayList<StoredProcedureInfo>(procRecords.size());
         	for (Procedure procRecord : procRecords) {
                 String procedureFullName = procRecord.getFullName();
@@ -433,8 +452,7 @@
         if (!tableRecord.isVirtual()) {
             throw new QueryMetadataException(QueryPlugin.Util.getString("TransformationMetadata.QueryPlan_could_not_be_found_for_physical_group__6")+tableRecord.getFullName()); //$NON-NLS-1$
         }
-        String transQuery = tableRecord.getSelectTransformation();
-        QueryNode queryNode = new QueryNode(transQuery);
+        LiveTableQueryNode queryNode = new LiveTableQueryNode(tableRecord);
 
         // get any bindings and add them onto the query node
         List bindings = tableRecord.getBindings();
@@ -680,13 +698,19 @@
         ArgCheck.isInstanceOf(Table.class, groupID);
 
         Table tableRecord = (Table) groupID;
+        
+        MappingDocument mappingDoc = tableRecord.getAttachment(MappingDocument.class);
+        
+        if (mappingDoc != null) {
+        	return mappingDoc;
+        }
+        
 		final String groupName = tableRecord.getFullName();
         if(tableRecord.isVirtual()) {
-            // get mappin transform
+            // get mapping transform
             String document = tableRecord.getSelectTransformation();            
             InputStream inputStream = new ByteArrayInputStream(document.getBytes());
             MappingLoader reader = new MappingLoader();
-            MappingDocument mappingDoc = null;
             try{
                 mappingDoc = reader.loadDocument(inputStream);
                 mappingDoc.setName(groupName);
@@ -697,7 +721,8 @@
 					inputStream.close();
             	} catch(Exception e) {}
             }
-            return (MappingDocument)mappingDoc.clone();
+            tableRecord.addAttchment(MappingDocument.class, mappingDoc);
+            return mappingDoc;
         }
 
         return null;
@@ -727,14 +752,14 @@
     /**
      * @see org.teiid.query.metadata.QueryMetadataInterface#getXMLTempGroups(java.lang.Object)
      */
-    public Collection getXMLTempGroups(final Object groupID) throws TeiidComponentException, QueryMetadataException {
+    public Collection<Table> getXMLTempGroups(final Object groupID) throws TeiidComponentException, QueryMetadataException {
         ArgCheck.isInstanceOf(Table.class, groupID);
         Table tableRecord = (Table) groupID;
 
         if(tableRecord.getTableType() == Table.Type.Document) {
             return this.store.getXMLTempGroups(tableRecord);
         }
-        return Collections.EMPTY_SET;
+        return Collections.emptySet();
     }
 
     public int getCardinality(final Object groupID) throws TeiidComponentException, QueryMetadataException {

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/BatchedUpdatePlanner.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/BatchedUpdatePlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/BatchedUpdatePlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,7 +30,6 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.id.IDGenerator;
-import org.teiid.core.id.IntegerID;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.metadata.QueryMetadataInterface;
@@ -142,9 +141,9 @@
                     }
                     // If two or more contiguous commands made on the same model were found, then batch them
                     if (batch.size() > 1) {
-                        ProjectNode projectNode = new ProjectNode(((IntegerID)idGenerator.create()).getValue());
+                        ProjectNode projectNode = new ProjectNode(idGenerator.nextInt());
                         // Create a BatchedUpdateNode that creates a batched request for the connector
-                        BatchedUpdateNode batchNode = new BatchedUpdateNode(((IntegerID)idGenerator.create()).getValue(),
+                        BatchedUpdateNode batchNode = new BatchedUpdateNode(idGenerator.nextInt(),
                                                                             batch, contexts, shouldEvaluate,
                                                                             modelName);
                         List symbols = batchedUpdateCommand.getProjectedSymbols();

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/ProcedurePlanner.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/ProcedurePlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/ProcedurePlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,8 +36,7 @@
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.processor.proc.AssignmentInstruction;
-import org.teiid.query.processor.proc.BreakInstruction;
-import org.teiid.query.processor.proc.ContinueInstruction;
+import org.teiid.query.processor.proc.BranchingInstruction;
 import org.teiid.query.processor.proc.CreateCursorResultSetInstruction;
 import org.teiid.query.processor.proc.ErrorInstruction;
 import org.teiid.query.processor.proc.ExecDynamicSqlInstruction;
@@ -53,6 +52,7 @@
 import org.teiid.query.sql.lang.StoredProcedure;
 import org.teiid.query.sql.proc.AssignmentStatement;
 import org.teiid.query.sql.proc.Block;
+import org.teiid.query.sql.proc.BranchingStatement;
 import org.teiid.query.sql.proc.CommandStatement;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.proc.IfStatement;
@@ -148,7 +148,8 @@
         // Generate program and add instructions
         // this program represents the block on the procedure
         // instruction in the program would correspond to statements in the block
-        Program programBlock = new Program();
+        Program programBlock = new Program(block.isAtomic());
+        programBlock.setLabel(block.getLabel());
 
 		// plan each statement in the block
         for (Statement statement : block.getStatements()) {
@@ -281,19 +282,14 @@
 				break;
             }
             case Statement.TYPE_BREAK:
-            {
-                if(debug) {
-                	analysisRecord.println("\tBREAK STATEMENT:\n" + statement); //$NON-NLS-1$
-                }
-                instruction = new BreakInstruction();
-                break;
-            }
             case Statement.TYPE_CONTINUE:
+            case Statement.TYPE_LEAVE:
             {
+            	BranchingStatement bs = (BranchingStatement)statement;
                 if(debug) {
-                	analysisRecord.println("\tCONTINUE STATEMENT:\n" + statement); //$NON-NLS-1$
+                	analysisRecord.println("\t" + statement); //$NON-NLS-1$
                 }
-                instruction = new ContinueInstruction();
+                instruction = new BranchingInstruction(bs);
                 break;
             }
             case Statement.TYPE_LOOP:
@@ -307,7 +303,7 @@
                 ProcessorPlan commandPlan = loopStmt.getCommand().getProcessorPlan();
 
                 Program loopProgram = planBlock(parentProcCommand, loopStmt.getBlock(), metadata, debug, idGenerator, capFinder, analysisRecord, context);
-                instruction = new LoopInstruction(loopProgram, rsName, commandPlan);
+                instruction = new LoopInstruction(loopProgram, rsName, commandPlan, loopStmt.getLabel());
                 break;
             }
             case Statement.TYPE_WHILE:
@@ -317,7 +313,7 @@
                 if(debug) {
                 	analysisRecord.println("\tWHILE STATEMENT:\n" + statement); //$NON-NLS-1$
                 }
-                instruction = new WhileInstruction(whileProgram, whileStmt.getCondition());
+                instruction = new WhileInstruction(whileProgram, whileStmt.getCondition(), whileStmt.getLabel());
                 break;
             }
 			default:

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/QueryOptimizer.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/QueryOptimizer.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/QueryOptimizer.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,7 +34,6 @@
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.id.IDGenerator;
-import org.teiid.core.id.IntegerIDFactory;
 import org.teiid.dqp.internal.process.PreparedPlan;
 import org.teiid.metadata.Procedure;
 import org.teiid.metadata.FunctionMethod.Determinism;
@@ -99,7 +98,6 @@
         // Create an ID generator that can be used for all plans to generate unique data node IDs
         if(idGenerator == null) {
             idGenerator = new IDGenerator();
-            idGenerator.setDefaultFactory(new IntegerIDFactory());
         }
         
 		if(debug) {

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/BasicSourceCapabilities.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,10 +29,12 @@
  */
 public class BasicSourceCapabilities implements SourceCapabilities, Serializable {
 
-    private Scope scope = Scope.SCOPE_GLOBAL;
-    private Map capabilityMap = new HashMap();
-    private Map functionMap = new HashMap();
-    private Map propertyMap = new HashMap();
+	private static final long serialVersionUID = -1779069588746365579L;
+	
+	private Scope scope = Scope.SCOPE_GLOBAL;
+    private Map<Capability, Boolean> capabilityMap = new HashMap<Capability, Boolean>();
+    private Map<String, Boolean> functionMap = new TreeMap<String, Boolean>(String.CASE_INSENSITIVE_ORDER);
+    private Map<Capability, Object> propertyMap = new HashMap<Capability, Object>();
 
     /**
      * Construct a basic capabilities object.
@@ -41,12 +43,12 @@
     }
 
     public boolean supportsCapability(Capability capability) {
-        Boolean supports = (Boolean) capabilityMap.get(capability);
+        Boolean supports = capabilityMap.get(capability);
         return (supports == null) ? false : supports.booleanValue();
     }
 
     public boolean supportsFunction(String functionName) {
-        Boolean supports = (Boolean) functionMap.get(functionName);
+        Boolean supports = functionMap.get(functionName);
         return (supports == null) ? false : supports.booleanValue();
     }
     

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/capabilities/SourceCapabilities.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -321,6 +321,12 @@
         INSERT_WITH_ITERATOR,
         COMMON_TABLE_EXPRESSIONS,
         MAX_DEPENDENT_PREDICATES,
+        ADVANCED_OLAP, 
+        QUERY_AGGREGATES_ARRAY, 
+        ELEMENTARY_OLAP, 
+        WINDOW_FUNCTION_ORDER_BY_AGGREGATES,
+        CRITERIA_SIMILAR,
+        CRITERIA_LIKE_REGEX
     }
 
     public enum Scope {
@@ -354,8 +360,7 @@
      * used if the capability FUNCTION is true.
      * 
      * @param functionName
-     *            The function that may be supported (see MetaMatrix documentation for further definition of the functions and
-     *            their parameters.)
+     *            The function that may be supported
      * @return True if function is supported.
      */
     public boolean supportsFunction(String functionName);

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,14 +26,13 @@
 import java.util.Collection;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.core.CoreConstants;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.id.IDGenerator;
-import org.teiid.core.id.IntegerID;
-import org.teiid.core.id.IntegerIDFactory;
 import org.teiid.core.util.Assertion;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.analysis.AnalysisRecord;
@@ -47,12 +46,15 @@
 import org.teiid.query.optimizer.relational.plantree.NodeConstants.Info;
 import org.teiid.query.optimizer.relational.rules.CapabilitiesUtil;
 import org.teiid.query.optimizer.relational.rules.FrameUtil;
+import org.teiid.query.optimizer.relational.rules.RuleAssignOutputElements;
+import org.teiid.query.optimizer.relational.rules.RuleChooseJoinStrategy;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.processor.relational.AccessNode;
 import org.teiid.query.processor.relational.ArrayTableNode;
 import org.teiid.query.processor.relational.DependentAccessNode;
 import org.teiid.query.processor.relational.DependentProcedureAccessNode;
 import org.teiid.query.processor.relational.DependentProcedureExecutionNode;
+import org.teiid.query.processor.relational.EnhancedSortMergeJoinStrategy;
 import org.teiid.query.processor.relational.GroupingNode;
 import org.teiid.query.processor.relational.InsertPlanExecutionNode;
 import org.teiid.query.processor.relational.JoinNode;
@@ -61,7 +63,6 @@
 import org.teiid.query.processor.relational.NestedLoopJoinStrategy;
 import org.teiid.query.processor.relational.NestedTableJoinStrategy;
 import org.teiid.query.processor.relational.NullNode;
-import org.teiid.query.processor.relational.EnhancedSortMergeJoinStrategy;
 import org.teiid.query.processor.relational.PlanExecutionNode;
 import org.teiid.query.processor.relational.ProjectIntoNode;
 import org.teiid.query.processor.relational.ProjectNode;
@@ -71,6 +72,7 @@
 import org.teiid.query.processor.relational.SortNode;
 import org.teiid.query.processor.relational.TextTableNode;
 import org.teiid.query.processor.relational.UnionAllNode;
+import org.teiid.query.processor.relational.WindowFunctionProjectNode;
 import org.teiid.query.processor.relational.XMLTableNode;
 import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
 import org.teiid.query.processor.relational.MergeJoinStrategy.SortOption;
@@ -82,6 +84,7 @@
 import org.teiid.query.sql.lang.Insert;
 import org.teiid.query.sql.lang.JoinType;
 import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.QueryCommand;
 import org.teiid.query.sql.lang.StoredProcedure;
@@ -92,7 +95,10 @@
 import org.teiid.query.sql.lang.XMLTable.XMLColumn;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.sql.visitor.EvaluatableVisitor;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
@@ -169,8 +175,7 @@
 	}
 
     protected int getID() {
-        IntegerIDFactory intFactory = (IntegerIDFactory) idGenerator.getDefaultFactory();
-        return ((IntegerID) intFactory.create()).getValue();
+        return idGenerator.nextInt();
     }
     
 	protected RelationalNode convertNode(PlanNode node)
@@ -216,11 +221,25 @@
                     }
 
                 } else {
-                    List symbols = (List) node.getProperty(NodeConstants.Info.PROJECT_COLS);
+                    List<SingleElementSymbol> symbols = (List) node.getProperty(NodeConstants.Info.PROJECT_COLS);
                     
                     ProjectNode pnode = new ProjectNode(getID());
                     pnode.setSelectSymbols(symbols);
             		processNode = pnode;
+            		
+            		if (node.hasBooleanProperty(Info.HAS_WINDOW_FUNCTIONS)) {
+            			WindowFunctionProjectNode wfpn = new WindowFunctionProjectNode(getID());
+            			Set<WindowFunction> windowFunctions = RuleAssignOutputElements.getWindowFunctions(symbols);
+            			//TODO: check for selecting all window functions
+            			List<SingleElementSymbol> outputElements = new ArrayList<SingleElementSymbol>(windowFunctions);
+            			//collect the other projected expressions
+            			for (SingleElementSymbol singleElementSymbol : (List<SingleElementSymbol>)node.getFirstChild().getProperty(Info.OUTPUT_COLS)) {
+							outputElements.add(singleElementSymbol);
+						}
+            			wfpn.setElements(outputElements);
+            			wfpn.init();
+            			pnode.addChild(wfpn);
+            		}
                 }
                 break;
 
@@ -238,7 +257,9 @@
                 if(stype == JoinStrategyType.MERGE || stype == JoinStrategyType.ENHANCED_SORT) {
                 	MergeJoinStrategy mjStrategy = null;
                 	if (stype.equals(JoinStrategyType.ENHANCED_SORT)) { 
-                		mjStrategy = new EnhancedSortMergeJoinStrategy(leftSort, (SortOption)node.getProperty(NodeConstants.Info.SORT_RIGHT));
+                		EnhancedSortMergeJoinStrategy esmjStrategy = new EnhancedSortMergeJoinStrategy(leftSort, (SortOption)node.getProperty(NodeConstants.Info.SORT_RIGHT));
+                		esmjStrategy.setSemiDep(node.hasBooleanProperty(Info.IS_SEMI_DEP));
+                		mjStrategy = esmjStrategy;
                 	} else {
                 		mjStrategy = new MergeJoinStrategy(leftSort, (SortOption)node.getProperty(NodeConstants.Info.SORT_RIGHT), false);
                 	}
@@ -341,7 +362,10 @@
 	                    }
                     }
                     aNode.setCommand(command);
-                    aNode.setModelName(getRoutingName(node));
+                    if (!aNode.isShouldEvaluate()) {
+                    	aNode.minimizeProject(command);
+                    }
+                    setRoutingName(aNode, node);
                 }
                 break;
 
@@ -372,8 +396,32 @@
 				break;
 			case NodeConstants.Types.GROUP:
 				GroupingNode gnode = new GroupingNode(getID());
-				gnode.setGroupingElements( (List) node.getProperty(NodeConstants.Info.GROUP_COLS) );
+				SymbolMap groupingMap = (SymbolMap)node.getProperty(NodeConstants.Info.SYMBOL_MAP);
+				gnode.setOutputMapping(groupingMap);
 				gnode.setRemoveDuplicates(node.hasBooleanProperty(NodeConstants.Info.IS_DUP_REMOVAL));
+				List<Expression> gCols = (List) node.getProperty(NodeConstants.Info.GROUP_COLS);
+				orderBy = (OrderBy) node.getProperty(Info.SORT_ORDER);
+				if (orderBy == null) {
+			        if (gCols != null) {
+		                orderBy = new OrderBy(RuleChooseJoinStrategy.createExpressionSymbols(gCols));
+			        }
+				} else {
+			        for (int i = 0; i < gCols.size(); i++) {
+			        	if (i < orderBy.getOrderByItems().size()) {
+			        		OrderByItem orderByItem = orderBy.getOrderByItems().get(i);
+							Expression ex = SymbolMap.getExpression(orderByItem.getSymbol());
+				        	if (ex instanceof ElementSymbol) {
+			            		ex = groupingMap.getMappedExpression((ElementSymbol) ex);
+			            		orderByItem.setSymbol(new ExpressionSymbol("expr", ex)); //$NON-NLS-1$
+			            	}
+			        	} else {
+			        		orderBy.addVariable(new ExpressionSymbol("expr", gCols.get(i)), OrderBy.ASC); //$NON-NLS-1$
+			        	}
+			        }
+				}
+				if (orderBy != null) {
+			        gnode.setOrderBy(orderBy.getOrderByItems());
+				}
 				processNode = gnode;
 				break;
 
@@ -540,7 +588,7 @@
         return processNode;
     }
 
-	private String getRoutingName(PlanNode node)
+	private void setRoutingName(AccessNode accessNode, PlanNode node)
 		throws QueryPlannerException, TeiidComponentException {
 
 		// Look up connector binding name
@@ -558,7 +606,8 @@
 				}
 			}
 			String cbName = metadata.getFullName(modelID);
-			return cbName;
+			accessNode.setModelName(cbName);
+			accessNode.setModelId(modelID);
 		} catch(QueryMetadataException e) {
             throw new QueryPlannerException(e, QueryPlugin.Util.getString("ERR.015.004.0009")); //$NON-NLS-1$
 		}


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java:3149-3217
/trunk/engine/src/main/java/org/teiid/query/optimizer/relational/PlanToProcessConverter.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,6 +27,9 @@
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -45,9 +48,11 @@
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.BasicQueryMetadata;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.metadata.TempMetadataID;
+import org.teiid.query.metadata.TempMetadataStore;
 import org.teiid.query.optimizer.QueryOptimizer;
 import org.teiid.query.optimizer.TriggerActionPlanner;
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
@@ -62,7 +67,10 @@
 import org.teiid.query.optimizer.relational.rules.RuleCollapseSource;
 import org.teiid.query.optimizer.relational.rules.RuleConstants;
 import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria;
+import org.teiid.query.optimizer.relational.rules.RulePlaceAccess;
+import org.teiid.query.optimizer.relational.rules.RulePushAggregates;
 import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
 import org.teiid.query.processor.relational.RelationalPlan;
 import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
 import org.teiid.query.resolver.ProcedureContainerResolver;
@@ -103,17 +111,24 @@
 import org.teiid.query.sql.navigator.PreOrPostOrderNavigator;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.proc.TriggerAction;
-import org.teiid.query.sql.symbol.AllSymbol;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.AliasSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SelectSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
 import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
 import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
 import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
 import org.teiid.query.util.CommandContext;
@@ -177,11 +192,12 @@
 	        		Command subCommand = with.getCommand();
 	                ProcessorPlan procPlan = QueryOptimizer.optimizePlan(subCommand, metadata, idGenerator, capFinder, analysisRecord, context);
 	                subCommand.setProcessorPlan(procPlan);
-	                QueryCommand withCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(procPlan);
-	                if (withCommand != null && supportsWithPushdown) {
-	                	modelID = CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, withCommand);
+	                AccessNode aNode = CriteriaCapabilityValidatorVisitor.getAccessNode(procPlan);
+	                if (aNode != null && supportsWithPushdown) {
+	                	modelID = CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, aNode);
 	            	}
-	                if (modelID == null) {
+                	QueryCommand withCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(aNode);
+	                if (modelID == null || withCommand == null) {
 	                	supportsWithPushdown = false;
 	                } else {
 	                	if (pushDownWith == null) {
@@ -226,9 +242,10 @@
 
         RelationalPlan result = planToProcessConverter.convert(plan);
         if (withList != null && supportsWithPushdown) {
-        	QueryCommand queryCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(result);
-        	if (queryCommand != null) { 
-				if (CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, queryCommand) == null) {
+            AccessNode aNode = CriteriaCapabilityValidatorVisitor.getAccessNode(result);
+        	if (aNode != null) { 
+        		QueryCommand queryCommand = CriteriaCapabilityValidatorVisitor.getQueryCommand(aNode);
+				if (queryCommand == null || CriteriaCapabilityValidatorVisitor.validateCommandPushdown(modelID, metadata, capFinder, aNode) == null) {
 					supportsWithPushdown = false;
 				} else {
 					queryCommand.setWith(pushDownWith);
@@ -398,7 +415,7 @@
             rules.push(RuleConstants.PLAN_PROCEDURES);
         }
         if(hints.hasAggregates) {
-            rules.push(RuleConstants.PUSH_AGGREGATES);
+            rules.push(new RulePushAggregates(idGenerator));
         }
         if(hints.hasJoin) {
             rules.push(RuleConstants.CHOOSE_DEPENDENT);
@@ -708,6 +725,8 @@
 
         PlanNode plan = null;
 
+		LinkedHashSet<WindowFunction> windowFunctions = new LinkedHashSet<WindowFunction>();
+
         if(query.getFrom() != null){
             FromClause fromClause = mergeClauseTrees(query.getFrom());
             
@@ -726,9 +745,19 @@
     		}
 
     		// Attach grouping node on top
-    		if(query.hasAggregates()) {
-    			plan = attachGrouping(plan, query, hints);
+    		LinkedHashSet<AggregateSymbol> aggs = new LinkedHashSet<AggregateSymbol>();
+    		AggregateSymbolCollectorVisitor.getAggregates(query.getSelect(), aggs, null, null, windowFunctions, null);
+    		boolean hasGrouping = !aggs.isEmpty();
+    		if (query.getHaving() != null) {
+    			aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(query.getHaving(), true));
+    			hasGrouping = true;
     		}
+    		if (query.getGroupBy() != null) {
+    			hasGrouping = true;
+    		}
+    		if(hasGrouping) {
+    			plan = attachGrouping(plan, query, aggs);
+    		}
 
     		// Attach having criteria node on top
     		if(query.getHaving() != null) {
@@ -740,6 +769,12 @@
 
 		// Attach project on top
 		plan = attachProject(plan, query.getSelect());
+		if (query.getOrderBy() != null) {
+			AggregateSymbolCollectorVisitor.getAggregates(query.getOrderBy(), null, null, null, windowFunctions, null);
+		}
+		if (!windowFunctions.isEmpty()) {
+			plan.setProperty(Info.HAS_WINDOW_FUNCTIONS, true);
+		}
 
 		// Attach dup removal on top
 		if(query.getSelect().isDistinct()) {
@@ -753,16 +788,16 @@
      * Merges the from clause into a single join predicate if there are more than 1 from clauses
      */
     private static FromClause mergeClauseTrees(From from) {
-        List clauses = from.getClauses();
+        List<FromClause> clauses = from.getClauses();
         
         while (clauses.size() > 1) {
-            FromClause first = (FromClause)from.getClauses().remove(0);
-            FromClause second = (FromClause)from.getClauses().remove(0);
+            FromClause first = from.getClauses().remove(0);
+            FromClause second = from.getClauses().remove(0);
             JoinPredicate jp = new JoinPredicate(first, second, JoinType.JOIN_CROSS);
             clauses.add(0, jp);
         }
         
-        return (FromClause)clauses.get(0);
+        return clauses.get(0);
     }
     
     /**
@@ -864,6 +899,8 @@
             tt.setCorrelatedReferences(getCorrelatedReferences(parent, node, tt));
             node.addGroup(group);
             parent.addLastChild(node);
+        } else {
+        	throw new AssertionError("Unknown Type"); //$NON-NLS-1$
         }
         
         if (clause.isOptional()) {
@@ -876,6 +913,9 @@
         } else if (clause.isMakeNotDep()) {
             node.setProperty(NodeConstants.Info.MAKE_NOT_DEP, Boolean.TRUE);
         }
+        if (clause.isMakeInd()) {
+        	node.setProperty(NodeConstants.Info.MAKE_IND, Boolean.TRUE);
+        }
     }
 
 	public static Object getTrackableGroup(GroupSymbol group, QueryMetadataInterface metadata)
@@ -974,7 +1014,7 @@
     public static PlanNode createSelectNode(final Criteria crit, boolean isHaving) {
         PlanNode critNode = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
         critNode.setProperty(NodeConstants.Info.SELECT_CRITERIA, crit);
-        if (isHaving && !AggregateSymbolCollectorVisitor.getAggregates(crit, false).isEmpty()) {
+        if (isHaving && !ElementCollectorVisitor.getAggregates(crit, false).isEmpty()) {
             critNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
         }
         // Add groups to crit node
@@ -986,19 +1026,29 @@
 	/**
 	 * Attach a grouping node at top of tree.
 	 * @param plan Existing plan
+	 * @param aggs 
 	 * @param groupBy Group by clause, which may be null
 	 * @return Updated plan
+	 * @throws TeiidComponentException 
+	 * @throws QueryMetadataException 
 	 */
-	private static PlanNode attachGrouping(PlanNode plan, Query query, PlanHints hints) {
-		PlanNode groupNode = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
-
+	private PlanNode attachGrouping(PlanNode plan, Query query, Collection<AggregateSymbol> aggs) throws QueryMetadataException, TeiidComponentException {
+		//TODO: correlated agg
+		
 		GroupBy groupBy = query.getGroupBy();
-		if(groupBy != null) {
-			groupNode.setProperty(NodeConstants.Info.GROUP_COLS, groupBy.getSymbols());
-            groupNode.addGroups(GroupsUsedByElementsVisitor.getGroups(groupBy));
+		List<Expression> groupingCols = null;
+		if (groupBy != null) {
+			groupingCols = groupBy.getSymbols();
 		}
+		
+		PlanNode groupNode = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
+		
+		Map<Expression, ElementSymbol> mapping = buildGroupingNode(aggs, groupingCols, groupNode, this.context, this.idGenerator).inserseMapping();
 
 		attachLast(groupNode, plan);
+		ExpressionMappingVisitor.mapExpressions(query.getHaving(), mapping);
+		ExpressionMappingVisitor.mapExpressions(query.getSelect(), mapping);
+		ExpressionMappingVisitor.mapExpressions(query.getOrderBy(), mapping);
         
         // Mark in hints
         hints.hasAggregates = true;
@@ -1006,6 +1056,57 @@
 		return groupNode;
 	}
 
+	/**
+	 * Build a grouping node that introduces a anon group (without a inline view source node)
+	 */
+	public static SymbolMap buildGroupingNode(
+			Collection<AggregateSymbol> aggs, List<? extends Expression> groupingCols,
+			PlanNode groupNode, CommandContext cc, IDGenerator idGenerator) throws QueryMetadataException, TeiidComponentException {
+		SymbolMap map = new SymbolMap();
+		aggs = LanguageObject.Util.deepClone(aggs, AggregateSymbol.class);
+		groupingCols = LanguageObject.Util.deepClone(groupingCols, Expression.class);
+		GroupSymbol group = new GroupSymbol("anon_grp" + idGenerator.nextInt()); //$NON-NLS-1$
+		if (!cc.getGroups().add(group.getName())) {
+			group = RulePlaceAccess.recontextSymbol(group, cc.getGroups());
+		}
+		
+		TempMetadataStore tms = new TempMetadataStore();
+		
+		int i = 0;
+		
+		List<AliasSymbol> symbols = new LinkedList<AliasSymbol>();
+		List<Expression> targets = new LinkedList<Expression>();
+
+		if(groupingCols != null) {
+			groupNode.setProperty(NodeConstants.Info.GROUP_COLS, groupingCols);
+            groupNode.addGroups(GroupsUsedByElementsVisitor.getGroups(groupingCols));
+            for (Expression ex : groupingCols) {
+            	AliasSymbol as = new AliasSymbol("gcol" + i++, new ExpressionSymbol("expr", ex)); //$NON-NLS-1$ //$NON-NLS-2$
+            	targets.add(ex);
+            	symbols.add(as);
+    		}
+		}
+		
+		i = 0;
+		for (AggregateSymbol ex : aggs) {
+			AliasSymbol as = new AliasSymbol("agg" + i++, new ExpressionSymbol("expr", ex)); //$NON-NLS-1$ //$NON-NLS-2$
+        	targets.add(ex);
+        	symbols.add(as);
+		}
+		
+		group.setMetadataID(tms.addTempGroup(group.getName(), symbols, true, false));
+		Iterator<Expression> targetIter = targets.iterator();
+		for (ElementSymbol es : ResolverUtil.resolveElementsInGroup(group, new TempMetadataAdapter(new BasicQueryMetadata(), tms))) {
+			Expression target = targetIter.next();
+			es.setAggregate(target instanceof AggregateSymbol);
+			map.addMapping(es, target);
+		}
+		
+		groupNode.setProperty(NodeConstants.Info.SYMBOL_MAP, map);
+		groupNode.addGroup(group);
+		return map;
+	}
+	
     /**
 	 * Attach SORT node at top of tree.  The SORT may be pushed down to a source (or sources)
 	 * if possible by the optimizer.
@@ -1134,7 +1235,7 @@
         	}else{
             	this.context.accessedPlanningObject(matMetadataId);
         		qnode = new QueryNode(null);
-        		Query query = createMatViewQuery(matMetadataId, matTableName, Arrays.asList(new AllSymbol()), isImplicitGlobal);
+        		Query query = createMatViewQuery(matMetadataId, matTableName, Arrays.asList(new MultipleElementSymbol()), isImplicitGlobal);
         		query.setCacheHint(hint);
         		qnode.setCommand(query);
                 cacheString = "matview"; //$NON-NLS-1$


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java:3149-3217
/trunk/engine/src/main/java/org/teiid/query/optimizer/relational/RelationalPlanner.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/plantree/NodeConstants.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,7 +43,6 @@
         public static final int SET_OP = 1<<8;
         public static final int NULL = 1<<9;
         public static final int TUPLE_LIMIT = 1<<10;
-        public static final int WITH = 1<<11;
     }
 
     /**
@@ -64,7 +63,6 @@
             case NodeConstants.Types.SET_OP:        return "SetOperation"; //$NON-NLS-1$
             case NodeConstants.Types.NULL:          return "Null"; //$NON-NLS-1$
             case NodeConstants.Types.TUPLE_LIMIT:   return "TupleLimit"; //$NON-NLS-1$
-            case NodeConstants.Types.WITH:   		return "With"; //$NON-NLS-1$
             default:                                return "Unknown: " + type; //$NON-NLS-1$
         }
     }
@@ -95,10 +93,12 @@
         IS_OPTIONAL,          // Boolean
         IS_LEFT_DISTINCT, 	// Boolean
         IS_RIGHT_DISTINCT, 	// Boolean
+        IS_SEMI_DEP,		// Boolean
 
         // Project node properties
         PROJECT_COLS,       // List <SingleElementSymbol>
         INTO_GROUP,         // GroupSymbol
+        HAS_WINDOW_FUNCTIONS,		// Boolean
 
         // Select node properties
         SELECT_CRITERIA,    // Criteria
@@ -119,16 +119,17 @@
         SYMBOL_MAP,         // SymbolMap
         PARTITION_INFO,		// Map<ElementSymbol, List<Set<Constant>>> - it will only be consistent in the initial stages of planning
         VIRTUAL_COMMAND,    // Command
-        MAKE_DEP,           // ??? List of Groups ???
+        MAKE_DEP,           // Boolean
         PROCESSOR_PLAN,     // ProcessorPlan for non-relational sub plan
         NESTED_COMMAND,     // Command for nested processor plan
         TABLE_FUNCTION,     // Table Function
         CORRELATED_REFERENCES,  // SymbolMap
-        MAKE_NOT_DEP,       // Source should not be dependent
+        MAKE_NOT_DEP,       // Boolean
         INLINE_VIEW,        // If the source node represents an inline view
+        MAKE_IND,
         
         // Group node properties
-        GROUP_COLS,         // List <SingleElementSymbol>
+        GROUP_COLS,         // List <Expression>
 
         // Special constant used in converting plan to process for all nodes
         OUTPUT_COLS,        // List <SingleElementSymbol>

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CapabilitiesUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -120,12 +120,13 @@
         		return false;
         	}
             boolean supportsFunctionsInGroupBy = caps.supportsCapability(Capability.QUERY_FUNCTIONS_IN_GROUP_BY);
+            boolean supportsInlineView = caps.supportsCapability(Capability.QUERY_FROM_INLINE_VIEWS);
 
             // Also verify that if there is a function that we can support pushdown of functions in group by
             Iterator colIter = groupCols.iterator();
             while(colIter.hasNext()) {
                 Expression col = (Expression) colIter.next();
-                if(!(col instanceof ElementSymbol) && !supportsFunctionsInGroupBy) {
+                if(!(col instanceof ElementSymbol) && !supportsFunctionsInGroupBy && !supportsInlineView) {
                     // Function in GROUP BY can't be pushed
                     return false;
                 }
@@ -179,6 +180,18 @@
                 return false;
             }
             break;
+        case ARRAY_AGG:
+            if(! caps.supportsCapability(Capability.QUERY_AGGREGATES_ARRAY)) {
+                return false;
+            }
+            break;
+        case RANK:
+        case DENSE_RANK:
+        case ROW_NUMBER:
+        	if (!caps.supportsCapability(Capability.ELEMENTARY_OLAP)) {
+        		return false;
+        	}
+        	break;
         default:
         	if (aggregate.isEnhancedNumeric()) { 
         		if (!caps.supportsCapability(Capability.QUERY_AGGREGATES_ENHANCED_NUMERIC)) {
@@ -195,10 +208,12 @@
             return false;
         }
         
+        if (aggregate.getCondition() != null && !caps.supportsCapability(Capability.ADVANCED_OLAP)) {
+    		return false;
+        }
+        
         // Passed all the checks!
         return true;
-        
-
     }
 
     public static boolean supportsScalarFunction(Object modelID, Function function, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) 
@@ -209,14 +224,14 @@
         }
         
         //capabilities check is only valid for non-schema scoped functions
-        //technically the other functions are scoped to SYS, but that's 
+        //technically the other functions are scoped to SYS or their function model, but that's 
         //not formally part of their metadata yet
         Schema schema = function.getFunctionDescriptor().getMethod().getParent();
         if (schema == null) {
             // Find capabilities
             SourceCapabilities caps = getCapabilities(modelID, metadata, capFinder);
 
-            if (!caps.supportsFunction(function.getFunctionDescriptor().getName().toLowerCase())) {
+            if (!caps.supportsFunction(function.getFunctionDescriptor().getName())) {
                 return false;
             }
         } else if (!schema.getFullName().equalsIgnoreCase(metadata.getFullName(modelID))) {
@@ -225,7 +240,7 @@
         
         //special check to ensure that special conversions are not pushed down (this can be removed after we support type based function pushdown)            
         if (FunctionLibrary.isConvert(function)) {
-            Class fromType = function.getArg(0).getType();
+            Class<?> fromType = function.getArg(0).getType();
             //object or clob to anything cannot be pushed down
             if (DataTypeManager.DefaultDataClasses.OBJECT.equals(fromType) 
                             || DataTypeManager.DefaultDataClasses.CLOB.equals(fromType)

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/CriteriaCapabilityValidatorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,7 +23,6 @@
 package org.teiid.query.optimizer.relational.rules;
 
 import java.util.Arrays;
-import java.util.Collection;
 
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.core.TeiidComponentException;
@@ -62,11 +61,11 @@
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.CaseExpression;
 import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.QueryString;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.query.sql.symbol.XMLAttributes;
 import org.teiid.query.sql.symbol.XMLElement;
 import org.teiid.query.sql.symbol.XMLForest;
@@ -77,7 +76,6 @@
 import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.sql.visitor.EvaluatableVisitor;
 import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
 
 
 /**
@@ -166,6 +164,20 @@
         }
     }
     
+    @Override
+    public void visit(WindowFunction windowFunction) {
+    	if(! this.caps.supportsCapability(Capability.ELEMENTARY_OLAP)) {
+            markInvalid(windowFunction, "Window function not supported by source"); //$NON-NLS-1$
+            return;
+        } 
+    	if (!this.caps.supportsCapability(Capability.WINDOW_FUNCTION_ORDER_BY_AGGREGATES) 
+    			&& windowFunction.getWindowSpecification().getOrderBy() != null
+    			&& !windowFunction.getFunction().isAnalytical()) {
+    		markInvalid(windowFunction, "Window function order by with aggregate not supported by source"); //$NON-NLS-1$
+            return;
+    	}
+    }
+    
     public void visit(CaseExpression obj) {
         if(! this.caps.supportsCapability(Capability.QUERY_CASE)) {
             markInvalid(obj, "CaseExpression pushdown not supported by source"); //$NON-NLS-1$
@@ -258,18 +270,32 @@
     }
 
     public void visit(MatchCriteria obj) {
-        // Check if compares are allowed
-        if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE)) {
-            markInvalid(obj, "Like is not supported by source"); //$NON-NLS-1$
-            return;
-        }
+    	switch (obj.getMode()) {
+    	case LIKE:
+            if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE)) {
+                markInvalid(obj, "Like is not supported by source"); //$NON-NLS-1$
+                return;
+            }
+            break;
+    	case SIMILAR:
+    		if(! this.caps.supportsCapability(Capability.CRITERIA_SIMILAR)) {
+                markInvalid(obj, "Similar to is not supported by source"); //$NON-NLS-1$
+                return;
+            }
+    		break;
+    	case REGEX:
+    		if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE_REGEX)) {
+                markInvalid(obj, "Like_regex is not supported by source"); //$NON-NLS-1$
+                return;
+            }
+    		break;
+    	}
         
         // Check ESCAPE char if necessary
-        if(obj.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR) {
-            if(! this.caps.supportsCapability(Capability.CRITERIA_LIKE_ESCAPE)) {
-                markInvalid(obj, "Like escape is not supported by source"); //$NON-NLS-1$
-                return;
-            }                
+        if(obj.getEscapeChar() != MatchCriteria.NULL_ESCAPE_CHAR 
+        		&& ! this.caps.supportsCapability(Capability.CRITERIA_LIKE_ESCAPE)) {
+            markInvalid(obj, "Like escape is not supported by source"); //$NON-NLS-1$
+            return;
         }
         
         //check NOT
@@ -464,17 +490,17 @@
      * @return
      * @throws TeiidComponentException
      */
-    public static Object validateSubqueryPushdown(SubqueryContainer subqueryContainer, Object critNodeModelID, 
+    public static Object validateSubqueryPushdown(SubqueryContainer<?> subqueryContainer, Object critNodeModelID, 
     		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord analysisRecord) throws TeiidComponentException {
     	ProcessorPlan plan = subqueryContainer.getCommand().getProcessorPlan();
     	if (plan != null) {
-    		QueryCommand queryCommand = getQueryCommand(plan);
+    		AccessNode aNode = getAccessNode(plan);
     		
-    		if (queryCommand == null) {
+    		if (aNode == null) {
     			return null;
     		}
     		
-    		critNodeModelID = validateCommandPushdown(critNodeModelID, metadata, capFinder,	queryCommand);  
+    		critNodeModelID = validateCommandPushdown(critNodeModelID, metadata, capFinder,	aNode);  
     	}
     	if (critNodeModelID == null) {
     		return null;
@@ -502,20 +528,13 @@
 
 	public static Object validateCommandPushdown(Object critNodeModelID,
 			QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
-			QueryCommand queryCommand) throws TeiidComponentException {
+			AccessNode aNode) throws TeiidComponentException {
 		// Check that query in access node is for the same model as current node
 		try {                
-		    Collection<GroupSymbol> subQueryGroups = GroupCollectorVisitor.getGroupsIgnoreInlineViews(queryCommand, false);
-		    if(subQueryGroups.size() == 0) {
-		        // No FROM?
-		        return null;
-		    }
-		    GroupSymbol subQueryGroup = subQueryGroups.iterator().next();
-
-		    Object modelID = subQueryGroup.getModelMetadataId();
-		    if (modelID == null) {
-		    	modelID = metadata.getModelID(subQueryGroup.getMetadataID());
-		    }
+			if (!(aNode.getCommand() instanceof QueryCommand)) {
+				return null;
+			}
+		    Object modelID = aNode.getModelId();
 		    if (critNodeModelID == null) {
 		    	critNodeModelID = modelID;
 		    } else if(!CapabilitiesUtil.isSameConnector(critNodeModelID, modelID, metadata, capFinder)) {
@@ -527,7 +546,7 @@
 		return critNodeModelID;
 	}
 
-	public static QueryCommand getQueryCommand(ProcessorPlan plan) {
+	public static AccessNode getAccessNode(ProcessorPlan plan) {
 		if(!(plan instanceof RelationalPlan)) {
 		    return null;
 		}
@@ -545,17 +564,27 @@
 			accessNode = ln.getChildren()[0];
 		}
 		
-		if (! (accessNode instanceof AccessNode) || accessNode.getChildren()[0] != null) {
+		if (! (accessNode instanceof AccessNode)) {
 			return null;
 		}
-		
-		// Check that command in access node is a query
-		Command command = ((AccessNode)accessNode).getCommand();
-		if(command == null || !(command instanceof QueryCommand) || ((command instanceof Query) && ((Query)command).getIsXML())) {
+		return (AccessNode)accessNode;
+	}
+	
+	public static QueryCommand getQueryCommand(AccessNode aNode) {
+		if (aNode == null) {
+			return null;
+		}
+		Command command = aNode.getCommand();
+		if(!(command instanceof QueryCommand)) {
 		    return null;
 		}
 		
 		QueryCommand queryCommand = (QueryCommand)command;
+		if (aNode.getProjection() != null && aNode.getProjection().length > 0) {
+			Query newCommand = (Query)queryCommand.clone();
+			newCommand.getSelect().setSymbols(aNode.getOriginalSelect());
+			return newCommand;
+		}
 		return queryCommand;
 	}
         

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/FrameUtil.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/FrameUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/FrameUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -37,7 +37,6 @@
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.util.Assertion;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.metadata.QueryMetadataInterface;
@@ -45,21 +44,26 @@
 import org.teiid.query.optimizer.relational.plantree.NodeEditor;
 import org.teiid.query.optimizer.relational.plantree.NodeFactory;
 import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants.Info;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.resolver.util.AccessPattern;
 import org.teiid.query.resolver.util.ResolverUtil;
 import org.teiid.query.rewriter.QueryRewriter;
+import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.CompoundCriteria;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.lang.GroupBy;
 import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
 import org.teiid.query.sql.lang.QueryCommand;
 import org.teiid.query.sql.lang.Select;
 import org.teiid.query.sql.lang.StoredProcedure;
+import org.teiid.query.sql.symbol.AliasSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.util.SymbolMap;
@@ -124,15 +128,15 @@
 	}
     
     static boolean canConvertAccessPatterns(PlanNode sourceNode) {
-        List accessPatterns = (List)sourceNode.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+        List<AccessPattern> accessPatterns = (List)sourceNode.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
         if (accessPatterns == null) {
             return true;
         }
         SymbolMap symbolMap = (SymbolMap)sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
-        for (Iterator i = accessPatterns.iterator(); i.hasNext();) {
-            AccessPattern ap = (AccessPattern)i.next();
-            for (Iterator elems = ap.getUnsatisfied().iterator(); elems.hasNext();) {
-                ElementSymbol symbol = (ElementSymbol)elems.next();
+        for (Iterator<AccessPattern> i = accessPatterns.iterator(); i.hasNext();) {
+            AccessPattern ap = i.next();
+            for (Iterator<ElementSymbol> elems = ap.getUnsatisfied().iterator(); elems.hasNext();) {
+                ElementSymbol symbol = elems.next();
                 Expression mapped = convertExpression(symbol, symbolMap.asMap());
                 if (ElementCollectorVisitor.getElements(mapped, true).isEmpty()) {
                     return false;
@@ -153,15 +157,15 @@
         if (accessPatterns != null) {
         	for (AccessPattern ap : accessPatterns) {
                 Set<ElementSymbol> newElements = new HashSet<ElementSymbol>();
-                for (Iterator elems = ap.getUnsatisfied().iterator(); elems.hasNext();) {
-                    ElementSymbol symbol = (ElementSymbol)elems.next();
+                for (Iterator<ElementSymbol> elems = ap.getUnsatisfied().iterator(); elems.hasNext();) {
+                    ElementSymbol symbol = elems.next();
                     Expression mapped = convertExpression(symbol, symbolMap);
                     newElements.addAll(ElementCollectorVisitor.getElements(mapped, true));
                 }
                 ap.setUnsatisfied(newElements);
                 Set<ElementSymbol> newHistory = new HashSet<ElementSymbol>();
-                for (Iterator elems = ap.getCurrentElements().iterator(); elems.hasNext();) {
-                    ElementSymbol symbol = (ElementSymbol)elems.next();
+                for (Iterator<ElementSymbol> elems = ap.getCurrentElements().iterator(); elems.hasNext();) {
+                    ElementSymbol symbol = elems.next();
                     Expression mapped = convertExpression(symbol, symbolMap);
                     newHistory.addAll(ElementCollectorVisitor.getElements(mapped, true));
                 }
@@ -178,6 +182,10 @@
     // multiple new groups.  
     static void convertNode(PlanNode node, GroupSymbol oldGroup, Set<GroupSymbol> newGroups, Map symbolMap, QueryMetadataInterface metadata, boolean rewrite)
         throws QueryPlannerException {
+    	
+    	if (node.getType() == NodeConstants.Types.GROUP) {
+    		correctSymbolMap(symbolMap, node);
+    	}
 
         // Convert expressions from correlated subquery references;
         List<SymbolMap> refMaps = node.getAllReferences();
@@ -228,6 +236,11 @@
             List<SingleElementSymbol> projectedSymbols = (List<SingleElementSymbol>)node.getProperty(NodeConstants.Info.PROJECT_COLS);
             Select select = new Select(projectedSymbols);
             ExpressionMappingVisitor.mapExpressions(select, symbolMap);
+            if (rewrite) {
+            	for (LanguageObject expr : select.getSymbols()) {
+					rewriteSingleElementSymbol(metadata, (SingleElementSymbol) expr);
+				}
+            }
             node.setProperty(NodeConstants.Info.PROJECT_COLS, select.getSymbols());
             if (!singleMapping) {
                 GroupsUsedByElementsVisitor.getGroups(select, groups);
@@ -252,11 +265,16 @@
         } else if(type == NodeConstants.Types.SORT) { 
         	OrderBy orderBy = (OrderBy)node.getProperty(NodeConstants.Info.SORT_ORDER);
             ExpressionMappingVisitor.mapExpressions(orderBy, symbolMap);
+            if (rewrite) {
+            	for (OrderByItem item : orderBy.getOrderByItems()) {
+            		rewriteSingleElementSymbol(metadata, item.getSymbol());
+            	}
+            }
             if (!singleMapping) {
                 GroupsUsedByElementsVisitor.getGroups(orderBy, groups);
             }
         } else if(type == NodeConstants.Types.GROUP) {  
-        	List<SingleElementSymbol> groupCols = (List<SingleElementSymbol>)node.getProperty(NodeConstants.Info.GROUP_COLS);
+        	List<Expression> groupCols = (List<Expression>)node.getProperty(NodeConstants.Info.GROUP_COLS);
             if (groupCols != null) {
                 GroupBy groupBy= new GroupBy(groupCols);
                 ExpressionMappingVisitor.mapExpressions(groupBy, symbolMap);
@@ -265,10 +283,36 @@
                     GroupsUsedByElementsVisitor.getGroups(groupBy, groups);
                 }
             }               
+            if (!singleMapping) {
+                //add back the anon group
+                SymbolMap property = (SymbolMap)node.getProperty(Info.SYMBOL_MAP);
+                if (!property.asMap().isEmpty()) {
+                	groups.add(property.asMap().keySet().iterator().next().getGroupSymbol());
+                }
+            }
         } else if (type == NodeConstants.Types.SOURCE || type == NodeConstants.Types.ACCESS) {
             convertAccessPatterns(symbolMap, node);
         }
     }
+
+	private static void rewriteSingleElementSymbol(
+			QueryMetadataInterface metadata, SingleElementSymbol ses) throws QueryPlannerException {
+		try {
+			if (ses instanceof AliasSymbol) {
+				ses = ((AliasSymbol)ses).getSymbol();
+			} 
+			if (ses instanceof ExpressionSymbol) {
+				ExpressionSymbol es = (ExpressionSymbol)ses;
+				if (es.getExpression() != null) {
+					es.setExpression(QueryRewriter.rewriteExpression(es.getExpression(), null, null, metadata));
+				}
+			}
+		} catch(TeiidProcessingException e) {
+		    throw new QueryPlannerException(e, QueryPlugin.Util.getString("ERR.015.004.0023", ses)); //$NON-NLS-1$
+		} catch (TeiidComponentException e) {
+			throw new QueryPlannerException(e, QueryPlugin.Util.getString("ERR.015.004.0023", ses)); //$NON-NLS-1$
+		}
+	}
     
     private static Expression convertExpression(Expression expression, Map symbolMap) {
         
@@ -281,7 +325,9 @@
             if (mappedSymbol != null) {
                 return mappedSymbol;
             }
-            return expression;
+            if (expression instanceof ElementSymbol) {
+            	return expression;
+            }
         }
                 
         ExpressionMappingVisitor.mapExpressions(expression, symbolMap);
@@ -303,7 +349,7 @@
         } catch(TeiidProcessingException e) {
             throw new QueryPlannerException(e, QueryPlugin.Util.getString("ERR.015.004.0023", criteria)); //$NON-NLS-1$
         } catch (TeiidComponentException e) {
-        	throw new TeiidRuntimeException(e);
+        	throw new QueryPlannerException(e, QueryPlugin.Util.getString("ERR.015.004.0023", criteria)); //$NON-NLS-1$
         }
     }
 
@@ -377,8 +423,7 @@
     private static PlanNode findOriginatingNode(PlanNode root, Set<GroupSymbol> groups, boolean joinSource) {
         boolean containsGroups = false;
         
-    	if(root.getType() == NodeConstants.Types.NULL || root.getType() == NodeConstants.Types.SOURCE 
-                        || root.getType() == NodeConstants.Types.JOIN || root.getType() == NodeConstants.Types.SET_OP ||
+    	if((root.getType() & (NodeConstants.Types.NULL | NodeConstants.Types.SOURCE | NodeConstants.Types.JOIN | NodeConstants.Types.SET_OP | NodeConstants.Types.GROUP)) == root.getType() ||
                         (joinSource && root.getType() == NodeConstants.Types.ACCESS)) {
     	    
             //if there are no groups then the first possible match is the one we want

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/NewCalculateCostUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,6 +43,7 @@
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.Like.MatchMode;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.query.QueryPlugin;
@@ -74,7 +75,6 @@
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
 import org.teiid.query.sql.visitor.EvaluatableVisitor;
 import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
@@ -440,7 +440,7 @@
     			if (stats == null) {
         			if (node.getType() == NodeConstants.Types.PROJECT) {
 	        			Collection<SingleElementSymbol> elems = new HashSet<SingleElementSymbol>();
-	        			AggregateSymbolCollectorVisitor.getAggregates(expr, elems, elems);
+	        			ElementCollectorVisitor.getElements(expr, elems);
 	        			newStats[Stat.NDV.ordinal()] = getStat(Stat.NDV, elems, node, childCardinality, metadata);
 		        		newStats[Stat.NNV.ordinal()] = getStat(Stat.NNV, elems, node, childCardinality, metadata);
         			} else {
@@ -578,9 +578,8 @@
 		if (node.getType() == NodeConstants.Types.PROJECT) {
 			return (List<? extends Expression>) node.getProperty(NodeConstants.Info.PROJECT_COLS);
 		} else if (node.getType() == NodeConstants.Types.GROUP) {
-			LinkedList<Expression> result = new LinkedList<Expression>(RulePushAggregates.collectAggregates(node));
-			result.addAll((Collection<? extends Expression>) node.getProperty(Info.GROUP_COLS));
-			return result;
+			SymbolMap map = (SymbolMap)node.getProperty(Info.SYMBOL_MAP);
+			return map.getKeys();
 		} 
 		LinkedList<ElementSymbol> elements = new LinkedList<ElementSymbol>();
 		for (GroupSymbol group : node.getGroups()) {
@@ -919,7 +918,8 @@
         Expression matchExpression = criteria.getRightExpression();
         if(matchExpression instanceof Constant && ((Constant)matchExpression).getType().equals(DataTypeManager.DefaultDataClasses.STRING)) {
             String compareValue = (String) ((Constant)matchExpression).getValue();
-            if(compareValue != null && compareValue.indexOf('%') < 0) {
+            if(criteria.getMode() != MatchMode.REGEX && criteria.getEscapeChar() == MatchCriteria.NULL_ESCAPE_CHAR 
+            		&& compareValue != null && compareValue.indexOf('%') < 0) {
             	return (childCost / 2) * (1 / 3f  + 1 / ndv); //without knowing length constraints we'll make an average guess
             }
         } else if (EvaluatableVisitor.willBecomeConstant(criteria.getLeftExpression())) {
@@ -1014,7 +1014,7 @@
         return cost;
     }
     
-    static boolean usesKey(PlanNode planNode, Collection<? extends SingleElementSymbol> allElements, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+    static boolean usesKey(PlanNode planNode, Collection<? extends Expression> allElements, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
     	//TODO: key preserved joins should be marked
     	return isSingleTable(planNode)
     	&& usesKey(allElements, metadata);
@@ -1035,17 +1035,17 @@
      * we are in the plan.
      * if a key column is used after a non 1-1 join or a union all, then it may be non-unique.
      */
-    public static boolean usesKey(Collection<? extends SingleElementSymbol> allElements, QueryMetadataInterface metadata)
+    public static boolean usesKey(Collection<? extends Expression> allElements, QueryMetadataInterface metadata)
         throws QueryMetadataException, TeiidComponentException {
     	return usesKey(allElements, null, metadata, true);
     }
 
-    public static boolean usesKey(Collection<? extends SingleElementSymbol> allElements, Set<GroupSymbol> groups, QueryMetadataInterface metadata, boolean unique)
+    public static boolean usesKey(Collection<? extends Expression> allElements, Set<GroupSymbol> groups, QueryMetadataInterface metadata, boolean unique)
     throws QueryMetadataException, TeiidComponentException {
 		return getKeyUsed(allElements, groups, metadata, unique) != null;
     }
     
-    public static Object getKeyUsed(Collection<? extends SingleElementSymbol> allElements, Set<GroupSymbol> groups, QueryMetadataInterface metadata, Boolean unique)
+    public static Object getKeyUsed(Collection<? extends Expression> allElements, Set<GroupSymbol> groups, QueryMetadataInterface metadata, Boolean unique)
     throws QueryMetadataException, TeiidComponentException {
         
         if(allElements == null || allElements.size() == 0) { 
@@ -1054,7 +1054,7 @@
      
         // Sort elements into groups
         Map<GroupSymbol, List<Object>> groupMap = new HashMap<GroupSymbol, List<Object>>();
-        for (SingleElementSymbol ses : allElements) {
+        for (Expression ses : allElements) {
         	Expression ex = SymbolMap.getExpression(ses); 
         	if (!(ex instanceof ElementSymbol)) {
         		continue; //TODO: function based indexes are possible, but we don't have the metadata
@@ -1337,7 +1337,7 @@
 
 	static float getNDVEstimate(PlanNode indNode,
 			QueryMetadataInterface metadata, float cardinality,
-			Collection<? extends SingleElementSymbol> elems, boolean useCardinalityIfUnknown) throws QueryMetadataException,
+			Collection<? extends Expression> elems, boolean useCardinalityIfUnknown) throws QueryMetadataException,
 			TeiidComponentException {
 		if (elems == null || elems.isEmpty()) {
 			return cardinality;

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleAssignOutputElements.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleAssignOutputElements.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleAssignOutputElements.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,6 +29,7 @@
 import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 import org.teiid.api.exception.query.QueryMetadataException;
@@ -42,7 +43,9 @@
 import org.teiid.query.optimizer.relational.RuleStack;
 import org.teiid.query.optimizer.relational.plantree.NodeConstants;
 import org.teiid.query.optimizer.relational.plantree.NodeEditor;
+import org.teiid.query.optimizer.relational.plantree.NodeFactory;
 import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants.Info;
 import org.teiid.query.processor.relational.RelationalNode;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Criteria;
@@ -51,13 +54,16 @@
 import org.teiid.query.sql.lang.StoredProcedure;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
+import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
 import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
 import org.teiid.query.util.CommandContext;
 
@@ -207,9 +213,44 @@
 		            	root.addGroups(GroupsUsedByElementsVisitor.getGroups(projectCols));
 		            	root.addGroups(GroupsUsedByElementsVisitor.getGroups(root.getCorrelatedReferenceElements()));
 	            	}
+	            	if (root.hasBooleanProperty(Info.HAS_WINDOW_FUNCTIONS)) {
+	            		Set<WindowFunction> windowFunctions = getWindowFunctions(projectCols);
+	            		if (windowFunctions.isEmpty()) {
+	            			root.setProperty(Info.HAS_WINDOW_FUNCTIONS, false);
+	            		}
+	            	}
 		    	}
 	            
 	            List<SingleElementSymbol> requiredInput = collectRequiredInputSymbols(root);
+	            //targeted optimization for unnecessary aggregation
+	            if (root.getType() == NodeConstants.Types.GROUP && root.hasBooleanProperty(Info.IS_OPTIONAL) && NodeEditor.findParent(root, NodeConstants.Types.ACCESS) == null) {
+	            	PlanNode old = root;
+	            	PlanNode next = root.getFirstChild();
+	            	NodeEditor.removeChildNode(root.getParent(), root);
+	            	
+            		SymbolMap symbolMap = (SymbolMap) old.getProperty(NodeConstants.Info.SYMBOL_MAP);
+            		if (!symbolMap.asMap().isEmpty()) {
+            			FrameUtil.convertFrame(next.getParent(), symbolMap.asMap().keySet().iterator().next().getGroupSymbol(), null, symbolMap.asMap(), metadata);
+            		}
+    				PlanNode parent = next.getParent();
+    				while (parent.getParent() != null && parent.getParent().getType() != NodeConstants.Types.SOURCE) {
+    					parent = parent.getParent();
+    				}
+    				if (!old.hasCollectionProperty(Info.GROUP_COLS)) {
+    					//just lob off everything under the projection
+    					PlanNode project = NodeEditor.findNodePreOrder(parent, NodeConstants.Types.PROJECT);
+    					project.removeAllChildren();
+    				} else {
+    					PlanNode limit = NodeFactory.getNewNode(NodeConstants.Types.TUPLE_LIMIT);
+        				limit.setProperty(Info.MAX_TUPLE_LIMIT, new Constant(1));
+	    				if (!rules.contains(RuleConstants.PUSH_LIMIT)) {
+	    					rules.push(RuleConstants.PUSH_LIMIT);
+	    				}
+						parent.getFirstChild().addAsParent(limit);
+    				}
+	            	execute(parent, metadata, capFinder, rules, analysisRecord, context);
+	            	return;
+            	}
 	            
 	            // Call children recursively
 	            if(root.getChildCount() == 1) {
@@ -228,6 +269,15 @@
 		}
 	}
 
+	public static Set<WindowFunction> getWindowFunctions(
+			List<SingleElementSymbol> projectCols) {
+		LinkedHashSet<WindowFunction> windowFunctions = new LinkedHashSet<WindowFunction>();
+		for (SingleElementSymbol singleElementSymbol : projectCols) {
+			AggregateSymbolCollectorVisitor.getAggregates(singleElementSymbol, null, null, null, windowFunctions, null);
+		}
+		return windowFunctions;
+	}
+
     private List<SingleElementSymbol> filterElements(Collection<? extends SingleElementSymbol> requiredInput, Set<GroupSymbol> filterGroups) {
         List<SingleElementSymbol> filteredElements = new ArrayList<SingleElementSymbol>();
         for (SingleElementSymbol element : requiredInput) {
@@ -429,8 +479,6 @@
      * are any symbols that are required in the processing of this node,
      * for instance to create a new element symbol or sort on it, etc.
      * @param node Node to collect for
-     * @param requiredSymbols Collection<SingleElementSymbol> Place to collect required symbols
-     * @param createdSymbols Set<SingleElementSymbol> Place to collect any symbols created by this node
      */
 	private List<SingleElementSymbol> collectRequiredInputSymbols(PlanNode node) {
 
@@ -450,68 +498,75 @@
                         ss = ((AliasSymbol)ss).getSymbol();
                     }
                     
-                    if (ss instanceof ExpressionSymbol && !(ss instanceof AggregateSymbol)) {
-                        ExpressionSymbol exprSymbol = (ExpressionSymbol)ss;
-                        
-                        if (!exprSymbol.isDerivedExpression()) {
-                            createdSymbols.add(ss);
-                        } 
+                    if (ss instanceof WindowFunction || (ss instanceof ExpressionSymbol && !(ss instanceof AggregateSymbol))) {
+                        createdSymbols.add(ss);
                     }
-                    AggregateSymbolCollectorVisitor.getAggregates(ss, requiredSymbols, requiredSymbols);                        
+                    ElementCollectorVisitor.getElements(ss, requiredSymbols);
                 }
 				break;
             }
 			case NodeConstants.Types.SELECT:
 				Criteria selectCriteria = (Criteria) node.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-                AggregateSymbolCollectorVisitor.getAggregates(selectCriteria, requiredSymbols, requiredSymbols);
+				ElementCollectorVisitor.getElements(selectCriteria, requiredSymbols);
 				break;
 			case NodeConstants.Types.JOIN:
 				List<Criteria> crits = (List) node.getProperty(NodeConstants.Info.JOIN_CRITERIA);
 				if(crits != null) {
 					for (Criteria joinCriteria : crits) {
-						AggregateSymbolCollectorVisitor.getAggregates(joinCriteria, requiredSymbols, requiredSymbols);
+						ElementCollectorVisitor.getElements(joinCriteria, requiredSymbols);
 					}
 				}
 				break;
 			case NodeConstants.Types.GROUP:
-				List<SingleElementSymbol> groupCols = (List<SingleElementSymbol>) node.getProperty(NodeConstants.Info.GROUP_COLS);
+				List<Expression> groupCols = (List<Expression>) node.getProperty(NodeConstants.Info.GROUP_COLS);
 				if(groupCols != null) {
-				    for (SingleElementSymbol expression : groupCols) {
-                        if(expression instanceof ElementSymbol || expression instanceof AggregateSymbol) {
-                            requiredSymbols.add(expression);
-                        } else {    
-                            ExpressionSymbol exprSymbol = (ExpressionSymbol) expression;
-                            Expression expr = exprSymbol.getExpression();
-                            AggregateSymbolCollectorVisitor.getAggregates(expr, requiredSymbols, requiredSymbols);
-                            createdSymbols.add(exprSymbol);
-                        }
+				    for (Expression expression : groupCols) {
+				    	ElementCollectorVisitor.getElements(expression, requiredSymbols);
                     }
 				}
-
+				SymbolMap symbolMap = (SymbolMap) node.getProperty(NodeConstants.Info.SYMBOL_MAP);
+				Set<ElementSymbol> usedAggregates = new HashSet<ElementSymbol>();
+				
 				// Take credit for creating any aggregates that are needed above
 				for (SingleElementSymbol outputSymbol : outputCols) {
-					if(outputSymbol instanceof AggregateSymbol) {
-					    AggregateSymbol agg = (AggregateSymbol)outputSymbol;
-					    createdSymbols.add(outputSymbol);
-					    
+					if (!(outputSymbol instanceof ElementSymbol)) {
+						continue;
+					}
+					createdSymbols.add(outputSymbol);
+					Expression ex = symbolMap.getMappedExpression((ElementSymbol) outputSymbol);
+					if(ex instanceof AggregateSymbol) {
+					    AggregateSymbol agg = (AggregateSymbol)ex;
 	                    Expression aggExpr = agg.getExpression();
 	                    if(aggExpr != null) {
-	                        AggregateSymbolCollectorVisitor.getAggregates(aggExpr, requiredSymbols, requiredSymbols);
+	                    	ElementCollectorVisitor.getElements(aggExpr, requiredSymbols);
 	                    }
 	                    OrderBy orderBy = agg.getOrderBy();
 	                    if(orderBy != null) {
-	                        AggregateSymbolCollectorVisitor.getAggregates(orderBy, requiredSymbols, requiredSymbols);
+	                    	ElementCollectorVisitor.getElements(orderBy, requiredSymbols);
 	                    }
+	                    Expression condition = agg.getCondition();
+	                    if(condition != null) {
+	                    	ElementCollectorVisitor.getElements(condition, requiredSymbols);
+	                    }
+	                    usedAggregates.add((ElementSymbol) outputSymbol);
 					}
 				}
-
+				//update the aggs in the symbolmap
+				for (Map.Entry<ElementSymbol, Expression> entry : new ArrayList<Map.Entry<ElementSymbol, Expression>>(symbolMap.asMap().entrySet())) {
+					if (entry.getValue() instanceof AggregateSymbol && !usedAggregates.contains(entry.getKey())) {
+						symbolMap.asUpdatableMap().remove(entry.getKey());
+					}
+				}
+				if (requiredSymbols.isEmpty() && usedAggregates.isEmpty()) {
+					node.setProperty(Info.IS_OPTIONAL, true);
+				}
 				break;
 		}
 
         // Gather elements from correlated subquery references;
 		for (SymbolMap refs : node.getAllReferences()) {
         	for (Expression expr : refs.asMap().values()) {
-                AggregateSymbolCollectorVisitor.getAggregates(expr, requiredSymbols, requiredSymbols);
+        		ElementCollectorVisitor.getElements(expr, requiredSymbols);
             }
         }
         

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseDependent.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -253,6 +253,16 @@
         		analysisRecord.println("Making access node dependent due to hint: "+ sourceNode2.nodeToString());                     //$NON-NLS-1$
         	}
             return rootNode2;
+        } else if (sourceNode1.hasBooleanProperty(NodeConstants.Info.MAKE_IND) && sourceNode2 != null) {
+        	if (analysisRecord.recordDebug()) {
+        		analysisRecord.println("Making access node dependent due to hint: "+ sourceNode2.nodeToString());                     //$NON-NLS-1$
+        	}
+        	return rootNode2;
+        } else if (sourceNode2 != null && sourceNode2.hasBooleanProperty(NodeConstants.Info.MAKE_IND)) {
+        	if (analysisRecord.recordDebug()) {
+        		analysisRecord.println("Making access node dependent due to hint: "+ sourceNode1.nodeToString());                     //$NON-NLS-1$
+        	}
+        	return rootNode1;
         }
         
         return null;

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseJoinStrategy.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseJoinStrategy.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleChooseJoinStrategy.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,11 +24,9 @@
 
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
 
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.core.TeiidComponentException;
@@ -71,7 +69,6 @@
      * Determines whether this node should be converted to a merge join node
      * @param joinNode The join node
      * @param metadata The metadata
-     * @return True if merge is possible
      */
     static void chooseJoinStrategy(PlanNode joinNode, QueryMetadataInterface metadata) {
         // Check that join is an inner join
@@ -170,23 +167,14 @@
         }
 	}
     
-    private static AtomicInteger EXPRESSION_INDEX = new AtomicInteger(0);
-    
     public static List<SingleElementSymbol> createExpressionSymbols(List<? extends Expression> expressions) {
-        HashMap<Expression, ExpressionSymbol> uniqueExpressions = new HashMap<Expression, ExpressionSymbol>();
         List<SingleElementSymbol> result = new ArrayList<SingleElementSymbol>();
         for (Expression expression : expressions) {
             if (expression instanceof SingleElementSymbol) {
                 result.add((SingleElementSymbol)expression);
                 continue;
             } 
-            ExpressionSymbol expressionSymbol = uniqueExpressions.get(expression);
-            if (expressionSymbol == null) {
-                expressionSymbol = new ExpressionSymbol("$" + EXPRESSION_INDEX.getAndIncrement(), expression); //$NON-NLS-1$
-                expressionSymbol.setDerivedExpression(true);
-                uniqueExpressions.put(expression, expressionSymbol);
-            }
-            result.add(expressionSymbol);
+            result.add(new ExpressionSymbol("expr", expression)); //$NON-NLS-1$
         }
         return result;
     }

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleCollapseSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,13 +24,19 @@
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
 import java.util.LinkedHashSet;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Set;
 
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.metadata.QueryMetadataInterface;
@@ -45,6 +51,7 @@
 import org.teiid.query.optimizer.relational.plantree.PlanNode;
 import org.teiid.query.optimizer.relational.plantree.NodeConstants.Info;
 import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.processor.relational.AccessNode;
 import org.teiid.query.processor.relational.RelationalPlan;
 import org.teiid.query.resolver.util.ResolverUtil;
 import org.teiid.query.rewriter.QueryRewriter;
@@ -70,6 +77,7 @@
 import org.teiid.query.sql.lang.UnaryFromClause;
 import org.teiid.query.sql.lang.SetQuery.Operation;
 import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
+import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
@@ -78,6 +86,7 @@
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
 import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
 import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
 import org.teiid.query.util.CommandContext;
@@ -171,9 +180,11 @@
 		 */
 		if (queryCommand instanceof SetQuery) {
 			((SetQuery)queryCommand).setAll(false);
-		} else if (!NewCalculateCostUtil.usesKey(accessNode, queryCommand.getProjectedSymbols(), metadata) && CapabilitiesUtil.supports(Capability.QUERY_SELECT_DISTINCT, RuleRaiseAccess.getModelIDFromAccess(accessNode, metadata), metadata, capFinder)) {
+		} else if (CapabilitiesUtil.supports(Capability.QUERY_SELECT_DISTINCT, RuleRaiseAccess.getModelIDFromAccess(accessNode, metadata), metadata, capFinder)) {
 			Query query = (Query)queryCommand;
-			if (!QueryRewriter.isDistinctWithGroupBy(query)) {
+			HashSet<GroupSymbol> keyPreservingGroups = new HashSet<GroupSymbol>();
+			ResolverUtil.findKeyPreserved(query, keyPreservingGroups, metadata);
+			if (!QueryRewriter.isDistinctWithGroupBy(query) && !NewCalculateCostUtil.usesKey(query.getSelect().getProjectedSymbols(), keyPreservingGroups, metadata, true)) {
 				((Query)queryCommand).getSelect().setDistinct(true);
 			}
 		}
@@ -237,11 +248,12 @@
 		if (query.getCriteria() instanceof CompoundCriteria) {
             query.setCriteria(QueryRewriter.optimizeCriteria((CompoundCriteria)query.getCriteria(), metadata));
         }
-		if (!CapabilitiesUtil.useAnsiJoin(RuleRaiseAccess.getModelIDFromAccess(accessRoot, metadata), metadata, capFinder)) {
+		Object modelID = RuleRaiseAccess.getModelIDFromAccess(accessRoot, metadata);
+		if (!CapabilitiesUtil.useAnsiJoin(modelID, metadata, capFinder)) {
 			simplifyFromClause(query);
         }
 		if (columns.isEmpty()) {
-        	if (CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, RuleRaiseAccess.getModelIDFromAccess(accessRoot, metadata), metadata, capFinder)) {
+        	if (CapabilitiesUtil.supports(Capability.QUERY_SELECT_EXPRESSION, modelID, metadata, capFinder)) {
         		select.addSymbol(new ExpressionSymbol("dummy", new Constant(1))); //$NON-NLS-1$
         	} else {
         		//TODO: need to ensure the type is consistent  
@@ -249,6 +261,20 @@
         		select.addSymbol(selectOutputElement(query.getFrom().getGroups(), metadata));
         	}
         }
+		PlanNode groupNode = NodeEditor.findNodePreOrder(node, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE);
+		if (groupNode != null) {
+	        SymbolMap symbolMap = (SymbolMap) groupNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
+	      
+	        //map back to expression form
+	        ExpressionMappingVisitor.mapExpressions(query.getOrderBy(), symbolMap.asMap());
+	        ExpressionMappingVisitor.mapExpressions(query.getSelect(), symbolMap.asMap()); 
+	        ExpressionMappingVisitor.mapExpressions(query.getHaving(), symbolMap.asMap()); 
+	
+			if (!CapabilitiesUtil.supports(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, modelID, metadata, capFinder)) {
+				//if group by expressions are not support, add an inline view to compensate
+				query = RuleCollapseSource.rewriteGroupByExpressionsAsView(query, metadata);
+			}
+		}
 		return query;
 	}		
 	
@@ -269,7 +295,7 @@
             
             for (ElementSymbol element : elements) {
                 if(metadata.elementSupports(element.getMetadataID(), SupportConstants.Element.SELECT)) {
-                    element = (ElementSymbol)element.clone();
+                    element = element.clone();
                     element.setGroupSymbol(group);
                     return element;
                 }
@@ -319,10 +345,10 @@
                 
                 // Get last two clauses added to the FROM and combine them into a JoinPredicate
                 From from = query.getFrom();
-                List clauses = from.getClauses();
+                List<FromClause> clauses = from.getClauses();
                 int lastClause = clauses.size()-1;
-                FromClause clause1 = (FromClause) clauses.get(lastClause-1);
-                FromClause clause2 = (FromClause) clauses.get(lastClause);
+                FromClause clause1 = clauses.get(lastClause-1);
+                FromClause clause2 = clauses.get(lastClause);
                  
                 //correct the criteria or the join type if necessary
                 if (joinType != JoinType.JOIN_CROSS && crits.isEmpty()) {
@@ -405,7 +431,8 @@
 
 	public static void prepareSubquery(SubqueryContainer container) {
 		RelationalPlan subqueryPlan = (RelationalPlan)container.getCommand().getProcessorPlan();
-		QueryCommand command = CriteriaCapabilityValidatorVisitor.getQueryCommand(subqueryPlan);
+		AccessNode aNode = CriteriaCapabilityValidatorVisitor.getAccessNode(subqueryPlan);
+		QueryCommand command = CriteriaCapabilityValidatorVisitor.getQueryCommand(aNode);
 		if (command == null) {
 			return;
 		}
@@ -487,13 +514,13 @@
     */
     private void simplifyFromClause(Query query) {
         From from = query.getFrom();
-        List clauses = from.getClauses();
-        FromClause rootClause = (FromClause) clauses.get(0);
+        List<FromClause> clauses = from.getClauses();
+        FromClause rootClause = clauses.get(0);
        
         // If all joins are inner joins, move criteria to WHERE and make 
         // FROM a list of groups instead of a tree of JoinPredicates
         if(! hasOuterJoins(rootClause)) {
-            from.setClauses(new ArrayList());
+            from.setClauses(new ArrayList<FromClause>());
             shredJoinTree(rootClause, query);
         } // else leave as is
     }    
@@ -549,4 +576,75 @@
    		return "CollapseSource"; //$NON-NLS-1$
    	}
 
+	public static Query rewriteGroupByExpressionsAsView(Query query, QueryMetadataInterface metadata) {
+		if (query.getGroupBy() == null) {
+			return query;
+		}
+	    // we check for group by expressions here to create an ANSI SQL plan
+	    boolean hasExpression = false;
+	    for (final Iterator<Expression> iterator = query.getGroupBy().getSymbols().iterator(); !hasExpression && iterator.hasNext();) {
+	        hasExpression = !(iterator.next() instanceof ElementSymbol);
+	    } 
+	    if (!hasExpression) {
+	    	return query;
+	    }
+		Select select = query.getSelect();
+	    GroupBy groupBy = query.getGroupBy();
+	    query.setGroupBy(null);
+	    Criteria having = query.getHaving();
+	    query.setHaving(null);
+	    OrderBy orderBy = query.getOrderBy();
+	    query.setOrderBy(null);
+	    Limit limit = query.getLimit();
+	    query.setLimit(null);
+	    Set<Expression> newSelectColumns = new HashSet<Expression>();
+	    for (final Iterator<Expression> iterator = groupBy.getSymbols().iterator(); iterator.hasNext();) {
+	        newSelectColumns.add(iterator.next());
+	    }
+	    Set<AggregateSymbol> aggs = new HashSet<AggregateSymbol>();
+	    aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(select, true));
+	    if (having != null) {
+	        aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(having, true));
+	    }
+	    for (AggregateSymbol aggregateSymbol : aggs) {
+	        if (aggregateSymbol.getExpression() != null) {
+	            Expression expr = aggregateSymbol.getExpression();
+	            newSelectColumns.add(SymbolMap.getExpression(expr));
+	        }
+	    }
+	    Select innerSelect = new Select();
+	    int index = 0;
+	    for (Expression expr : newSelectColumns) {
+	        if (expr instanceof SingleElementSymbol) {
+	            innerSelect.addSymbol((SingleElementSymbol)expr);
+	        } else {
+	            innerSelect.addSymbol(new ExpressionSymbol("EXPR" + index++ , expr)); //$NON-NLS-1$
+	        }
+	    }
+	    query.setSelect(innerSelect);
+	    Query outerQuery = null;
+	    try {
+	        outerQuery = QueryRewriter.createInlineViewQuery(new GroupSymbol("X"), query, metadata, query.getSelect().getProjectedSymbols()); //$NON-NLS-1$
+	    } catch (TeiidException err) {
+	        throw new TeiidRuntimeException(err);
+	    }
+	    Iterator<SingleElementSymbol> iter = outerQuery.getSelect().getProjectedSymbols().iterator();
+	    HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
+	    for (SingleElementSymbol symbol : query.getSelect().getProjectedSymbols()) {
+	        expressionMap.put(SymbolMap.getExpression(symbol), iter.next());
+	    }
+	    ExpressionMappingVisitor.mapExpressions(groupBy, expressionMap);
+	    outerQuery.setGroupBy(groupBy);
+	    ExpressionMappingVisitor.mapExpressions(having, expressionMap);
+	    outerQuery.setHaving(having);
+	    ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
+	    outerQuery.setOrderBy(orderBy);
+	    outerQuery.setLimit(limit);
+	    ExpressionMappingVisitor.mapExpressions(select, expressionMap);
+	    outerQuery.setSelect(select);
+	    outerQuery.setOption(query.getOption());
+	    query = outerQuery;
+		return query;
+	}
+
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleConstants.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleConstants.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleConstants.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,7 +34,6 @@
 	public static final OptimizerRule MERGE_VIRTUAL = new RuleMergeVirtual();
     public static final OptimizerRule CHOOSE_JOIN_STRATEGY = new RuleChooseJoinStrategy();
 	public static final OptimizerRule RAISE_ACCESS = new RuleRaiseAccess();
-    public static final OptimizerRule PUSH_AGGREGATES = new RulePushAggregates();
     public static final OptimizerRule CHOOSE_DEPENDENT = new RuleChooseDependent();
 	public static final OptimizerRule COLLAPSE_SOURCE = new RuleCollapseSource();
 	public static final OptimizerRule ASSIGN_OUTPUT_ELEMENTS = new RuleAssignOutputElements();

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleDecomposeJoin.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleDecomposeJoin.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleDecomposeJoin.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,7 +25,6 @@
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
@@ -208,20 +207,15 @@
 			throws TeiidComponentException, QueryPlannerException,
 			QueryMetadataException {
 		Set<String> groups = context.getGroups();
-        if (groups == null) {
-        	groups = new HashSet<String>();
-        	context.setGroups(groups);
-        }
 		
 		group = RulePlaceAccess.recontextSymbol(group, groups);
 		
 		PlanNode projectNode = NodeEditor.findNodePreOrder(newUnion, NodeConstants.Types.PROJECT);
 		List<? extends SingleElementSymbol> projectedSymbols = (List<? extends SingleElementSymbol>)projectNode.getProperty(Info.PROJECT_COLS);
 
-		PlanNode view = RulePushAggregates.createView(group, projectedSymbols, newUnion, metadata);
+    	SymbolMap newSymbolMap = RulePushAggregates.createSymbolMap(group, projectedSymbols, newUnion, metadata);
+	    PlanNode view = RuleDecomposeJoin.createSource(group, newUnion, newSymbolMap);
 		
-		SymbolMap newSymbolMap = (SymbolMap)view.getProperty(Info.SYMBOL_MAP);
-		
 		Map<Expression, ElementSymbol> inverseMap = newSymbolMap.inserseMapping();
 		toReplace.getParent().replaceChild(toReplace, view);
 		Set<GroupSymbol> newGroups = Collections.singleton(group);

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleImplementJoinStrategy.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,6 +24,7 @@
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Set;
@@ -116,6 +117,7 @@
 
             List<SingleElementSymbol> leftExpressions = (List<SingleElementSymbol>) joinNode.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS);
             List<SingleElementSymbol> rightExpressions = (List<SingleElementSymbol>) joinNode.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS);
+            int origExpressionCount = leftExpressions.size();
 
             //check index information on each side
             //TODO: don't do null order compensation - in fact we should check what the order actually is, but we don't have that metadata
@@ -152,7 +154,7 @@
 						toCriteria.add(j);
 					}
 				}
-        		List<Criteria> joinCriteria = (List<Criteria>) joinNode.getProperty(Info.JOIN_CRITERIA);
+        		List<Criteria> joinCriteria = (List<Criteria>) joinNode.getProperty(Info.NON_EQUI_JOIN_CRITERIA);
         		for (int index : toCriteria) {
 					SingleElementSymbol lses = leftExpressions.get(index);
 					SingleElementSymbol rses = rightExpressions.get(index);
@@ -163,17 +165,30 @@
 						joinNode.setProperty(Info.JOIN_TYPE, JoinType.JOIN_INNER);
 					}
 				}
-        		joinNode.setProperty(Info.JOIN_CRITERIA, joinCriteria);
+        		joinNode.setProperty(Info.NON_EQUI_JOIN_CRITERIA, joinCriteria);
         		leftExpressions = RelationalNode.projectTuple(reorder, leftExpressions);
             	rightExpressions = RelationalNode.projectTuple(reorder, rightExpressions);
             	joinNode.setProperty(NodeConstants.Info.LEFT_EXPRESSIONS, leftExpressions);
             	joinNode.setProperty(NodeConstants.Info.RIGHT_EXPRESSIONS, rightExpressions);
             }
-            
+
 			boolean pushedLeft = insertSort(joinNode.getFirstChild(), leftExpressions, joinNode, metadata, capabilitiesFinder, pushLeft);	
-			insertSort(joinNode.getLastChild(), rightExpressions, joinNode, metadata, capabilitiesFinder, pushRight);
-        	
-        	if (joinNode.getProperty(NodeConstants.Info.JOIN_TYPE) == JoinType.JOIN_INNER && (!pushRight || !pushedLeft)) {
+			
+	        if (origExpressionCount == 1 
+	        		&& joinNode.getProperty(NodeConstants.Info.JOIN_TYPE) == JoinType.JOIN_INNER 
+	        		&& joinNode.getProperty(NodeConstants.Info.DEPENDENT_VALUE_SOURCE) != null
+	        		&& !joinNode.hasCollectionProperty(Info.NON_EQUI_JOIN_CRITERIA)) {
+	        	Collection<SingleElementSymbol> output = (Collection<SingleElementSymbol>) joinNode.getProperty(NodeConstants.Info.OUTPUT_COLS);
+	        	Collection<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(output);
+	        	if (Collections.disjoint(groups, FrameUtil.findJoinSourceNode(joinNode.getFirstChild()).getGroups())) {
+	        		pushRight = false;
+	        		joinNode.setProperty(Info.IS_SEMI_DEP, Boolean.TRUE);
+	        	}
+			}
+
+			boolean pushedRight = insertSort(joinNode.getLastChild(), rightExpressions, joinNode, metadata, capabilitiesFinder, pushRight);
+			
+        	if (joinNode.getProperty(NodeConstants.Info.JOIN_TYPE) == JoinType.JOIN_INNER && (!pushedRight || !pushedLeft)) {
         		joinNode.setProperty(NodeConstants.Info.JOIN_STRATEGY, JoinStrategyType.ENHANCED_SORT);
         	}
         }
@@ -207,8 +222,22 @@
                 
         PlanNode sortNode = createSortNode(new ArrayList<SingleElementSymbol>(orderSymbols), outputSymbols);
         
+        boolean distinct = false;
+        if (sourceNode.getType() == NodeConstants.Types.SOURCE && outputSymbols.size() == expressions.size() && outputSymbols.containsAll(expressions)) {
+        	PlanNode setOp = NodeEditor.findNodePreOrder(sourceNode.getFirstChild(), NodeConstants.Types.SET_OP, NodeConstants.Types.SOURCE);
+        	if (setOp != null) {
+        		if (setOp.hasBooleanProperty(NodeConstants.Info.USE_ALL)) {
+        			distinct = true;
+        		}
+        	} else if (NodeEditor.findNodePreOrder(sourceNode.getFirstChild(), NodeConstants.Types.DUP_REMOVE, NodeConstants.Types.PROJECT) != null) {
+	        	distinct = true;
+	        }
+        }
+        
+        boolean sort = true;
+        
         if (sourceNode.getType() == NodeConstants.Types.ACCESS) {
-        	if (NewCalculateCostUtil.usesKey(sourceNode, expressions, metadata)) {
+        	if (distinct || NewCalculateCostUtil.usesKey(sourceNode, expressions, metadata)) {
                 joinNode.setProperty(joinNode.getFirstChild() == childNode ? NodeConstants.Info.IS_LEFT_DISTINCT : NodeConstants.Info.IS_RIGHT_DISTINCT, true);
         	}
 	        if (attemptPush && RuleRaiseAccess.canRaiseOverSort(sourceNode, metadata, capFinder, sortNode, null, false)) {
@@ -219,10 +248,19 @@
 	            }
 	            return true;
 	        }
+        } else if (sourceNode.getType() == NodeConstants.Types.GROUP) {
+        	sourceNode.addAsParent(sortNode);
+        	sort = false; // the grouping columns must contain all of the ordering columns
         }
         
-        joinNode.setProperty(joinNode.getFirstChild() == childNode ? NodeConstants.Info.SORT_LEFT : NodeConstants.Info.SORT_RIGHT, SortOption.SORT);
+        if (distinct) {
+            joinNode.setProperty(joinNode.getFirstChild() == childNode ? NodeConstants.Info.IS_LEFT_DISTINCT : NodeConstants.Info.IS_RIGHT_DISTINCT, true);
+    	}
         
+        if (sort) {
+        	joinNode.setProperty(joinNode.getFirstChild() == childNode ? NodeConstants.Info.SORT_LEFT : NodeConstants.Info.SORT_RIGHT, SortOption.SORT);
+        }        
+        
         if (needsCorrection) {
             PlanNode projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
             projectNode.setProperty(NodeConstants.Info.PROJECT_COLS, new ArrayList(outputSymbols));

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeCriteria.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -68,10 +68,10 @@
 import org.teiid.query.sql.lang.SubquerySetCriteria;
 import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
 import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.AliasSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
@@ -131,6 +131,7 @@
 		public Class<?> type;
 		public boolean mergeJoin;
 		public boolean madeDistinct;
+		public boolean makeInd;
 	}
 
 	private IDGenerator idGenerator;
@@ -363,6 +364,7 @@
 			result.not ^= ssc.isNegated();
 			result.type = crit.getClass();
 			result.mergeJoin = ssc.getSubqueryHint().isMergeJoin();
+			result.makeInd = ssc.getSubqueryHint().isDepJoin();
 			if (!UNNEST && !result.mergeJoin) {
 				return result;
 			}
@@ -417,11 +419,12 @@
 			result.type = crit.getClass();
 			result.not = exists.isNegated();
 			//the correlations can only be in where (if no group by or aggregates) or having
-			result.query = (Query)exists.getCommand();
 			result.mergeJoin = exists.getSubqueryHint().isMergeJoin();
+			result.makeInd = exists.getSubqueryHint().isDepJoin();
 			if (!UNNEST && !result.mergeJoin) {
 				return result;
 			}
+			result.query = (Query)exists.getCommand();
 		}
 		return result;
 	}
@@ -453,7 +456,7 @@
 
 	private boolean isSimpleJoin(Query query) {
 		if (query.getFrom() != null) {
-			for (FromClause clause : (List<FromClause>)query.getFrom().getClauses()) {
+			for (FromClause clause : query.getFrom().getClauses()) {
 				if (RuleCollapseSource.hasOuterJoins(clause)) {
 					return false;
 				}
@@ -477,7 +480,7 @@
 		plannedResult.query.setLimit(null);
 
 		List<GroupSymbol> rightGroups = plannedResult.query.getFrom().getGroups();
-		Set<SingleElementSymbol> requiredExpressions = new LinkedHashSet<SingleElementSymbol>();
+		Set<Expression> requiredExpressions = new LinkedHashSet<Expression>();
 		final SymbolMap refs = plannedResult.query.getCorrelatedReferences();
 		boolean addGroupBy = false;
 		if (refs != null) {
@@ -492,7 +495,7 @@
 				return false;
 			}
 			if (plannedResult.query.getGroupBy() == null) {
-				processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, where, true);
+				processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, where, null, true);
 				if (hasAggregates) {
 					if (!plannedResult.nonEquiJoinCriteria.isEmpty()) {
 						return false;
@@ -500,7 +503,7 @@
 					addGroupBy = true;
 				}
 			}
-			processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, having, false);
+			processCriteria(leftGroups, plannedResult, rightGroups, requiredExpressions, refs, having, plannedResult.query.getGroupBy(), false);
 		}
 				
 		if (plannedResult.additionalCritieria != null) {
@@ -523,29 +526,29 @@
 		}
 
 		if (addGroupBy) {
-			LinkedHashSet<SingleElementSymbol> groupingSymbols = new LinkedHashSet<SingleElementSymbol>();
-			ArrayList<SingleElementSymbol> aggs = new ArrayList<SingleElementSymbol>();
+			LinkedHashSet<Expression> groupingSymbols = new LinkedHashSet<Expression>();
 			for (Expression expr : (List<Expression>)plannedResult.rightExpressions) {
-				AggregateSymbolCollectorVisitor.getAggregates(expr, aggs, groupingSymbols);
+				AggregateSymbolCollectorVisitor.getAggregates(expr, null, groupingSymbols, null, null, null);
 			}
 			if (!groupingSymbols.isEmpty()) {
-				plannedResult.query.setGroupBy((GroupBy) new GroupBy(new ArrayList<SingleElementSymbol>(groupingSymbols)).clone());
+				plannedResult.query.setGroupBy((GroupBy) new GroupBy(new ArrayList<Expression>(groupingSymbols)).clone());
 			}
 		}
-		HashSet<SingleElementSymbol> projectedSymbols = new HashSet<SingleElementSymbol>();
+		HashSet<Expression> projectedSymbols = new HashSet<Expression>();
 		for (SingleElementSymbol ses : plannedResult.query.getProjectedSymbols()) {
-			if (ses instanceof AliasSymbol) {
-				ses = ((AliasSymbol)ses).getSymbol();
-			}
-			projectedSymbols.add(ses);
+			projectedSymbols.add(SymbolMap.getExpression(ses));
 		}
-		for (SingleElementSymbol ses : requiredExpressions) {
+		for (Expression ses : requiredExpressions) {
 			if (projectedSymbols.add(ses)) {
-				plannedResult.query.getSelect().addSymbol((SingleElementSymbol) ses.clone());
+				if (ses instanceof SingleElementSymbol) {
+					plannedResult.query.getSelect().addSymbol((SingleElementSymbol)ses);
+				} else {
+					plannedResult.query.getSelect().addSymbol(new ExpressionSymbol("expr", (Expression) ses.clone())); //$NON-NLS-1$
+				}
 			}
 		}
 		for (SingleElementSymbol ses : (List<SingleElementSymbol>)plannedResult.rightExpressions) {
-			if (projectedSymbols.add(ses)) {
+			if (projectedSymbols.add(SymbolMap.getExpression(ses))) {
 				plannedResult.query.getSelect().addSymbol((SingleElementSymbol)ses.clone());
 			}
 		}
@@ -554,8 +557,8 @@
 
 	private void processCriteria(Collection<GroupSymbol> leftGroups,
 			PlannedResult plannedResult, List<GroupSymbol> rightGroups,
-			Set<SingleElementSymbol> requiredExpressions, final SymbolMap refs,
-			Criteria joinCriteria, boolean where) {
+			Set<Expression> requiredExpressions, final SymbolMap refs,
+			Criteria joinCriteria, GroupBy groupBy, boolean where) {
 		if (joinCriteria == null) {
 			return;
 		}
@@ -563,9 +566,8 @@
 
 		for (Iterator<Criteria> critIter = crits.iterator(); critIter.hasNext();) {
 			Criteria conjunct = critIter.next();
-			List<SingleElementSymbol> aggregates = new LinkedList<SingleElementSymbol>();
-			List<SingleElementSymbol> elements = new LinkedList<SingleElementSymbol>();
-			AggregateSymbolCollectorVisitor.getAggregates(conjunct, aggregates, elements);
+			List<Expression> additionalRequired = new LinkedList<Expression>();
+			AggregateSymbolCollectorVisitor.getAggregates(conjunct, additionalRequired, additionalRequired, additionalRequired, null, groupBy!=null?groupBy.getSymbols():null);
 			ReferenceReplacementVisitor emv = new ReferenceReplacementVisitor(refs);
 			DeepPostOrderNavigator.doVisit(conjunct, emv);
 			if (!emv.replacedAny) {
@@ -577,8 +579,7 @@
 					plannedResult.query.setHaving(Criteria.combineCriteria(plannedResult.query.getHaving(), conjunct));
 				}
 			} else {
-				requiredExpressions.addAll(aggregates);
-				requiredExpressions.addAll(elements);
+				requiredExpressions.addAll(additionalRequired);
 			}
 		}
 		RuleChooseJoinStrategy.separateCriteria(leftGroups, rightGroups, plannedResult.leftExpressions, plannedResult.rightExpressions, crits, plannedResult.nonEquiJoinCriteria);
@@ -589,7 +590,7 @@
 		boolean distinct = false;
 		if (query.getGroupBy() != null) {
 			distinct = true;
-			for (SingleElementSymbol groupByExpr :  (List<SingleElementSymbol>)query.getGroupBy().getSymbols()) {
+			for (Expression groupByExpr : query.getGroupBy().getSymbols()) {
 				if (!expressions.contains(groupByExpr)) {
 					distinct = false;
 					break;

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleMergeVirtual.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,6 +41,7 @@
 import org.teiid.query.optimizer.relational.plantree.NodeEditor;
 import org.teiid.query.optimizer.relational.plantree.PlanNode;
 import org.teiid.query.optimizer.relational.plantree.NodeConstants.Info;
+import org.teiid.query.resolver.util.AccessPattern;
 import org.teiid.query.sql.lang.JoinType;
 import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.lang.OrderByItem;
@@ -126,9 +127,6 @@
         		for (ElementSymbol elementSymbol : elements) {
 					if (virtualGroup.equals(elementSymbol.getGroupSymbol())) {
 						unrelated = true;
-						if (!(symbolMap.getMappedExpression(elementSymbol) instanceof ElementSymbol)) {
-							return root;
-						}
 					}
 				}
 			}
@@ -164,13 +162,7 @@
             return root;
         }
         
-        PlanNode parentGroup = NodeEditor.findParent(frame, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE);
-        List<SingleElementSymbol> groupCols = null;
-        if (parentGroup != null) {
-        	groupCols = (List<SingleElementSymbol>)parentGroup.getProperty(NodeConstants.Info.GROUP_COLS);
-        }
-
-        if (!checkProjectedSymbols(projectNode, virtualGroup, parentJoin, groupCols, symbolMap, metadata)) {
+        if (!checkProjectedSymbols(projectNode, virtualGroup, parentJoin, metadata)) {
             return root;
         }
 
@@ -193,9 +185,9 @@
         // find the new root of the frame so that access patterns can be propagated
         PlanNode newRoot = FrameUtil.findJoinSourceNode(frame.getFirstChild());
         if (newRoot != null) {
-            Collection ap = (Collection)frame.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+            Collection<AccessPattern> ap = (Collection)frame.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
             if (ap != null) {
-                Collection newAp = (Collection)newRoot.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
+                Collection<AccessPattern> newAp = (Collection)newRoot.getProperty(NodeConstants.Info.ACCESS_PATTERNS);
                 if (newAp == null) {
                     newRoot.setProperty(NodeConstants.Info.ACCESS_PATTERNS, ap);
                 } else {
@@ -326,9 +318,11 @@
     private static boolean checkProjectedSymbols(PlanNode projectNode,
                                                  GroupSymbol virtualGroup,
                                                  PlanNode parentJoin,
-                                                 List<SingleElementSymbol> parentGroupingCols,
-                                                 SymbolMap symbolMap,
                                                  QueryMetadataInterface metadata) {
+        if (projectNode.hasBooleanProperty(Info.HAS_WINDOW_FUNCTIONS)) {
+        	return false;
+        }
+
         List<SingleElementSymbol> selectSymbols = (List<SingleElementSymbol>)projectNode.getProperty(NodeConstants.Info.PROJECT_COLS);
         
         HashSet<GroupSymbol> groups = new HashSet<GroupSymbol>();
@@ -354,7 +348,6 @@
             }
         }
 
-        List<ElementSymbol> virtualElements = symbolMap.getKeys();
         for (int i = 0; i < selectSymbols.size(); i++) {
         	SingleElementSymbol symbol = selectSymbols.get(i);
             Collection scalarSubqueries = ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(symbol);
@@ -364,9 +357,6 @@
             if (checkForNullDependent && JoinUtil.isNullDependent(metadata, groups, SymbolMap.getExpression(symbol))) {
                 return false;
             }
-            if (parentGroupingCols != null && !(SymbolMap.getExpression(symbol) instanceof SingleElementSymbol) && parentGroupingCols.contains(virtualElements.get(i))) {
-                return false;
-            }
             // TEIID-16: We do not want to merge a non-deterministic scalar function
             if (FunctionCollectorVisitor.isNonDeterministic(symbol)) {
             	return false;

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlaceAccess.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -69,10 +69,6 @@
                                                    QueryPlannerException {
 
         Set<String> groups = context.getGroups();
-        if (groups == null) {
-        	groups = new HashSet<String>();
-        	context.setGroups(groups);
-        }
 
         boolean[] addtionalRules = new boolean[2];
 
@@ -286,6 +282,10 @@
         if (hint != null) {
             copyTo.setProperty(NodeConstants.Info.MAKE_NOT_DEP, hint);
         }
+        hint = node.getProperty(NodeConstants.Info.MAKE_IND);
+        if (hint != null) {
+            copyTo.setProperty(NodeConstants.Info.MAKE_IND, hint);
+        }
     }
 
     /**

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanJoins.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -466,7 +466,7 @@
                 }
                 JoinType jt = (JoinType)root.getProperty(NodeConstants.Info.JOIN_TYPE);
                 
-                boolean treatJoinAsSource = jt.isOuter() || root.getProperty(NodeConstants.Info.ACCESS_PATTERNS) != null || root.hasProperty(NodeConstants.Info.MAKE_DEP);
+                boolean treatJoinAsSource = jt.isOuter() || root.getProperty(NodeConstants.Info.ACCESS_PATTERNS) != null || root.hasProperty(NodeConstants.Info.MAKE_DEP) || root.hasProperty(NodeConstants.Info.MAKE_IND);
                 
                 if (treatJoinAsSource) {
                     currentRegion.addJoinSourceNode(root);

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanSorts.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanSorts.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePlanSorts.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,6 +22,7 @@
 
 package org.teiid.query.optimizer.relational.rules;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import org.teiid.api.exception.query.QueryMetadataException;
@@ -43,8 +44,11 @@
 import org.teiid.query.sql.lang.SetQuery;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.util.CommandContext;
 
 
@@ -85,14 +89,27 @@
 			} else {
 				root = checkForProjectOptimization(node, root, metadata, capFinder, record);
 			}
-			List<SingleElementSymbol> orderColumns = ((OrderBy)node.getProperty(NodeConstants.Info.SORT_ORDER)).getSortKeys();
+			OrderBy orderBy = (OrderBy)node.getProperty(NodeConstants.Info.SORT_ORDER);
+			List<SingleElementSymbol> orderColumns = orderBy.getSortKeys();
+			List<Expression> sortExpressions = new ArrayList<Expression>(orderColumns.size());
 			PlanNode possibleSort = NodeEditor.findNodePreOrder(node, NodeConstants.Types.GROUP, NodeConstants.Types.SOURCE | NodeConstants.Types.ACCESS);
 			if (possibleSort != null) {
-				List exprs = (List)possibleSort.getProperty(Info.GROUP_COLS);
-				if (exprs != null && exprs.containsAll(orderColumns)) {
-					exprs.removeAll(orderColumns);
-					orderColumns.addAll(exprs);
-					possibleSort.setProperty(Info.GROUP_COLS, orderColumns);
+				boolean otherExpression = false;
+				SymbolMap groupMap = (SymbolMap)possibleSort.getProperty(Info.SYMBOL_MAP);
+				for (SingleElementSymbol singleElementSymbol : orderColumns) {
+					Expression ex = SymbolMap.getExpression(singleElementSymbol);
+					if (ex instanceof ElementSymbol) {
+						sortExpressions.add(groupMap.getMappedExpression((ElementSymbol) ex));						
+					} else {
+						otherExpression = true;
+						break;
+					}
+				}
+
+				List<Expression> exprs = (List<Expression>)possibleSort.getProperty(Info.GROUP_COLS);
+				if (!otherExpression && exprs != null && exprs.containsAll(sortExpressions)) {
+					exprs.removeAll(sortExpressions);
+					exprs.addAll(0, sortExpressions);
 					if (node.getParent() == null) {
 						root = node.getFirstChild();
 						root.removeFromParent();
@@ -102,57 +119,10 @@
 						NodeEditor.removeChildNode(node.getParent(), node);
 						node = nextNode;
 					}
+					possibleSort.setProperty(Info.SORT_ORDER, orderBy);
 				}
 				break;
 			} 
-/*			possibleSort = NodeEditor.findNodePreOrder(node, NodeConstants.Types.JOIN, NodeConstants.Types.SOURCE | NodeConstants.Types.ACCESS);
-			if (possibleSort == null) {
-				break;
-			}
-			boolean left = false;
-			if (possibleSort.getType() == NodeConstants.Types.JOIN) {
-				if (possibleSort.getProperty(NodeConstants.Info.JOIN_STRATEGY) != JoinStrategyType.MERGE
-					|| possibleSort.getProperty(NodeConstants.Info.JOIN_TYPE) != JoinType.JOIN_INNER) {
-					break;
-				} 
-				if (FrameUtil.findJoinSourceNode(possibleSort.getFirstChild()).getGroups().containsAll(node.getGroups()) 
-						&& possibleSort.getProperty(NodeConstants.Info.SORT_LEFT) == SortOption.SORT) {
-					left = true;
-				} else if (!FrameUtil.findJoinSourceNode(possibleSort.getLastChild()).getGroups().containsAll(node.getGroups()) 
-						|| possibleSort.getProperty(NodeConstants.Info.SORT_RIGHT) != SortOption.SORT) {
-					break;
-				}
-			}
-			List exprs = (List)possibleSort.getProperty(left?Info.LEFT_EXPRESSIONS:Info.RIGHT_EXPRESSIONS);
-			if (exprs != null && exprs.containsAll(orderColumns)) {
-				List<Integer> indexes = new ArrayList<Integer>(orderColumns.size());
-				for (Expression expr : (List<Expression>)orderColumns) {
-					indexes.add(0, exprs.indexOf(expr));
-				}
-				exprs.removeAll(orderColumns);
-				List newExprs = new ArrayList(orderColumns);
-				newExprs.addAll(exprs);
-				possibleSort.setProperty(left?Info.LEFT_EXPRESSIONS:Info.RIGHT_EXPRESSIONS, newExprs);
-				if (node.getParent() == null) {
-					root = node.getFirstChild();
-					root.removeFromParent();
-					node = root;
-				} else {
-					PlanNode nextNode = node.getFirstChild();
-					NodeEditor.removeChildNode(node.getParent(), node);
-					node = nextNode;
-				}
-				exprs = (List)possibleSort.getProperty(left?Info.RIGHT_EXPRESSIONS:Info.LEFT_EXPRESSIONS);
-				List toRemove = new ArrayList();
-				for (Integer index : indexes) {
-					Object o = exprs.get(index);
-					exprs.add(0, o);
-					toRemove.add(o);
-				}
-				exprs.subList(indexes.size(), exprs.size()).removeAll(toRemove);
-				possibleSort.setProperty(left?NodeConstants.Info.SORT_LEFT:NodeConstants.Info.SORT_RIGHT, SortOption.SORT_REQUIRED);
-			}
-*/
 			break;
 		case NodeConstants.Types.DUP_REMOVE:
 			if (parentBlocking) {
@@ -164,8 +134,33 @@
 			if (!node.hasCollectionProperty(NodeConstants.Info.GROUP_COLS)) {
 				break;
 			}
-			if (mergeSortWithDupRemovalAcrossSource(node)) {
+			SymbolMap map = (SymbolMap)node.getProperty(Info.SYMBOL_MAP);
+			boolean cardinalityDependent = false;
+			boolean canOptimize = true;
+			for (Expression ex : map.asMap().values()) {
+				if (ex instanceof AggregateSymbol) {
+					AggregateSymbol agg = (AggregateSymbol)ex;
+					if (agg.isCardinalityDependent()) {
+						cardinalityDependent = true;
+						break;
+					}
+				} else if (!(ex instanceof ElementSymbol)) {
+					//there is an expression in the grouping columns
+					canOptimize = false;
+					break;
+				}
+			}
+			if (canOptimize && mergeSortWithDupRemovalAcrossSource(node)) {
 				node.setProperty(NodeConstants.Info.IS_DUP_REMOVAL, true);
+				if (cardinalityDependent) {
+					PlanNode source = NodeEditor.findNodePreOrder(node, NodeConstants.Types.SOURCE);
+					List<SingleElementSymbol> sourceOutput = (List<SingleElementSymbol>)source.getProperty(Info.OUTPUT_COLS);
+					PlanNode child = node.getFirstChild();
+					while (child != source) {
+						child.setProperty(Info.OUTPUT_COLS, sourceOutput);
+						child = child.getFirstChild();
+					}
+				}
 			}
 			//TODO: check the join interesting order
 			parentBlocking = true;
@@ -243,13 +238,8 @@
 			if(ss instanceof AliasSymbol) {
                 ss = ((AliasSymbol)ss).getSymbol();
             }
-            
             if (ss instanceof ExpressionSymbol && !(ss instanceof AggregateSymbol)) {
-                ExpressionSymbol exprSymbol = (ExpressionSymbol)ss;
-                
-                if (!exprSymbol.isDerivedExpression()) {
-                    return root; //TODO: insert a new project node to handle this case
-                } 
+                return root; //TODO: insert a new project node to handle this case
             }
 			if (!childOutputCols.contains(ss)) {
 				return root;

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushAggregates.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,6 +29,7 @@
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.LinkedHashSet;
 import java.util.LinkedList;
 import java.util.List;
@@ -39,17 +40,18 @@
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.id.IDGenerator;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.language.SQLConstants.NonReserved;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.function.FunctionLibrary;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataAdapter;
-import org.teiid.query.metadata.TempMetadataID;
 import org.teiid.query.metadata.TempMetadataStore;
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.optimizer.relational.OptimizerRule;
+import org.teiid.query.optimizer.relational.RelationalPlanner;
 import org.teiid.query.optimizer.relational.RuleStack;
 import org.teiid.query.optimizer.relational.plantree.NodeConstants;
 import org.teiid.query.optimizer.relational.plantree.NodeEditor;
@@ -60,7 +62,6 @@
 import org.teiid.query.resolver.util.ResolverVisitor;
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageObject.Util;
 import org.teiid.query.sql.lang.CompareCriteria;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.lang.IsNullCriteria;
@@ -93,6 +94,12 @@
  */
 public class RulePushAggregates implements
                                OptimizerRule {
+	
+	private IDGenerator idGenerator;
+	
+	public RulePushAggregates(IDGenerator idGenerator) {
+		this.idGenerator = idGenerator;
+	}
 
     /**
      * @see org.teiid.query.optimizer.relational.OptimizerRule#execute(org.teiid.query.optimizer.relational.plantree.PlanNode,
@@ -112,13 +119,16 @@
         for (PlanNode groupNode : NodeEditor.findAllNodes(plan, NodeConstants.Types.GROUP, NodeConstants.Types.ACCESS)) {
             PlanNode child = groupNode.getFirstChild();
 
-        	List<SingleElementSymbol> groupingExpressions = (List<SingleElementSymbol>)groupNode.getProperty(NodeConstants.Info.GROUP_COLS);
+        	List<Expression> groupingExpressions = (List<Expression>)groupNode.getProperty(NodeConstants.Info.GROUP_COLS);
+        	if (groupingExpressions == null) {
+        		groupingExpressions = Collections.emptyList();
+        	}
             
             if (child.getType() == NodeConstants.Types.SOURCE) {
                 PlanNode setOp = child.getFirstChild();
                 
                 try {
-					pushGroupNodeOverUnion(plan, metadata, capFinder, groupNode, child, groupingExpressions, setOp, context);
+					pushGroupNodeOverUnion(metadata, capFinder, groupNode, child, groupingExpressions, setOp, context, analysisRecord);
 				} catch (QueryResolverException e) {
 					throw new TeiidComponentException(e);
 				}
@@ -131,7 +141,7 @@
 
             Set<AggregateSymbol> aggregates = collectAggregates(groupNode);
 
-            pushGroupNode(groupNode, groupingExpressions, aggregates, metadata, capFinder);
+            pushGroupNode(groupNode, groupingExpressions, aggregates, metadata, capFinder, context);
         }
 
         return plan;
@@ -158,32 +168,19 @@
 	 *       ...
 	 *       
 	 * Or if the child does not support pushdown we add dummy aggregate projection
-     * count(*) = 1, count(x) = case x is null then 0 else 1 end, avg(x) = x, etc.
-     * 
-     * if partitioned, then we don't need decomposition or the top level group by
-     * 
-	 *   source
-	 *     set op
-	 *       project
-	 *         [select]
-	 *           group [agg(x), {a, b}]
-	 *             source
-	 *               child 1
-	 *       ...
-     * 
+     * count(*) = 1, count(x) = case x is null then 0 else 1 end, avg(x) = x, etc. 
 	 */
-	private void pushGroupNodeOverUnion(PlanNode plan,
-			QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
-			PlanNode groupNode, PlanNode child,
-			List<SingleElementSymbol> groupingExpressions, PlanNode setOp, CommandContext context)
+	private void pushGroupNodeOverUnion(QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+			PlanNode groupNode, PlanNode unionSourceParent,
+			List<Expression> groupingExpressions, PlanNode setOp, CommandContext context, AnalysisRecord record)
 			throws TeiidComponentException, QueryMetadataException,
 			QueryPlannerException, QueryResolverException {
-		if (setOp == null || setOp.getType() != NodeConstants.Types.SET_OP || setOp.getProperty(NodeConstants.Info.SET_OPERATION) != Operation.UNION) {
-			return; //must not be a union
+		if (setOp == null || setOp.getProperty(NodeConstants.Info.SET_OPERATION) != Operation.UNION) {
+			return;
 		}
 		LinkedHashSet<AggregateSymbol> aggregates = collectAggregates(groupNode);
 
-		Map<ElementSymbol, List<Set<Constant>>> partitionInfo = (Map<ElementSymbol, List<Set<Constant>>>)child.getProperty(Info.PARTITION_INFO);
+		Map<ElementSymbol, List<Set<Constant>>> partitionInfo = (Map<ElementSymbol, List<Set<Constant>>>)unionSourceParent.getProperty(Info.PARTITION_INFO);
 
 		//check to see if any aggregate is dependent upon cardinality
 		boolean cardinalityDependent = AggregateSymbol.areAggregatesCardinalityDependent(aggregates);
@@ -191,11 +188,11 @@
 		LinkedList<PlanNode> unionChildren = new LinkedList<PlanNode>();
 		findUnionChildren(unionChildren, cardinalityDependent, setOp);
 
-		SymbolMap parentMap = (SymbolMap)child.getProperty(NodeConstants.Info.SYMBOL_MAP);
+		SymbolMap parentMap = (SymbolMap)unionSourceParent.getProperty(NodeConstants.Info.SYMBOL_MAP);
 
 		//partitioned union
 		if (partitionInfo != null && !Collections.disjoint(partitionInfo.keySet(), groupingExpressions)) {
-			decomposeGroupBy(groupNode, child, groupingExpressions, aggregates, unionChildren, parentMap, context, metadata, capFinder);
+			decomposeGroupBy(groupNode, unionSourceParent, groupingExpressions, aggregates, unionChildren, parentMap, metadata, capFinder, context);
 			return;
 		}
 
@@ -205,10 +202,15 @@
 		 * serves as a hint to distribute a distinct to the union queries
 		 */
 		if (aggregates.isEmpty()) {
-			if (groupingExpressions != null && !groupingExpressions.isEmpty()) {
+			if (!groupingExpressions.isEmpty()) {
 				setOp.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
 			}
 			return;
+		} 
+		for (AggregateSymbol agg : aggregates) {
+			if (!agg.canStage()) {
+				return;
+			}
 		}
 		
 		//TODO: merge virtual, plan unions, raise null - change the partition information
@@ -217,15 +219,15 @@
 			return;
 		}
 		
-		List<ElementSymbol> virtualElements = parentMap.getKeys();
 		List<SingleElementSymbol> copy = new ArrayList<SingleElementSymbol>(aggregates);
 		aggregates.clear();
 		Map<AggregateSymbol, Expression> aggMap = buildAggregateMap(copy, metadata, aggregates);
-
+		
 		boolean shouldPushdown = false;
 		List<Boolean> pushdownList = new ArrayList<Boolean>(unionChildren.size());
+		
 		for (PlanNode planNode : unionChildren) {
-			boolean pushdown = canPushGroupByToUnionChild(metadata, capFinder, groupingExpressions, aggregates, planNode); 
+			boolean pushdown = canPushGroupByToUnionChild(metadata, capFinder, groupingExpressions, aggregates, planNode, record); 
 			pushdownList.add(pushdown);
 			shouldPushdown |= pushdown;
 		}
@@ -234,91 +236,239 @@
 			return;
 		}
 
+		GroupSymbol group = unionSourceParent.getGroups().iterator().next().clone();
+
 		Iterator<Boolean> pushdownIterator = pushdownList.iterator();
+		boolean first = true;
 		for (PlanNode planNode : unionChildren) {
-		    addView(plan, planNode, pushdownIterator.next(), groupingExpressions, aggregates, virtualElements, metadata, capFinder);
+			addUnionGroupBy(groupingExpressions, aggregates, parentMap, metadata, capFinder, context, group, first, planNode, !pushdownIterator.next());
+			first = false;
 		}
 		
-		//update the parent plan with the staged aggregates and the new projected symbols
-		List<SingleElementSymbol> projectedViewSymbols = (List<SingleElementSymbol>)NodeEditor.findNodePreOrder(child, NodeConstants.Types.PROJECT).getProperty(NodeConstants.Info.PROJECT_COLS);
-		List<ElementSymbol> updatedVirturalElement = new ArrayList<ElementSymbol>(virtualElements);
+		updateParentAggs(groupNode, context, aggMap, metadata);
 		
-		//hack to introduce aggregate symbols to the parent view TODO: this should change the metadata properly.
-		GroupSymbol virtualGroup = child.getGroups().iterator().next();
-		for (int i = updatedVirturalElement.size(); i < projectedViewSymbols.size(); i++) {
-			SingleElementSymbol symbol = projectedViewSymbols.get(i);
-			String name = symbol.getShortName();
-            String virtualElementName = virtualGroup.getCanonicalName() + ElementSymbol.SEPARATOR + name;
-            ElementSymbol virtualElement = new ElementSymbol(virtualElementName);
-            virtualElement.setGroupSymbol(virtualGroup);
-            virtualElement.setType(symbol.getType());
-            virtualElement.setMetadataID(new TempMetadataID(virtualElementName, symbol.getType()));
-            updatedVirturalElement.add(virtualElement);
+		List<SingleElementSymbol> symbols = (List<SingleElementSymbol>) NodeEditor.findNodePreOrder(unionSourceParent, NodeConstants.Types.PROJECT).getProperty(Info.PROJECT_COLS);
+		GroupSymbol modifiedGroup = group.clone();
+		SymbolMap symbolMap = createSymbolMap(modifiedGroup, symbols, unionSourceParent, metadata);
+		unionSourceParent.setProperty(Info.SYMBOL_MAP, symbolMap);
+		
+		//correct the parent frame
+		Map<Expression, ElementSymbol> mapping = new HashMap<Expression, ElementSymbol>();
+		Iterator<ElementSymbol> elemIter = symbolMap.getKeys().iterator();
+		for (Expression expr : groupingExpressions) {
+			mapping.put(expr, elemIter.next());
 		}
-		SymbolMap newParentMap = SymbolMap.createSymbolMap(updatedVirturalElement, projectedViewSymbols);
-		child.setProperty(NodeConstants.Info.SYMBOL_MAP, newParentMap);
-		Map<AggregateSymbol, ElementSymbol> projectedMap = new HashMap<AggregateSymbol, ElementSymbol>();
-		Iterator<AggregateSymbol> aggIter = aggregates.iterator();
-		for (ElementSymbol projectedViewSymbol : newParentMap.getKeys().subList(projectedViewSymbols.size() - aggregates.size(), projectedViewSymbols.size())) {
-			projectedMap.put(aggIter.next(), projectedViewSymbol);
+		for (AggregateSymbol agg : aggregates) {
+			mapping.put(agg, elemIter.next());
 		}
-		for (Expression expr : aggMap.values()) {
-			ExpressionMappingVisitor.mapExpressions(expr, projectedMap);
+		PlanNode node = unionSourceParent;
+		while (node != groupNode.getParent()) {
+			FrameUtil.convertNode(node, null, null, mapping, metadata, false);
+			node = node.getParent();
 		}
-		mapExpressions(groupNode.getParent(), aggMap, metadata);
 	}
 
+	private void updateParentAggs(PlanNode groupNode, CommandContext context,
+			Map<AggregateSymbol, Expression> aggMap, QueryMetadataInterface metadata)
+			throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
+		LinkedHashSet<AggregateSymbol> compositeAggs = new LinkedHashSet<AggregateSymbol>();
+		boolean hasExpressionMapping = false;
+		for (Expression ex : aggMap.values()) {
+			if (ex instanceof AggregateSymbol) {
+				compositeAggs.add((AggregateSymbol) ex);
+			} else {
+				compositeAggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(ex, false));
+				hasExpressionMapping = true;
+			}
+		}
+		if (!hasExpressionMapping) {
+			//if no new expressions are created we can just modify the existing aggregates
+			FrameUtil.correctSymbolMap(aggMap, groupNode);
+		} else {
+			//if new expressions are created we insert a view to handle the projection
+			groupNode.getGroups().clear();
+			SymbolMap oldGroupingMap = (SymbolMap) groupNode.getProperty(Info.SYMBOL_MAP);
+			GroupSymbol oldGroup = oldGroupingMap.asMap().keySet().iterator().next().getGroupSymbol();
+			SymbolMap groupingMap = RelationalPlanner.buildGroupingNode(compositeAggs, (List<? extends Expression>) groupNode.getProperty(Info.GROUP_COLS), groupNode, context, idGenerator);
+			ArrayList<SingleElementSymbol> projectCols = new ArrayList<SingleElementSymbol>(oldGroupingMap.asMap().size());
+			SymbolMap correctedMap = new SymbolMap();
+			Map<Expression, ElementSymbol> inverseMap = groupingMap.inserseMapping();
+			for (Map.Entry<ElementSymbol, Expression> entry : oldGroupingMap.asMap().entrySet()) {
+				SingleElementSymbol ses = null;
+				if (entry.getValue() instanceof AggregateSymbol) {
+					Expression ex = aggMap.get(entry.getValue());
+					if (ex instanceof AggregateSymbol) {
+						ses = inverseMap.get(ex);
+					} else {
+						ExpressionMappingVisitor.mapExpressions(ex, inverseMap);
+						ses = new ExpressionSymbol("expr", ex); //$NON-NLS-1$
+					}
+				} else {
+					ses = inverseMap.get(entry.getValue());
+				}
+				ses = (SingleElementSymbol) ses.clone();
+				projectCols.add(new AliasSymbol(entry.getKey().getShortCanonicalName(), ses));
+				correctedMap.addMapping(entry.getKey(), SymbolMap.getExpression(ses));
+			}
+			PlanNode projectNode = groupNode.getParent();
+			if (projectNode.getType() != NodeConstants.Types.PROJECT) {
+				projectNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+				groupNode.addAsParent(projectNode);
+				projectNode.setProperty(Info.PROJECT_COLS, projectCols);
+				RuleDecomposeJoin.createSource(oldGroup, projectNode, correctedMap);
+			} else {
+				FrameUtil.convertFrame(projectNode, oldGroup, null, correctedMap.asMap(), metadata);
+			}
+		}
+	}
+
+    /* if partitioned, then we don't need decomposition or the top level group by
+     * 
+	 *   source
+	 *     set op
+	 *       project
+	 *           group [agg(x), {a, b}]
+	 *             source
+	 *               child 1
+	 *       ...
+     * 
+     */
 	private void decomposeGroupBy(PlanNode groupNode, PlanNode sourceNode,
-			List<SingleElementSymbol> groupingExpressions,
+			List<Expression> groupingExpressions,
 			LinkedHashSet<AggregateSymbol> aggregates,
-			LinkedList<PlanNode> unionChildren, SymbolMap parentMap, CommandContext context, QueryMetadataInterface metadata, CapabilitiesFinder capFinder) throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
+			LinkedList<PlanNode> unionChildren, SymbolMap parentMap, QueryMetadataInterface metadata, 
+			CapabilitiesFinder capFinder, CommandContext cc) throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
 		// remove the group node
 		groupNode.getParent().replaceChild(groupNode, groupNode.getFirstChild());
+		
 		GroupSymbol group = sourceNode.getGroups().iterator().next().clone();
 
 		boolean first = true;
-		List<SingleElementSymbol> symbols = null;
 		for (PlanNode planNode : unionChildren) {
-			PlanNode groupClone = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
-			groupClone.setProperty(Info.GROUP_COLS, LanguageObject.Util.deepClone(groupingExpressions, SingleElementSymbol.class));
-			groupClone.addGroups(groupNode.getGroups());
-			
-			PlanNode view = RuleDecomposeJoin.createSource(group, planNode, parentMap);
-			
-			view.addAsParent(groupClone);
-			
-			PlanNode projectPlanNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
-			
-			Select allSymbols = new Select(groupingExpressions);
-			allSymbols.addSymbols(aggregates);
-			if (first) {
-				first = false;
-				QueryRewriter.makeSelectUnique(allSymbols, false);
-				symbols = allSymbols.getSymbols();
-			}
-			projectPlanNode.setProperty(NodeConstants.Info.PROJECT_COLS, allSymbols.getSymbols());
-		    projectPlanNode.addGroups(view.getGroups());
-		    
-		    groupClone.addAsParent(projectPlanNode);
-		    
-		    if (planNode.getType() == NodeConstants.Types.ACCESS) {
-		    	//TODO: temporarily remove the access node so that the inline view could be removed if possible 
-			    while (RuleRaiseAccess.raiseAccessNode(planNode, planNode, metadata, capFinder, true, null) != null) {
-	        		//continue to raise
-	        	}
-		    }
+			addUnionGroupBy(groupingExpressions, aggregates,
+					parentMap, metadata, capFinder, cc, group, first,
+					planNode, false);
+			first = false;
 		}
+		List<SingleElementSymbol> symbols = (List<SingleElementSymbol>) NodeEditor.findNodePreOrder(sourceNode, NodeConstants.Types.PROJECT).getProperty(Info.PROJECT_COLS);
 		GroupSymbol modifiedGroup = group.clone();
 		SymbolMap symbolMap = createSymbolMap(modifiedGroup, symbols, sourceNode, metadata);
 		sourceNode.setProperty(Info.SYMBOL_MAP, symbolMap);
+
+		//map from the anon group to the updated inline view group
+		SymbolMap map = (SymbolMap)groupNode.getProperty(Info.SYMBOL_MAP);
+		Map<Expression, ElementSymbol> inverse = map.inserseMapping();
+		SymbolMap newMapping = (SymbolMap) NodeEditor.findNodePreOrder(sourceNode, NodeConstants.Types.GROUP).getProperty(Info.SYMBOL_MAP);
 		
-		FrameUtil.convertFrame(sourceNode, group, Collections.singleton(modifiedGroup), symbolMap.inserseMapping(), metadata);
+		GroupSymbol oldGroup = null;
+		Map<ElementSymbol, ElementSymbol> updatedMapping = new HashMap<ElementSymbol, ElementSymbol>();
+		for (Map.Entry<ElementSymbol, Expression> entry : symbolMap.asMap().entrySet()) {
+			Expression ex = newMapping.getMappedExpression((ElementSymbol) entry.getValue());
+			ElementSymbol orig = inverse.get(ex);
+			oldGroup = orig.getGroupSymbol();
+			updatedMapping.put(orig, entry.getKey());
+		}
+		FrameUtil.convertFrame(sourceNode, oldGroup, Collections.singleton(modifiedGroup), updatedMapping, metadata);
 	}
 
+	private void addUnionGroupBy(
+			List<Expression> groupingExpressions,
+			LinkedHashSet<AggregateSymbol> aggregates, SymbolMap parentMap,
+			QueryMetadataInterface metadata, CapabilitiesFinder capFinder,
+			CommandContext cc, GroupSymbol group, boolean first, PlanNode planNode, boolean viewOnly)
+			throws QueryMetadataException, TeiidComponentException,
+			QueryPlannerException, QueryResolverException {
+		List<Expression> groupingColumns = LanguageObject.Util.deepClone(groupingExpressions, Expression.class);
+		
+		//branches other than the first need to have their projected column names updated
+		if (!first) {
+			PlanNode sortNode = NodeEditor.findNodePreOrder(planNode, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
+			List<SingleElementSymbol> sortOrder = null;
+			OrderBy orderBy = null;
+			if (sortNode != null) {
+				orderBy = (OrderBy)sortNode.getProperty(Info.SORT_ORDER);
+				sortOrder = orderBy.getSortKeys();
+			}
+			List<SingleElementSymbol> projectCols = FrameUtil.findTopCols(planNode);
+			List<ElementSymbol> virtualElements = parentMap.getKeys();
+			for (int i = 0; i < virtualElements.size(); i++) {
+				ElementSymbol virtualElem = virtualElements.get(i);
+				SingleElementSymbol projectedSymbol = projectCols.get(i);
+				if (!projectedSymbol.getShortCanonicalName().equals(virtualElem.getShortCanonicalName())) {
+					if (sortOrder != null) {
+						int sortIndex = sortOrder.indexOf(projectedSymbol);
+						if (sortIndex > -1) {
+							updateSymbolName(sortOrder, sortIndex, virtualElem, sortOrder.get(sortIndex));
+							orderBy.getOrderByItems().get(sortIndex).setSymbol(sortOrder.get(sortIndex));
+						}
+					}
+					updateSymbolName(projectCols, i, virtualElem, projectedSymbol);
+				}
+			}
+		}
+		
+		PlanNode view = RuleDecomposeJoin.createSource(group, planNode, parentMap);
+		
+		PlanNode projectPlanNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
+		
+		Select allSymbols = new Select();
+		for (Expression expr : groupingColumns) {
+			allSymbols.addSymbol(new ExpressionSymbol("expr", expr)); //$NON-NLS-1$
+		}
+		if (viewOnly) {
+			for (AggregateSymbol agg : aggregates) {
+	        	agg = (AggregateSymbol)agg.clone();
+	    		if (agg.getAggregateFunction() == Type.COUNT) {
+	    			if (agg.getExpression() == null) {
+	    				allSymbols.addSymbol(new ExpressionSymbol("stagedAgg", new Constant(1))); //$NON-NLS-1$
+	    			} else { 
+	        			SearchedCaseExpression count = new SearchedCaseExpression(Arrays.asList(new IsNullCriteria(agg.getExpression())), Arrays.asList(new Constant(Integer.valueOf(0))));
+	        			count.setElseExpression(new Constant(Integer.valueOf(1)));
+	        			count.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+	        			allSymbols.addSymbol(new ExpressionSymbol("stagedAgg", count)); //$NON-NLS-1$
+	    			}
+	    		} else { //min, max, sum
+	    			Expression ex = agg.getExpression();
+	    			ex = ResolverUtil.convertExpression(ex, DataTypeManager.getDataTypeName(agg.getType()), metadata);
+	    			allSymbols.addSymbol(new ExpressionSymbol("stagedAgg", ex)); //$NON-NLS-1$
+	    		}
+			}
+		} else {
+			allSymbols.addSymbols(aggregates);
+		}
+		if (first) {
+			QueryRewriter.makeSelectUnique(allSymbols, false);
+		}
+		projectPlanNode.setProperty(NodeConstants.Info.PROJECT_COLS, allSymbols.getSymbols());
+		projectPlanNode.addGroups(view.getGroups());
+		
+		view.addAsParent(projectPlanNode);
+		
+		if (!viewOnly) {
+			addGroupBy(cc, view, groupingColumns, aggregates, metadata, projectPlanNode.getParent());
+		}
+		
+		if (planNode.getType() == NodeConstants.Types.ACCESS) {
+			//TODO: temporarily remove the access node so that the inline view could be removed if possible 
+		    while (RuleRaiseAccess.raiseAccessNode(planNode, planNode, metadata, capFinder, true, null) != null) {
+				//continue to raise
+			}
+		}
+	}
+	
+	private void updateSymbolName(List<SingleElementSymbol> projectCols, int i,
+			ElementSymbol virtualElem, SingleElementSymbol projectedSymbol) {
+		if (projectedSymbol instanceof AliasSymbol) {
+			((AliasSymbol)projectedSymbol).setShortName(virtualElem.getShortCanonicalName());
+		} else {
+			projectCols.set(i, new AliasSymbol(virtualElem.getShortCanonicalName(), projectedSymbol));
+		}
+	}
+
 	private boolean canPushGroupByToUnionChild(QueryMetadataInterface metadata,
 			CapabilitiesFinder capFinder,
-			List<SingleElementSymbol> groupingExpressions,
-			LinkedHashSet<AggregateSymbol> aggregates, PlanNode planNode)
+			List<Expression> groupingExpressions,
+			LinkedHashSet<AggregateSymbol> aggregates, PlanNode planNode, AnalysisRecord record)
 			throws QueryMetadataException, TeiidComponentException {
 		if (planNode.getType() != NodeConstants.Types.ACCESS) {
 			return false;
@@ -329,13 +479,21 @@
 			return false;
 		}
 		for (AggregateSymbol aggregate : aggregates) {
-			if (!CapabilitiesUtil.supportsAggregateFunction(modelId, aggregate, metadata, capFinder)) {
+			if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(aggregate, modelId, metadata, capFinder, record)) {
+	            return false;
+	        }
+		}
+		if (groupingExpressions.isEmpty()) {
+			if (!CapabilitiesUtil.supports(Capability.QUERY_AGGREGATES_COUNT_STAR, modelId, metadata, capFinder)) {
 				return false;
 			}
+		} else {
+			for (Expression ses : groupingExpressions) {
+				if(! CriteriaCapabilityValidatorVisitor.canPushLanguageObject(ses, modelId, metadata, capFinder, record)) {
+		            return false;
+		        }
+			}
 		}
-		if ((groupingExpressions == null || groupingExpressions.isEmpty()) && !CapabilitiesUtil.supports(Capability.QUERY_AGGREGATES_COUNT_STAR, modelId, metadata, capFinder)) {
-			return false;
-		}
 		//TODO: check to see if we are distinct
 		return true;
 	}
@@ -365,107 +523,7 @@
 		return null;
 	}
     
-	public void addView(PlanNode root, PlanNode unionSource, boolean pushdown, List<SingleElementSymbol> groupingExpressions,
-			Set<AggregateSymbol> aggregates, List<ElementSymbol> virtualElements,
-			QueryMetadataInterface metadata, CapabilitiesFinder capFinder)
-			throws TeiidComponentException, QueryPlannerException, QueryResolverException {
-		PlanNode originalNode = unionSource;
-		//branches other than the first need to have their projected column names updated
-		PlanNode sortNode = NodeEditor.findNodePreOrder(unionSource, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
-		List<SingleElementSymbol> sortOrder = null;
-		OrderBy orderBy = null;
-		if (sortNode != null) {
-			orderBy = (OrderBy)sortNode.getProperty(Info.SORT_ORDER);
-			sortOrder = orderBy.getSortKeys();
-		}
-		List<SingleElementSymbol> projectCols = FrameUtil.findTopCols(unionSource);
-		for (int i = 0; i < virtualElements.size(); i++) {
-			ElementSymbol virtualElem = virtualElements.get(i);
-			SingleElementSymbol projectedSymbol = projectCols.get(i);
-			if (!projectedSymbol.getShortCanonicalName().equals(virtualElem.getShortCanonicalName())) {
-				if (sortOrder != null) {
-					int sortIndex = sortOrder.indexOf(projectedSymbol);
-					if (sortIndex > -1) {
-						updateSymbolName(sortOrder, sortIndex, virtualElem, sortOrder.get(sortIndex));
-						orderBy.getOrderByItems().get(sortIndex).setSymbol(sortOrder.get(sortIndex));
-					}
-				}
-				updateSymbolName(projectCols, i, virtualElem, projectedSymbol);
-			}
-		}
-		GroupSymbol group = new GroupSymbol("X"); //$NON-NLS-1$
-        
-		PlanNode intermediateView = createView(group, virtualElements, unionSource, metadata);
-    	SymbolMap symbolMap = (SymbolMap)intermediateView.getProperty(Info.SYMBOL_MAP);
-    	unionSource = intermediateView;
-    	
-        Set<SingleElementSymbol> newGroupingExpressions = Collections.emptySet();
-        if (groupingExpressions != null) {
-        	newGroupingExpressions = new HashSet<SingleElementSymbol>();
-        	for (SingleElementSymbol singleElementSymbol : groupingExpressions) {
-				newGroupingExpressions.add((SingleElementSymbol)symbolMap.getKeys().get(virtualElements.indexOf(singleElementSymbol)).clone());
-			}
-        }
-
-        List<SingleElementSymbol> projectedViewSymbols = Util.deepClone(symbolMap.getKeys(), SingleElementSymbol.class);
-
-        PlanNode parent = NodeEditor.findParent(unionSource, NodeConstants.Types.SOURCE);
-        SymbolMap parentMap = (SymbolMap) parent.getProperty(NodeConstants.Info.SYMBOL_MAP);
-        SymbolMap viewMapping = SymbolMap.createSymbolMap(parentMap.getKeys(), projectedViewSymbols);
-        for (AggregateSymbol agg : aggregates) {
-        	agg = (AggregateSymbol)agg.clone();
-        	ExpressionMappingVisitor.mapExpressions(agg, viewMapping.asMap());
-        	if (pushdown) {
-        		projectedViewSymbols.add(agg);
-        	} else {
-        		if (agg.getAggregateFunction() == Type.COUNT) {
-        			if (agg.getExpression() == null) {
-	    				projectedViewSymbols.add(new ExpressionSymbol("stagedAgg", new Constant(1))); //$NON-NLS-1$
-        			} else { 
-	        			SearchedCaseExpression count = new SearchedCaseExpression(Arrays.asList(new IsNullCriteria(agg.getExpression())), Arrays.asList(new Constant(Integer.valueOf(0))));
-	        			count.setElseExpression(new Constant(Integer.valueOf(1)));
-	        			count.setType(DataTypeManager.DefaultDataClasses.INTEGER);
-	    				projectedViewSymbols.add(new ExpressionSymbol("stagedAgg", count)); //$NON-NLS-1$
-        			}
-        		} else { //min, max, sum
-        			Expression ex = agg.getExpression();
-        			ex = ResolverUtil.convertExpression(ex, DataTypeManager.getDataTypeName(agg.getType()), metadata);
-        			projectedViewSymbols.add(new ExpressionSymbol("stagedAgg", ex)); //$NON-NLS-1$
-        		}
-        	}
-		}
-
-        if (pushdown) {
-        	unionSource = addGroupBy(unionSource, newGroupingExpressions, new LinkedList<AggregateSymbol>());
-        }
-        
-        PlanNode projectPlanNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);
-        unionSource.addAsParent(projectPlanNode);
-        unionSource = projectPlanNode;
-
-        //create proper names for the aggregate symbols
-        Select select = new Select(projectedViewSymbols);
-        QueryRewriter.makeSelectUnique(select, false);
-        projectedViewSymbols = select.getProjectedSymbols();
-        projectPlanNode.setProperty(NodeConstants.Info.PROJECT_COLS, projectedViewSymbols);
-        projectPlanNode.addGroup(group);
-        if (pushdown) {
-        	while (RuleRaiseAccess.raiseAccessNode(root, originalNode, metadata, capFinder, true, null) != null) {
-        		//continue to raise
-        	}
-        }
-    }
-	
-	static PlanNode createView(GroupSymbol group, List<? extends SingleElementSymbol> virtualElements, PlanNode child, QueryMetadataInterface metadata) throws TeiidComponentException {
-		PlanNode intermediateView = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);
-    	SymbolMap symbolMap = createSymbolMap(group, virtualElements, child, metadata);
-    	intermediateView.setProperty(NodeConstants.Info.SYMBOL_MAP, symbolMap);
-    	child.addAsParent(intermediateView);
-    	intermediateView.addGroup(group);
-    	return intermediateView;
-	}
-
-	private static SymbolMap createSymbolMap(GroupSymbol group,
+	static SymbolMap createSymbolMap(GroupSymbol group,
 			List<? extends SingleElementSymbol> virtualElements,
 			PlanNode child, QueryMetadataInterface metadata)
 			throws TeiidComponentException, QueryMetadataException {
@@ -482,15 +540,6 @@
 		return symbolMap;
 	}
 
-	private void updateSymbolName(List<SingleElementSymbol> projectCols, int i,
-			ElementSymbol virtualElem, SingleElementSymbol projectedSymbol) {
-		if (projectedSymbol instanceof AliasSymbol) {
-			((AliasSymbol)projectedSymbol).setShortName(virtualElem.getShortCanonicalName());
-		} else {
-			projectCols.set(i, new AliasSymbol(virtualElem.getShortCanonicalName(), projectedSymbol));
-		}
-	}
-
     /**
      * Walk up the plan from the GROUP node. Should encounter only (optionally) a SELECT and can stop at the PROJECT node. Need to
      * collect any AggregateSymbols used in the select criteria or projected columns.
@@ -502,23 +551,34 @@
     static LinkedHashSet<AggregateSymbol> collectAggregates(PlanNode groupNode) {
     	LinkedHashSet<AggregateSymbol> aggregates = new LinkedHashSet<AggregateSymbol>();
         PlanNode currentNode = groupNode.getParent();
+        SymbolMap symbolMap = (SymbolMap) groupNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
+        
         while (currentNode != null) {
             if (currentNode.getType() == NodeConstants.Types.PROJECT) {
                 List<SingleElementSymbol> projectedSymbols = (List<SingleElementSymbol>)currentNode.getProperty(NodeConstants.Info.PROJECT_COLS);
                 for (SingleElementSymbol symbol : projectedSymbols) {
-                    aggregates.addAll(AggregateSymbolCollectorVisitor.getAggregates(symbol, true));
+                    mapAggregates(ElementCollectorVisitor.getAggregates(symbol, true), symbolMap, aggregates);
                 }
                 break;
             }
             if (currentNode.getType() == NodeConstants.Types.SELECT) {
                 Criteria crit = (Criteria)currentNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
-                aggregates.addAll(AggregateSymbolCollectorVisitor.getAggregates(crit, true));
+                mapAggregates(ElementCollectorVisitor.getAggregates(crit, true), symbolMap, aggregates);
             }
 
             currentNode = currentNode.getParent();
         }
         return aggregates;
     }
+    
+    static void mapAggregates(Collection<ElementSymbol> symbols, SymbolMap map, Collection<? super AggregateSymbol> aggs) {
+    	for (ElementSymbol es : symbols) {
+			Expression ex = map.getMappedExpression(es);
+			if (ex instanceof AggregateSymbol) {
+				aggs.add((AggregateSymbol) ex);
+			}
+		}
+    }
 
     /**
      * Attempt to push the group node below one or more joins, manipulating the parent plan as necessary. This may involve
@@ -528,33 +588,39 @@
      * @since 4.2
      */
     private void pushGroupNode(PlanNode groupNode,
-                               List<SingleElementSymbol> groupingExpressions,
+                               List<Expression> groupingExpressions,
                                Set<AggregateSymbol> allAggregates,
                                QueryMetadataInterface metadata,
-                               CapabilitiesFinder capFinder) throws TeiidComponentException,
+                               CapabilitiesFinder capFinder, CommandContext cc) throws TeiidComponentException,
                                                             QueryMetadataException, QueryPlannerException {
 
         Map<PlanNode, List<AggregateSymbol>> aggregateMap = createNodeMapping(groupNode, allAggregates, true);
         if (aggregateMap == null) {
         	return;
         }
-        Map<PlanNode, List<SingleElementSymbol>> groupingMap = createNodeMapping(groupNode, groupingExpressions, false);
+        Map<PlanNode, List<Expression>> groupingMap = createNodeMapping(groupNode, groupingExpressions, false);
 
-        Set<PlanNode> possibleTargetNodes = new HashSet<PlanNode>(aggregateMap.keySet());
+        Set<PlanNode> possibleTargetNodes = new LinkedHashSet<PlanNode>(aggregateMap.keySet());
         possibleTargetNodes.addAll(groupingMap.keySet());
-
+        for (Map.Entry<PlanNode, List<AggregateSymbol>> entry : aggregateMap.entrySet()) {
+    		if (AggregateSymbol.areAggregatesCardinalityDependent(entry.getValue())) {
+        		//can't change the cardinality on the other side of the join - 
+    			//unless it's a 1-1 join, in which case this optimization isn't needed
+    			//TODO: make a better choice if there are multiple targets
+    			possibleTargetNodes.clear();
+    			possibleTargetNodes.add(entry.getKey());
+    			break;
+        	}        		
+    	}
         for (PlanNode planNode : possibleTargetNodes) {
-            Set<SingleElementSymbol> stagedGroupingSymbols = new LinkedHashSet<SingleElementSymbol>();
-            List<AggregateSymbol> aggregates = aggregateMap.get(planNode);
-            List<SingleElementSymbol> groupBy = groupingMap.get(planNode);
+            Set<Expression> stagedGroupingSymbols = new LinkedHashSet<Expression>();
+            Collection<AggregateSymbol> aggregates = aggregateMap.get(planNode);
 
             if (!canPush(groupNode, stagedGroupingSymbols, planNode)) {
                 continue;
             }
 
-            if (groupBy != null) {
-                stagedGroupingSymbols.addAll(groupBy);
-            }
+        	filterJoinColumns(stagedGroupingSymbols, planNode.getGroups(), groupingExpressions);
 
             collectSymbolsFromOtherAggregates(allAggregates, aggregates, planNode, stagedGroupingSymbols);
             
@@ -566,7 +632,7 @@
         	}
             
             if (aggregates != null) {
-                stageAggregates(groupNode, metadata, stagedGroupingSymbols, aggregates);
+                aggregates = stageAggregates(groupNode, metadata, stagedGroupingSymbols, aggregates, cc);
             } else {
                 aggregates = new ArrayList<AggregateSymbol>(1);
             }
@@ -576,12 +642,15 @@
             }
             //TODO: if aggregates is empty, then could insert a dup remove node instead
             
-            PlanNode stageGroup = addGroupBy(planNode, stagedGroupingSymbols, aggregates);
-    		
+            PlanNode stageGroup = addGroupBy(cc, planNode, new ArrayList<Expression>(stagedGroupingSymbols), aggregates, metadata, groupNode.getParent());
+			
             //check for push down
-            if (stageGroup.getFirstChild().getType() == NodeConstants.Types.ACCESS 
-                            && RuleRaiseAccess.canRaiseOverGroupBy(stageGroup, stageGroup.getFirstChild(), aggregates, metadata, capFinder, null)) {
-                RuleRaiseAccess.performRaise(null, stageGroup.getFirstChild(), stageGroup);
+            PlanNode accessNode = stageGroup.getFirstChild();
+			if (accessNode.getType() == NodeConstants.Types.ACCESS 
+                            && RuleRaiseAccess.canRaiseOverGroupBy(stageGroup, accessNode, aggregates, metadata, capFinder, null)) {
+            	accessNode.getGroups().clear();
+            	accessNode.getGroups().addAll(stageGroup.getGroups());
+                RuleRaiseAccess.performRaise(null, accessNode, stageGroup);
                 if (stagedGroupingSymbols.isEmpty()) {
                     RuleRaiseAccess.performRaise(null, stageGroup.getParent(), stageGroup.getParent().getParent());
                 }
@@ -589,16 +658,14 @@
         }
     }
 
-	private PlanNode addGroupBy(PlanNode planNode,
-			Collection<SingleElementSymbol> stagedGroupingSymbols,
-			Collection<AggregateSymbol> aggregates) {
+	private PlanNode addGroupBy(CommandContext cc,
+			PlanNode child, List<Expression> stagedGroupingSymbols,
+			Collection<AggregateSymbol> aggregates, QueryMetadataInterface metadata, PlanNode endNode) throws QueryMetadataException,
+			TeiidComponentException, QueryPlannerException {
 		PlanNode stageGroup = NodeFactory.getNewNode(NodeConstants.Types.GROUP);
-		planNode.addAsParent(stageGroup);
-
-		if (!stagedGroupingSymbols.isEmpty()) {
-		    stageGroup.setProperty(NodeConstants.Info.GROUP_COLS, new ArrayList<SingleElementSymbol>(stagedGroupingSymbols));
-		    stageGroup.addGroups(GroupsUsedByElementsVisitor.getGroups(stagedGroupingSymbols));
-		} else {
+		child.addAsParent(stageGroup);
+		aggregates = new LinkedHashSet<AggregateSymbol>(aggregates);
+		if (stagedGroupingSymbols.isEmpty()) {
 		    // if the source has no rows we need to insert a select node with criteria count(*)>0
 		    PlanNode selectNode = NodeFactory.getNewNode(NodeConstants.Types.SELECT);
 		    AggregateSymbol count = new AggregateSymbol("stagedAgg", NonReserved.COUNT, false, null); //$NON-NLS-1$
@@ -608,48 +675,60 @@
 		    selectNode.setProperty(NodeConstants.Info.IS_HAVING, Boolean.TRUE);
 		    stageGroup.addAsParent(selectNode);
 		}
+		
+		Map<Expression, ElementSymbol> reverseMapping = RelationalPlanner.buildGroupingNode(aggregates, stagedGroupingSymbols, stageGroup, cc, idGenerator).inserseMapping();
+		GroupSymbol newGroup = reverseMapping.values().iterator().next().getGroupSymbol();
+		PlanNode node = stageGroup.getParent();
+		while (node != endNode) {
+			if (node.getType() == NodeConstants.Types.JOIN) {
+				node.getGroups().removeAll(FrameUtil.findJoinSourceNode(stageGroup.getFirstChild()).getGroups());
+				node.getGroups().add(newGroup);
+			}
+			FrameUtil.convertNode(node, null, null, reverseMapping, metadata, false);
+			if (node.getType() == NodeConstants.Types.JOIN) {
+				//reset the left/right/non-equi join criteria
+				RuleChooseJoinStrategy.chooseJoinStrategy(node, metadata);
+			}
+			node = node.getParent();
+		}
 		return stageGroup;
 	}
 
-    static void stageAggregates(PlanNode groupNode,
+    Set<AggregateSymbol> stageAggregates(PlanNode groupNode,
                                  QueryMetadataInterface metadata,
-                                 Collection<SingleElementSymbol> stagedGroupingSymbols,
-                                 Collection<AggregateSymbol> aggregates) throws TeiidComponentException, QueryPlannerException {
+                                 Set<Expression> stagedGroupingSymbols,
+                                 Collection<AggregateSymbol> aggregates, CommandContext context) throws TeiidComponentException, QueryPlannerException {
         //remove any aggregates that are computed over a group by column
-        Set<Expression> expressions = new HashSet<Expression>();
-        for (SingleElementSymbol expression : stagedGroupingSymbols) {
-            expressions.add(SymbolMap.getExpression(expression));
-        }
-        
         for (final Iterator<AggregateSymbol> iterator = aggregates.iterator(); iterator.hasNext();) {
             final AggregateSymbol symbol = iterator.next();
             Expression expr = symbol.getExpression();
             if (expr == null) {
                 continue;
             }
-            if (expressions.contains(expr)) {
+            if (stagedGroupingSymbols.contains(expr)) {
                 iterator.remove();
             }
         } 
         
-        if (!aggregates.isEmpty()) {
-            // Fix any aggregate expressions so they correctly recombine the staged aggregates
-            try {
-                Set<AggregateSymbol> newAggs = new HashSet<AggregateSymbol>();
-                Map<AggregateSymbol, Expression> aggMap = buildAggregateMap(aggregates, metadata, newAggs);
-                mapExpressions(groupNode.getParent(), aggMap, metadata);
-                aggregates.clear();
-                aggregates.addAll(newAggs);
-            } catch (QueryResolverException err) {
-                throw new TeiidComponentException(err);
-            }
-        } 
+        if (aggregates.isEmpty()) {
+        	return Collections.emptySet();
+        }
+        // Fix any aggregate expressions so they correctly recombine the staged aggregates
+        Set<AggregateSymbol> newAggs = new HashSet<AggregateSymbol>();
+        Map<AggregateSymbol, Expression> aggMap;
+		try {
+			aggMap = buildAggregateMap(aggregates, metadata, newAggs);
+		} catch (QueryResolverException e) {
+			throw new QueryPlannerException(e, e.getMessage());
+		}
+        updateParentAggs(groupNode, context, aggMap, metadata);
+        return newAggs;
     }
     
     private void collectSymbolsFromOtherAggregates(Collection<AggregateSymbol> allAggregates,
                                                       Collection<AggregateSymbol> aggregates,
                                                       PlanNode current,
-                                                      Set<SingleElementSymbol> stagedGroupingSymbols) {
+                                                      Set<Expression> stagedGroupingSymbols) {
         Set<AggregateSymbol> otherAggs = new HashSet<AggregateSymbol>(allAggregates);
         if (aggregates != null) {
             otherAggs.removeAll(aggregates);
@@ -670,7 +749,7 @@
      * Ensures that we are only pushing through inner equi joins or cross joins.  Also collects the necessary staged grouping symbols
      */
     private boolean canPush(PlanNode groupNode,
-                            Set<SingleElementSymbol> stagedGroupingSymbols,
+                            Set<Expression> stagedGroupingSymbols,
                             PlanNode planNode) {
         PlanNode parentJoin = planNode.getParent();
         
@@ -684,12 +763,12 @@
             }
 
             if (planNode == parentJoin.getFirstChild()) {
-                if (parentJoin.hasCollectionProperty(NodeConstants.Info.LEFT_EXPRESSIONS) && !filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS))) {
-                    return false;
+                if (parentJoin.hasCollectionProperty(NodeConstants.Info.LEFT_EXPRESSIONS)) {
+                	filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.LEFT_EXPRESSIONS));
                 }
             } else {
-                if (parentJoin.hasCollectionProperty(NodeConstants.Info.RIGHT_EXPRESSIONS) && !filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS))) {
-                    return false;
+                if (parentJoin.hasCollectionProperty(NodeConstants.Info.RIGHT_EXPRESSIONS)) {
+                	filterJoinColumns(stagedGroupingSymbols, groups, (List<SingleElementSymbol>)parentJoin.getProperty(NodeConstants.Info.RIGHT_EXPRESSIONS));
                 }
             }
 
@@ -699,23 +778,19 @@
         return true;
     }
 
-    private boolean filterJoinColumns(Set<SingleElementSymbol> stagedGroupingSymbols,
+    private void filterJoinColumns(Set<Expression> stagedGroupingSymbols,
                                    Set<GroupSymbol> groups,
-                                   List<SingleElementSymbol> symbols) {
-        for (SingleElementSymbol singleElementSymbol : symbols) {
-            if (!(singleElementSymbol instanceof ElementSymbol)) {
-                return false;
+                                   List<? extends Expression> symbols) {
+        for (Expression ex : symbols) {
+            if (groups.containsAll(GroupsUsedByElementsVisitor.getGroups(ex))) {
+                stagedGroupingSymbols.add(SymbolMap.getExpression(ex));
             }
-            if (groups.contains(((ElementSymbol)singleElementSymbol).getGroupSymbol())) {
-                stagedGroupingSymbols.add(singleElementSymbol);
-            }
         }
-        return true;
     }
 
-    private <T extends SingleElementSymbol> Map<PlanNode, List<T>> createNodeMapping(PlanNode groupNode,
+    private <T extends Expression> Map<PlanNode, List<T>> createNodeMapping(PlanNode groupNode,
                                                                        Collection<T> expressions, boolean aggs) {
-        Map<PlanNode, List<T>> result = new HashMap<PlanNode, List<T>>();
+        Map<PlanNode, List<T>> result = new LinkedHashMap<PlanNode, List<T>>();
         if (expressions == null) {
             return result;
         }
@@ -723,11 +798,14 @@
         	if (aggs && ((AggregateSymbol)aggregateSymbol).getExpression() == null) {
         		return null; //count(*) is not yet handled.  a general approach would be count(*) => count(r.col) * count(l.col), but the logic here assumes a simpler initial mapping
         	}
+        	if (aggs && !((AggregateSymbol)aggregateSymbol).canStage()) {
+        		continue;
+        	}
             Set<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(aggregateSymbol);
             if (groups.isEmpty()) {
             	continue;
             }
-            PlanNode originatingNode = FrameUtil.findOriginatingNode(groupNode, groups);
+            PlanNode originatingNode = FrameUtil.findOriginatingNode(groupNode.getFirstChild(), groups);
             if (originatingNode == null) {
             	if (aggs) {
             		return null;  //should never happen
@@ -753,6 +831,10 @@
                 continue;
             }
             
+            if (originatingNode.getType() != NodeConstants.Types.ACCESS) {
+            	continue; //don't perform intermediate grouping
+            }
+            
             if (aggs && ((AggregateSymbol)aggregateSymbol).isDistinct()) {
             	//TODO: support distinct
             	continue;
@@ -771,7 +853,7 @@
     private static Map<AggregateSymbol, Expression> buildAggregateMap(Collection<? extends SingleElementSymbol> aggregateExpressions,
                                                                         QueryMetadataInterface metadata, Set<AggregateSymbol> nestedAggregates) throws QueryResolverException,
                                                                                                         TeiidComponentException {
-        Map<AggregateSymbol, Expression> aggMap = new HashMap<AggregateSymbol, Expression>();
+        Map<AggregateSymbol, Expression> aggMap = new LinkedHashMap<AggregateSymbol, Expression>();
         for (SingleElementSymbol symbol : aggregateExpressions) {
             AggregateSymbol partitionAgg = (AggregateSymbol)symbol;
            
@@ -781,7 +863,6 @@
             if (aggFunction == Type.COUNT) {
                 //COUNT(x) -> CONVERT(SUM(COUNT(x)), INTEGER)
                 AggregateSymbol newAgg = new AggregateSymbol("stagedAgg", NonReserved.SUM, false, partitionAgg); //$NON-NLS-1$
-
                 // Build conversion function to convert SUM (which returns LONG) back to INTEGER
                 Function convertFunc = new Function(FunctionLibrary.CONVERT, new Expression[] {newAgg, new Constant(DataTypeManager.getDataTypeName(partitionAgg.getType()))});
                 ResolverVisitor.resolveLanguageObject(convertFunc, metadata);
@@ -843,10 +924,7 @@
                 nestedAggregates.add(countAgg);
                 nestedAggregates.add(sumAgg);
                 nestedAggregates.add(sumSqAgg);
-            } else if (aggFunction == Type.TEXTAGG) {
-            	continue;
-            }
-            else {
+            } else {
                 //AGG(X) -> AGG(AGG(X))
                 newExpression = new AggregateSymbol("stagedAgg", aggFunction.name(), false, partitionAgg); //$NON-NLS-1$
                 nestedAggregates.add(partitionAgg);
@@ -857,22 +935,6 @@
         return aggMap;
     }
     
-    static void mapExpressions(PlanNode node, Map<? extends Expression, ? extends Expression> exprMap, QueryMetadataInterface metadata) 
-    throws QueryPlannerException {
-        
-        while (node != null) {
-            FrameUtil.convertNode(node, null, null, exprMap, metadata, true);
-            
-            switch (node.getType()) {
-                case NodeConstants.Types.SOURCE:
-                case NodeConstants.Types.GROUP:
-                    return;
-            }
-
-            node = node.getParent();
-        }
-    }
-
     /**
      * @see java.lang.Object#toString()
      * @since 4.2

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushLimit.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushLimit.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushLimit.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -51,6 +51,7 @@
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.Function;
+import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.visitor.EvaluatableVisitor;
 import org.teiid.query.util.CommandContext;
@@ -168,6 +169,13 @@
             }
             case NodeConstants.Types.SOURCE:
             {
+                GroupSymbol virtualGroup = child.getGroups().iterator().next();
+                if (virtualGroup.isProcedure()) {
+                        return false;
+                }
+                if (FrameUtil.isProcedure(child.getFirstChild())) {
+                    return false;
+                }
                 return true;
             }
             default:

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushSelectCriteria.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushSelectCriteria.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RulePushSelectCriteria.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,6 +43,7 @@
 import org.teiid.query.optimizer.relational.plantree.NodeEditor;
 import org.teiid.query.optimizer.relational.plantree.NodeFactory;
 import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants.Info;
 import org.teiid.query.resolver.util.AccessPattern;
 import org.teiid.query.sql.lang.CompoundCriteria;
 import org.teiid.query.sql.lang.Criteria;
@@ -51,6 +52,7 @@
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
@@ -113,7 +115,7 @@
 	            
                 boolean moved = false;
                 
-                if((critNode.getGroups().isEmpty() && critNode.getSubqueryContainers().isEmpty()) || !atBoundary(critNode, sourceNode)) {
+                if(critNode.hasBooleanProperty(Info.IS_PUSHED) || (critNode.getGroups().isEmpty() && critNode.getSubqueryContainers().isEmpty()) || !atBoundary(critNode, sourceNode)) {
                     deadNodes.add(critNode);
                     continue;
                 }
@@ -132,6 +134,16 @@
                             break;
         				}
                     }
+                    case NodeConstants.Types.GROUP:
+                    {
+                    	if (!critNode.hasBooleanProperty(NodeConstants.Info.IS_HAVING)) {
+                        	SymbolMap symbolMap = (SymbolMap) sourceNode.getProperty(NodeConstants.Info.SYMBOL_MAP);
+                        	FrameUtil.convertNode(critNode, null, null, symbolMap.asMap(), metadata, true);
+                        	NodeEditor.removeChildNode(critNode.getParent(), critNode);
+                            sourceNode.getFirstChild().addAsParent(critNode);
+                        	moved = true;
+                    	}
+                    }
                 }
                 
                 if (!moved) {
@@ -333,8 +345,6 @@
                 satisfyAccessPatterns(critNode, currentNode);
             } else if (FrameUtil.isOrderedLimit(currentNode)) {
                 return currentNode;
-            } else if (currentNode.getType() == NodeConstants.Types.GROUP && critNode.hasBooleanProperty(NodeConstants.Info.IS_HAVING)) {
-                return currentNode;
             }
 		}
 
@@ -552,17 +562,21 @@
         if(projectNode.getChildCount() == 0) {
             return false;
         }
+        List<WindowFunction> windowFunctions = null;
+        if (projectNode.hasBooleanProperty(Info.HAS_WINDOW_FUNCTIONS)) {
+        	windowFunctions = new LinkedList<WindowFunction>();
+        }
 
         Criteria crit = (Criteria) critNode.getProperty(NodeConstants.Info.SELECT_CRITERIA);
 
-        Boolean conversionResult = checkConversion(symbolMap, ElementCollectorVisitor.getElements(crit, true));
+        Boolean conversionResult = checkConversion(symbolMap, ElementCollectorVisitor.getElements(crit, true), windowFunctions);
         
         if (conversionResult == Boolean.FALSE) {
         	return false; //not convertable
         }
         
         if (!critNode.getSubqueryContainers().isEmpty() 
-        		&& checkConversion(symbolMap, critNode.getCorrelatedReferenceElements()) != null) {
+        		&& checkConversion(symbolMap, critNode.getCorrelatedReferenceElements(), windowFunctions) != null) {
     		return false; //not convertable, or has an aggregate for a correlated reference
         }
         
@@ -583,7 +597,7 @@
     }
 
 	private Boolean checkConversion(SymbolMap symbolMap,
-			Collection<ElementSymbol> elements) {
+			Collection<ElementSymbol> elements, List<WindowFunction> windowFunctions) {
 		Boolean result = null;
         
         for (ElementSymbol element : elements) {
@@ -598,9 +612,16 @@
                 return false;
             }
             
-            if (!AggregateSymbolCollectorVisitor.getAggregates(converted, false).isEmpty()) {
+            if (!ElementCollectorVisitor.getAggregates(converted, false).isEmpty()) {
                 result = Boolean.TRUE;
             }
+            
+            if (windowFunctions != null) {
+            	AggregateSymbolCollectorVisitor.getAggregates(converted, null, null, null, windowFunctions, null);
+            	if (!windowFunctions.isEmpty()) {
+            		return false;
+            	}
+            }
         }
 		return result;
 	}

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseAccess.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -44,6 +44,7 @@
 import org.teiid.query.optimizer.relational.plantree.NodeEditor;
 import org.teiid.query.optimizer.relational.plantree.NodeFactory;
 import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants.Info;
 import org.teiid.query.sql.lang.CompareCriteria;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.lang.JoinType;
@@ -133,6 +134,12 @@
                 if (FrameUtil.isProcedure(parentNode)) {
                 	return null;
                 }
+                
+                PlanNode orderBy = NodeEditor.findParent(parentNode, NodeConstants.Types.SORT, NodeConstants.Types.SOURCE);
+                if (orderBy != null && orderBy.hasBooleanProperty(Info.UNRELATED_SORT) && !canRaiseOverSort(accessNode, metadata, capFinder, orderBy, record, false)) {
+                	//this project node logically has the responsibility of creating the sort keys
+            		return null;
+                }
                                 
                 return performRaise(rootNode, accessNode, parentNode);                
             }
@@ -163,6 +170,8 @@
             {                
                 Set<AggregateSymbol> aggregates = RulePushAggregates.collectAggregates(parentNode);
                 if (canRaiseOverGroupBy(parentNode, accessNode, aggregates, metadata, capFinder, record)) {
+                	accessNode.getGroups().clear();
+                	accessNode.getGroups().addAll(parentNode.getGroups());
                     return performRaise(rootNode, accessNode, parentNode);
                 }
                 return null;
@@ -302,14 +311,14 @@
         if(modelID == null) {
             return false;
         }
-        List<SingleElementSymbol> groupCols = (List<SingleElementSymbol>)groupNode.getProperty(NodeConstants.Info.GROUP_COLS);
+        List<Expression> groupCols = (List<Expression>)groupNode.getProperty(NodeConstants.Info.GROUP_COLS);
         if(!CapabilitiesUtil.supportsAggregates(groupCols, modelID, metadata, capFinder)) {
         	recordDebug("cannot push group by, since group by is not supported by source", groupNode, record); //$NON-NLS-1$
             return false;
         }
         if (groupCols != null) {
-            for (SingleElementSymbol singleElementSymbol : groupCols) {
-                if (!canPushSymbol(singleElementSymbol, false, modelID, metadata, capFinder, record)) {
+            for (Expression expr : groupCols) {
+                if (!canPushSymbol(expr, false, modelID, metadata, capFinder, record)) {
                     return false;
                 }
             }
@@ -344,7 +353,6 @@
         
         List<OrderByItem> sortCols = ((OrderBy)parentNode.getProperty(NodeConstants.Info.SORT_ORDER)).getOrderByItems();
         for (OrderByItem symbol : sortCols) {
-            //TODO: this check shouldn't be necessary, since the order by is not introducing new expressions
             if(! canPushSymbol(symbol.getSymbol(), true, modelID, metadata, capFinder, record)) {
                 return false;
             }
@@ -468,7 +476,7 @@
      * @throws QueryMetadataException
      * @since 4.1.2
      */
-    private static boolean canPushSymbol(SingleElementSymbol symbol, boolean inSelectClause, Object modelID, 
+    private static boolean canPushSymbol(Expression symbol, boolean inSelectClause, Object modelID, 
     		QueryMetadataInterface metadata, CapabilitiesFinder capFinder, AnalysisRecord record) 
     throws TeiidComponentException, QueryMetadataException {
 
@@ -764,15 +772,8 @@
 		newAccess.addGroups(leftAccess.getGroups());
         
         // Combine hints if necessary
-        Object leftHint = leftAccess.getProperty(NodeConstants.Info.MAKE_DEP);
-        if(leftHint != null) {
-            newAccess.setProperty(NodeConstants.Info.MAKE_DEP, leftHint);
-        } else {
-            Object rightHint = rightAccess.getProperty(NodeConstants.Info.MAKE_DEP);
-            if(rightHint != null) {
-                newAccess.setProperty(NodeConstants.Info.MAKE_DEP, rightHint);
-            }    
-        }
+        combineHint(leftAccess, rightAccess, newAccess, NodeConstants.Info.MAKE_DEP);
+        combineHint(leftAccess, rightAccess, newAccess, NodeConstants.Info.MAKE_IND);
         RulePlaceAccess.copyDependentHints(leftAccess, newAccess);
         RulePlaceAccess.copyDependentHints(rightAccess, newAccess);
         RulePlaceAccess.copyDependentHints(joinNode, newAccess);
@@ -786,6 +787,19 @@
         return newAccess;
 	}
 
+	private static void combineHint(PlanNode leftAccess, PlanNode rightAccess,
+			PlanNode newAccess, NodeConstants.Info info) {
+		Object leftHint = leftAccess.getProperty(info);
+        if(leftHint != null) {
+            newAccess.setProperty(info, leftHint);
+        } else {
+            Object rightHint = rightAccess.getProperty(info);
+            if(rightHint != null) {
+                newAccess.setProperty(info, rightHint);
+            }    
+        }
+	}
+
     /**
      * Get modelID for Access node and cache the result in the Access node.
      * @param accessNode Access node

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseNull.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseNull.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/relational/rules/RuleRaiseNull.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -44,6 +44,8 @@
 import org.teiid.query.sql.lang.OrderByItem;
 import org.teiid.query.sql.lang.SetQuery;
 import org.teiid.query.sql.symbol.AliasSymbol;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
@@ -277,7 +279,7 @@
         NodeEditor.removeChildNode(joinNode.getParent(), joinNode);
         
         for (GroupSymbol group : nullNode.getGroups()) {
-            Map nullSymbolMap = FrameUtil.buildSymbolMap(group, null, metadata);
+            Map<ElementSymbol, Expression> nullSymbolMap = FrameUtil.buildSymbolMap(group, null, metadata);
             FrameUtil.convertFrame(frameStart, group, null, nullSymbolMap, metadata);
         }
         

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ContextReplacerVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,7 +41,7 @@
  */
 class ContextReplacerVisitor extends ExpressionMappingVisitor {
     
-    private Collection contextFunctions = new LinkedList(); //contains Function objects
+    private Collection<Function> contextFunctions = new LinkedList<Function>(); //contains Function objects
     
     /**
      * Construct a new visitor
@@ -55,7 +55,7 @@
      * which were stripped out of the language object by this visitor
      * @return Collection of Function
      */
-    Collection getContextFunctions(){
+    Collection<Function> getContextFunctions(){
         return this.contextFunctions;
     }
     
@@ -78,9 +78,9 @@
      * Helper to quickly replace 'context'
      * @param obj Language object
      */
-    static final Collection replaceContextFunctions(LanguageObject obj) {
+    static final Collection<Function> replaceContextFunctions(LanguageObject obj) {
         if (obj == null){
-            return Collections.EMPTY_SET;
+            return Collections.emptySet();
         }
         ContextReplacerVisitor visitor = new ContextReplacerVisitor();
         PreOrderNavigator.doVisit(obj, visitor);

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/CriteriaPlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -37,6 +37,7 @@
 import org.teiid.query.mapping.xml.MappingSourceNode;
 import org.teiid.query.mapping.xml.ResultSetInfo;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.optimizer.relational.rules.JoinUtil;
 import org.teiid.query.sql.lang.CompareCriteria;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.symbol.Constant;
@@ -44,6 +45,7 @@
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
 
 
 public class CriteriaPlanner {
@@ -64,9 +66,9 @@
     static void placeUserCriteria(Criteria criteria, XMLPlannerEnvironment planEnv)
         throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
         
-        for (Iterator conjunctIter = Criteria.separateCriteriaByAnd(criteria).iterator(); conjunctIter.hasNext();) {
+        for (Iterator<Criteria> conjunctIter = Criteria.separateCriteriaByAnd(criteria).iterator(); conjunctIter.hasNext();) {
         
-            Criteria conjunct = (Criteria) conjunctIter.next();
+            Criteria conjunct = conjunctIter.next();
             
             if (planStagingTableCriteria(conjunct, planEnv)) {
                 continue;
@@ -79,11 +81,10 @@
             
             MappingNode context = null;
             
-            Collection contextFunctions = ContextReplacerVisitor.replaceContextFunctions(conjunct);
+            Collection<Function> contextFunctions = ContextReplacerVisitor.replaceContextFunctions(conjunct);
             if (!contextFunctions.isEmpty()) {
                 //ensure that every part of the conjunct is to the same context
-                for (Iterator i = contextFunctions.iterator(); i.hasNext();) {
-                    Function contextFunction = (Function)i.next();
+            	for (Function contextFunction : contextFunctions) {
                     MappingNode otherContext = getContext(planEnv, contextFunction);
                     if (context == null) {
                         context = otherContext;
@@ -102,14 +103,20 @@
                 context = planEnv.mappingDoc;
             }
             
-            Set sourceNodes = collectSourceNodesInConjunct(conjunct, context, planEnv.mappingDoc);
+            Set<MappingSourceNode> sourceNodes = collectSourceNodesInConjunct(conjunct, context, planEnv.mappingDoc);
 
             //TODO: this can be replaced with method on the source node?
             MappingSourceNode criteriaRs = findRootResultSetNode(context, sourceNodes, criteria);
             
+            Collection<GroupSymbol> groups = GroupsUsedByElementsVisitor.getGroups(conjunct);
+            boolean userCritNullDependent = JoinUtil.isNullDependent(planEnv.getGlobalMetadata(), groups, conjunct);
+            ResultSetInfo rs = criteriaRs.getResultSetInfo();
+            if(userCritNullDependent){
+            	rs.setCritNullDependent(true);
+            }
+            
             Criteria convertedCrit = XMLNodeMappingVisitor.convertCriteria(conjunct, planEnv.mappingDoc, planEnv.getGlobalMetadata());
             
-            ResultSetInfo rs = criteriaRs.getResultSetInfo();
             rs.setCriteria(Criteria.combineCriteria(rs.getCriteria(), convertedCrit));
             rs.addToCriteriaResultSets(sourceNodes);
         }
@@ -118,23 +125,21 @@
     /** 
      * This method collects all the MappingSourceNode(s) at or below the context given.
      */
-    private static Set collectSourceNodesInConjunct(Criteria conjunct, MappingNode context, MappingDocument mappingDoc)
+    private static Set<MappingSourceNode> collectSourceNodesInConjunct(Criteria conjunct, MappingNode context, MappingDocument mappingDoc)
         throws QueryPlannerException {
         
-        Collection elements = ElementCollectorVisitor.getElements(conjunct, true);
-        Set resultSets = new HashSet();
+        Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(conjunct, true);
+        Set<MappingSourceNode> resultSets = new HashSet<MappingSourceNode>();
         
         String contextFullName = context.getFullyQualifiedName().toUpperCase();
         
         //validate that each element's group is under the current context or is in the direct parentage
-        for (Iterator i = elements.iterator(); i.hasNext();) {
-            ElementSymbol elementSymbol = (ElementSymbol)i.next();
-            
+        for (ElementSymbol elementSymbol : elements) {
             String elementFullName = elementSymbol.getCanonicalName();
             
             MappingNode node = MappingNode.findNode(mappingDoc, elementFullName);
             
-            MappingNode elementRsNode = node.getSourceNode(); 
+            MappingSourceNode elementRsNode = node.getSourceNode(); 
             if (elementRsNode == null) {
                 throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.invalid_element", elementSymbol)); //$NON-NLS-1$
             }
@@ -158,20 +163,16 @@
         return resultSets;
     }
 
-    private static MappingSourceNode findRootResultSetNode(MappingNode context, Set resultSets, Criteria criteria) 
+    private static MappingSourceNode findRootResultSetNode(MappingNode context, Set<MappingSourceNode> resultSets, Criteria criteria) 
         throws QueryPlannerException {
         
         if (context instanceof MappingSourceNode) {
             return (MappingSourceNode)context;
         }
 
-        Set criteriaResultSets = new HashSet();
+        Set<MappingNode> criteriaResultSets = new HashSet<MappingNode>();
         // if the context node is not the root node then we need to find the root source node from list.
-        for (Iterator i = resultSets.iterator(); i.hasNext();) {
-
-            // these are actually source nodes.
-            MappingNode node = (MappingNode)i.next();
-   
+        for (MappingNode node : resultSets) {
             MappingNode root = node;
             
             while (node != null) {
@@ -288,14 +289,13 @@
     static String getStagingTableForConjunct(Criteria conjunct, QueryMetadataInterface metadata)
         throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
 
-        Collection elements = ElementCollectorVisitor.getElements(conjunct, true);
+        Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(conjunct, true);
 
         boolean first = true;
         String resultSet = null;
         
         // Check each remaining element to make sure it matches
-        for(Iterator elemIter = elements.iterator(); elemIter.hasNext();) {
-            ElementSymbol element = (ElementSymbol) elemIter.next();
+        for (ElementSymbol element : elements) {
             GroupSymbol group = element.getGroupSymbol();
             //assumes that all non-xml group elements are temp elements
             boolean hasTempElement = !metadata.isXMLGroup(group.getMetadataID());
@@ -314,7 +314,7 @@
         }
         
         if (resultSet != null) {
-            Collection functions = ContextReplacerVisitor.replaceContextFunctions(conjunct);
+            Collection<Function> functions = ContextReplacerVisitor.replaceContextFunctions(conjunct);
             if (!functions.isEmpty()) {
                 throw new QueryPlannerException(QueryPlugin.Util.getString("CriteriaPlanner.staging_context")); //$NON-NLS-1$
             }

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/MarkExcludeVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,13 +40,13 @@
 
 
 /** 
- * This vistor marks all the nodes in the Mapping Document to 
+ * This visitor marks all the nodes in the Mapping Document to 
  * "exclude".
  */
 public class MarkExcludeVisitor extends MappingVisitor{
-    HashSet keepNodes;
+    HashSet<String> keepNodes;
     
-    public MarkExcludeVisitor(HashSet keppNodes) {
+    public MarkExcludeVisitor(HashSet<String> keppNodes) {
         this.keepNodes = keppNodes;
     }
 
@@ -132,7 +132,7 @@
         }
     }
         
-    public static MappingDocument markExcludedNodes(MappingDocument doc, HashSet keepNodes) {
+    public static MappingDocument markExcludedNodes(MappingDocument doc, HashSet<String> keepNodes) {
         MarkExcludeVisitor visitor = new MarkExcludeVisitor(keepNodes);
         doc.acceptVisitor(new Navigator(true, visitor));
         return doc;

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/NameInSourceResolverVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -61,12 +61,12 @@
         
         Map symbols = element.getSymbolMap();
         
-        List elements = new LinkedList();
+        List<ElementSymbol> elements = new LinkedList<ElementSymbol>();
         
         for (Iterator i = symbols.values().iterator(); i.hasNext();) {
             Object symbol = i.next();
             if (symbol instanceof ElementSymbol) {
-                elements.add(symbol);
+                elements.add((ElementSymbol)symbol);
             }
         }
         

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/QueryUtil.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/QueryUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/QueryUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -51,10 +51,10 @@
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.Select;
 import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
 import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
@@ -135,7 +135,7 @@
     
     static Query wrapQuery(FromClause fromClause, String groupName) {
         Select select = new Select();
-        select.addSymbol(new AllInGroupSymbol(groupName + ".*")); //$NON-NLS-1$
+        select.addSymbol(new MultipleElementSymbol(groupName));
         Query query = new Query();
         query.setSelect(select);
         From from = new From();

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/SourceNodePlannerVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -122,11 +122,12 @@
                         
             MappingSourceNode parent = sourceNode.getParentSourceNode();
             Collection<ElementSymbol> bindings = QueryUtil.getBindingElements(modifiedNode);
+            rsInfo.setInputSet(!bindings.isEmpty());
             // root source nodes do not have any inputset criteria on them; so there is no use in
             // going through the raising the criteria.
             // if the original query is not a select.. we are out of luck. we can expand on this later
-            // versions. make ure bindings are only to parent.
-            if (parent == null || !canRaiseInputset(command, bindings) || !areBindingsOnlyToNode(modifiedNode, parent)) {
+            // versions. make sure bindings are only to parent.
+            if (!rsInfo.hasInputSet() || !canRaiseInputset(command, bindings) || !areBindingsOnlyToNode(modifiedNode, parent)) {
                 return;
             }
             
@@ -152,6 +153,10 @@
                 }
             }
             
+            if (inputSetCriteria == null) {
+            	return;
+            }
+            
             // Keep the criteria which is not reference based.
             transformationQuery.setCriteria(nonInputsetCriteria);
 
@@ -229,7 +234,7 @@
         throws QueryMetadataException, TeiidComponentException, QueryPlannerException {
         
         // get elements in the old group
-        List elements = ResolverUtil.resolveElementsInGroup(oldSymbol, planEnv.getGlobalMetadata());
+        List<ElementSymbol> elements = ResolverUtil.resolveElementsInGroup(oldSymbol, planEnv.getGlobalMetadata());
         
         TempMetadataStore store = planEnv.getGlobalMetadata().getMetadataStore();
         
@@ -280,7 +285,7 @@
         }
     }
     
-    private boolean canRaiseInputset(Command command, Collection<ElementSymbol> bindings) throws TeiidComponentException {
+    private boolean canRaiseInputset(Command command, Collection<ElementSymbol> bindings) {
         // check to see if this is query.
         if (!(command instanceof Query)) {
             return false;
@@ -311,14 +316,13 @@
      * @param criteria - criteria on which the elements need to modified
      * @return true if converted; false otherwise
      */
-    private boolean convertCriteria(GroupSymbol newGroupSymbol, Query transformationQuery, Criteria criteria, TempMetadataAdapter metadata, Map symbolMap) 
-        throws QueryMetadataException, TeiidComponentException {
+    private boolean convertCriteria(GroupSymbol newGroupSymbol, Query transformationQuery, Criteria criteria, TempMetadataAdapter metadata, Map symbolMap) {
         
         String groupName = newGroupSymbol.getName();
         Collection<ElementSymbol> elementsInCriteria = ElementCollectorVisitor.getElements(criteria, true);
-        Map mappedElements = new HashMap();
+        Map<ElementSymbol, ElementSymbol> mappedElements = new HashMap<ElementSymbol, ElementSymbol>();
 
-        List projectedSymbols = transformationQuery.getProjectedSymbols();
+        List<SingleElementSymbol> projectedSymbols = transformationQuery.getProjectedSymbols();
         
         boolean addedProjectedSymbol = false;
         
@@ -383,10 +387,8 @@
      * If the element has alias wrapping, then return the matching alias element.
      * @return matched alias symbol; null otherwise.
      */
-    private AliasSymbol getMachingAlias(List elementsInGroup, ElementSymbol symbol) {
-        
-        for(Iterator i = elementsInGroup.iterator(); i.hasNext();) {
-            final SingleElementSymbol element = (SingleElementSymbol)i.next();
+    private AliasSymbol getMachingAlias(List<SingleElementSymbol> elementsInGroup, ElementSymbol symbol) {
+    	for (SingleElementSymbol element : elementsInGroup) {
             if (element instanceof AliasSymbol) {
                 AliasSymbol alias = (AliasSymbol)element;
                 if (alias.getSymbol().equals(symbol)) {
@@ -421,14 +423,14 @@
                  */
                 @Override
                 protected void walkChildNodes(MappingNode element) {
-                    List children = new ArrayList(element.getNodeChildren());
-                    for(Iterator i=children.iterator(); i.hasNext();) {
+                    List<MappingNode> children = new ArrayList<MappingNode>(element.getNodeChildren());
+                    for(Iterator<MappingNode> i=children.iterator(); i.hasNext();) {
                         
                         if (shouldAbort()) {
                             break;
                         }
                         
-                        MappingNode node = (MappingNode)i.next();            
+                        MappingNode node = i.next();            
                         node.acceptVisitor(this);
                     }
                 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/ValidateMappedCriteriaVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,10 +22,6 @@
 
 package org.teiid.query.optimizer.xml;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
 import java.util.Map;
 
 import org.teiid.api.exception.query.QueryMetadataException;
@@ -40,8 +36,6 @@
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.util.ResolverVisitor;
 import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
 import org.teiid.query.sql.visitor.StaticSymbolMappingVisitor;
 
 
@@ -60,9 +54,7 @@
         Map symbolMap = element.getSourceNode().buildFullSymbolMap();
         Criteria criteria = resolveCriteria(criteriaStr, symbolMap);
         if (criteria != null) {
-            List groupNames = getCriteriaGroups(criteria);
             element.setCriteriaNode(criteria);
-            element.setGroupsInCriteria(groupNames);
         }
     }
 
@@ -71,9 +63,7 @@
         Map symbolMap = element.getSourceNode().buildFullSymbolMap();
         Criteria criteria = resolveCriteria(criteriaStr, symbolMap);
         if (criteria != null) {
-            List groupNames = getCriteriaGroups(criteria);
             element.setCriteriaNode(criteria);
-            element.setGroupsInCriteria(groupNames);
         }
     }
 
@@ -91,17 +81,6 @@
         return null;
     }
     
-    private static List getCriteriaGroups(Criteria criteria) {
-        Collection criteriaGroups = GroupsUsedByElementsVisitor.getGroups(criteria);
-        List names = new ArrayList(criteriaGroups.size());
-        Iterator iter = criteriaGroups.iterator();
-        while(iter.hasNext()) {
-            names.add( ((GroupSymbol)iter.next()).getName().toUpperCase() );
-        }
-        return names;
-    }     
-    
-    
     public static void validateAndCollectCriteriaElements(MappingDocument doc, XMLPlannerEnvironment planEnv) 
         throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
         

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLNodeMappingVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,15 +26,18 @@
 
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.mapping.xml.MappingDocument;
 import org.teiid.query.mapping.xml.MappingNode;
+import org.teiid.query.mapping.xml.MappingSourceNode;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
+import org.teiid.query.sql.navigator.PreOrPostOrderNavigator;
 import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.Symbol;
 import org.teiid.query.sql.visitor.AbstractSymbolMappingVisitor;
 
@@ -58,33 +61,54 @@
         this.metadata = metadata;
     }
     
+    @Override
+    protected boolean createAliases() {
+    	return false; //xml style selects do not have aliases
+    }
+    
     /**
      * @see AbstractSymbolMappingVisitor#getMappedSymbol(Symbol)
      */
     protected Symbol getMappedSymbol(Symbol symbol) {
-    	if(!(symbol instanceof ElementSymbol)) {
-    		return null;
-    	}
-
-		// Lookup full path to mapping node from symbol
-		ElementSymbol element = (ElementSymbol) symbol;
-        
         try {
-            String path = metadata.getFullName(element.getMetadataID()).toUpperCase();
-		
+        	Object metadataId = null;
+        	Object groupId = null;
+	    	if (symbol instanceof GroupSymbol) {
+	    		GroupSymbol groupSymbol = (GroupSymbol)symbol;
+	    		metadataId = groupSymbol.getMetadataID();
+	    		groupId = metadataId;
+	    	} else {
+				ElementSymbol element = (ElementSymbol) symbol;
+				metadataId = element.getMetadataID();
+				groupId = element.getGroupSymbol().getMetadataID();
+	    	}
+	    	boolean xml = metadata.isXMLGroup(groupId);
+	    	if (!xml) {
+    			return symbol;
+	    	}
+	    	String path = metadata.getFullName(metadataId).toUpperCase();
+	
     		// Find mapping node for specified path
-    		MappingNode elementNode = MappingNode.findNode(rootNode, path); 
-    		if(elementNode == null) { 
+    		MappingNode node = MappingNode.findNode(rootNode, path); 
+    		if(node == null) { 
     			return null;
     		}
-    		
+    		MappingSourceNode msn = node.getSourceNode();
+			if (msn == null) {
+				return null;
+			}
+    		if (symbol instanceof GroupSymbol) {
+    			GroupSymbol gs = msn.getMappedSymbol(new GroupSymbol(msn.getResultName()));
+    			return gs;
+    		} 
     		// Construct a new element node based on mapping node reference
-    		String symbolName = elementNode.getNameInSource();
+    		String symbolName = node.getNameInSource();
     		if (symbolName == null){
     			return null;
     		}
-			return elementNode.getSourceNode().getMappedSymbol(new ElementSymbol(symbolName));
-        } catch (TeiidComponentException err) {
+			ElementSymbol es = msn.getMappedSymbol(new ElementSymbol(symbolName));
+			return es;
+        } catch (TeiidException err) {
             throw new TeiidRuntimeException(err);
         } 
     }
@@ -100,17 +124,15 @@
      */
     public static Criteria convertCriteria(Criteria simpleCrit, MappingDocument rootNode, QueryMetadataInterface metadata)
     throws QueryPlannerException, TeiidComponentException{
-        return (Criteria)convertObject(simpleCrit, rootNode, metadata);
+        return convertObject((Criteria)simpleCrit.clone(), rootNode, metadata, true);
     }
 
-    public static LanguageObject convertObject(LanguageObject object, MappingDocument rootNode, QueryMetadataInterface metadata)
+    public static <T extends LanguageObject> T convertObject(T object, MappingDocument rootNode, QueryMetadataInterface metadata, boolean deep)
     throws QueryPlannerException, TeiidComponentException{
-        LanguageObject copy = (LanguageObject)object.clone();
-
         //Don't want to do deep visiting
         XMLNodeMappingVisitor mappingVisitor = new XMLNodeMappingVisitor(rootNode, metadata);
         try {
-            PreOrderNavigator.doVisit(copy, mappingVisitor);
+            PreOrPostOrderNavigator.doVisit(object, mappingVisitor, PreOrPostOrderNavigator.POST_ORDER, deep);
         } catch (TeiidRuntimeException e) {
             Throwable child = e.getChild();
             
@@ -126,7 +148,7 @@
             throw new QueryPlannerException("ERR.015.004.0046", QueryPlugin.Util.getString("ERR.015.004.0046", new Object[] {unmappedSymbols, object})); //$NON-NLS-1$ //$NON-NLS-2$
         }
 
-        return copy;
+        return object;
     }
         
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanToProcessVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,7 +22,8 @@
 
 package org.teiid.query.optimizer.xml;
 
-import java.util.Iterator;
+import java.util.HashMap;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Stack;
@@ -53,7 +54,6 @@
 import org.teiid.query.processor.xml.ExecStagingTableInstruction;
 import org.teiid.query.processor.xml.IfInstruction;
 import org.teiid.query.processor.xml.InitializeDocumentInstruction;
-import org.teiid.query.processor.xml.JoinedWhileInstruction;
 import org.teiid.query.processor.xml.MoveCursorInstruction;
 import org.teiid.query.processor.xml.MoveDocInstruction;
 import org.teiid.query.processor.xml.ProcessorInstruction;
@@ -69,10 +69,10 @@
  */
 public class XMLPlanToProcessVisitor implements MappingInterceptor {
     
-    Stack programStack = new Stack(); 
+    Stack<Program> programStack = new Stack<Program>(); 
     XMLPlannerEnvironment planEnv;
     Program originalProgram ;
-    Program cleanupProgram  = new Program();
+    Map<String, List<String>> unloadInstructions = new HashMap<String, List<String>>();
 
     public XMLPlanToProcessVisitor(XMLPlannerEnvironment env) {
         this.planEnv = env;
@@ -85,14 +85,13 @@
     
     public void end(MappingDocument doc, Map context) {
         // remove the current program from the stack; we no longer need this
-        originalProgram=(Program)this.programStack.pop();
+        originalProgram=this.programStack.pop();
         
-        // cleanup program will have instructions to unload the staging table.
-        originalProgram.addInstructions(cleanupProgram);
+        addUnloads(originalProgram, null);
     }
         
     public void start(MappingAttribute attribute, Map context){
-        Program currentProgram = (Program)this.programStack.peek();
+        Program currentProgram = this.programStack.peek();
         ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(attribute);
         if (tagInst != null) {
             currentProgram.addInstruction(tagInst);
@@ -103,7 +102,7 @@
     }
     
     public void start(MappingCommentNode comment, Map context){
-        Program currentProgram = (Program)this.programStack.peek();
+        Program currentProgram = this.programStack.peek();
         ProcessorInstruction tagInst = TagBuilderVisitor.buildTag(comment);
         if (tagInst != null) {
             currentProgram.addInstruction(tagInst);
@@ -138,7 +137,7 @@
         // process the node as others (if see we have not done anything for this node yet..)
         commonStart(choice, context);
 
-        Program currentProgram = (Program)this.programStack.peek();        
+        Program currentProgram = this.programStack.peek();        
         currentProgram.addInstruction(ifInst);        
     }
     
@@ -197,10 +196,10 @@
 
     private void endRootRecursive(MappingBaseNode node, Map context) {
         // add the recursive program to the main program.
-        Program recursiveProgram = (Program)programStack.pop();
+        Program recursiveProgram = programStack.pop();
         
         // this is the main program
-        Program currentProgram = (Program)this.programStack.peek();
+        Program currentProgram = this.programStack.peek();
         currentProgram.addInstructions(recursiveProgram);
         context.remove(node.getRecursionId());
         
@@ -215,7 +214,7 @@
     
     public void start(MappingElement element, Map context){
         //commonStart(element, context);
-        Program currentProgram = (Program)programStack.peek();
+        Program currentProgram = programStack.peek();
         
         // if we are dealing with multiple documents
         startFragment(currentProgram, element);
@@ -228,13 +227,13 @@
         // If there are more children under this node move the cursor down
         if (!element.getChildren().isEmpty()) {
             // update the program pointer 
-            currentProgram = (Program)programStack.peek();
+            currentProgram = programStack.peek();
             currentProgram.addInstruction(new MoveDocInstruction(MoveDocInstruction.DOWN));
         }
     }
 
     public void end(MappingElement element, Map context){
-        Program currentProgram = (Program)this.programStack.peek();
+        Program currentProgram = this.programStack.peek();
         
         // If there were more children under this node move the cursor up        
         if (!element.getChildren().isEmpty()) {
@@ -244,33 +243,20 @@
         commonEnd(element, context);
         
         // update the program pointer
-        currentProgram = (Program)programStack.peek();            
+        currentProgram = programStack.peek();            
         
         // if we are dealing with multiple documents                        
         endFragment(currentProgram, element);        
     }
    
     public void start(MappingSourceNode node, Map context) {
-        Program currentProgram = (Program)programStack.peek();
+        Program currentProgram = programStack.peek();
         
         commonStart(node, context);
         
         String source = node.getActualResultSetName();
         ResultSetInfo info= node.getResultSetInfo();
         
-        if (info.isJoinedWithParent()) {
-            //create a dependent while loop
-            JoinedWhileInstruction whileInst = new JoinedWhileInstruction(source, new Integer(info.getMappingClassNumber()),
-                                                                          info.getMappingClassSymbol(), node.getResultName());
-            currentProgram.addInstruction(whileInst);
-            
-            Program childProgram = new Program();
-            whileInst.setBlockProgram(childProgram);
-            
-            programStack.push(childProgram);
-            return;
-        }
-        
         // Add instruction to execute relational query
         ExecSqlInstruction sqlInst = new ExecSqlInstruction(source, info);
         currentProgram.addInstruction(sqlInst);
@@ -301,15 +287,12 @@
     }
     
     public void end(MappingSourceNode node, Map context) {
-        Program currentProgram = (Program)programStack.peek();        
+        Program currentProgram = programStack.peek();        
         
         String source = node.getActualResultSetName();  
-        ResultSetInfo info= node.getResultSetInfo();
         
-        if (!info.isJoinRoot()) {
-            // move to next row.
-            currentProgram.addInstruction(new MoveCursorInstruction(source));
-        }
+        // move to next row.
+        currentProgram.addInstruction(new MoveCursorInstruction(source));
 
         // Since each element with a source started a new program; 
         // since now we are done with children, we need to pop to current program                                    
@@ -343,17 +326,23 @@
             startRootRecursive(node, context);
         }
         
-        List stagingTables = node.getStagingTables();
-        for (final Iterator i = stagingTables.iterator(); i.hasNext();) {
-            final String table = (String)i.next();
-            Program currentProgram = (Program)programStack.peek();
+        List<String> stagingTables = node.getStagingTables();
+        Program currentProgram = programStack.peek();
 
+        for (String table : stagingTables) {
             // load staging
-            currentProgram.addInstruction(new ExecStagingTableInstruction(table, planEnv.getStagingTableResultsInfo(table)));
+            ResultSetInfo stagingTableResultsInfo = planEnv.getStagingTableResultsInfo(table);
+			currentProgram.addInstruction(new ExecStagingTableInstruction(table, stagingTableResultsInfo));
             
-            // unload sttaging
+            // unload staging
             String unloadName = planEnv.unLoadResultName(table);
-            cleanupProgram.addInstruction(new ExecStagingTableInstruction(unloadName, planEnv.getStagingTableResultsInfo(unloadName)));
+            String parent = stagingTableResultsInfo.getStagingRoot();
+            List<String> instructions = this.unloadInstructions.get(parent);
+            if (instructions == null) {
+            	instructions = new LinkedList<String>();
+            	this.unloadInstructions.put(parent, instructions);
+            }
+            instructions.add(unloadName);
         } // for
     }
     
@@ -362,10 +351,25 @@
             // stop recording and update the program
             endRootRecursive(node, context);            
         }
+
+        Program currentProgram = programStack.peek();
+        if (node instanceof MappingSourceNode) {
+	        String name = node.getSource();
+	        addUnloads(currentProgram, name);
+        }
     }
+
+	private void addUnloads(Program currentProgram, String name) {
+		List<String> unloads = this.unloadInstructions.get(name);
+        if (unloads != null) {
+        	for (String string : unloads) {
+            	currentProgram.addInstruction(new ExecStagingTableInstruction(string, planEnv.getStagingTableResultsInfo(string)));
+			}
+        }
+	}
     
     public void start(final MappingRecursiveElement element, Map context){
-        Program currentProgram = (Program)programStack.peek();
+        Program currentProgram = programStack.peek();
         
         // if we are dealing with multiple documents
         startFragment(currentProgram, element);
@@ -385,7 +389,7 @@
     }   
     
     public void end(final MappingRecursiveElement element, Map context){
-        Program currentProgram = (Program)programStack.peek();        
+        Program currentProgram = programStack.peek();        
 
         // if we are dealing with multiple documents                        
         endFragment(currentProgram, element);                

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -53,10 +53,11 @@
 import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
 import org.teiid.query.util.CommandContext;
 
@@ -110,7 +111,7 @@
         GroupSymbol group = xmlQuery.getFrom().getGroups().iterator().next();
 
         MappingDocument doc = (MappingDocument)metadata.getMappingNode(group.getMetadataID());
-        doc = (MappingDocument)doc.clone();
+        doc = doc.clone();
         
         // make a copy of the document
         planEnv.mappingDoc = doc;
@@ -200,29 +201,33 @@
         if (debug) {
             debugDocumentInfo("After Exclude", planEnv); //$NON-NLS-1$
         }
+
+        //Resolve all the "elements" against the result sets
+        NameInSourceResolverVisitor.resolveElements(planEnv.mappingDoc, planEnv);
         
+        //Validate and resolve the criteria specified on the mapping nodes.
+        ValidateMappedCriteriaVisitor.validateAndCollectCriteriaElements(planEnv.mappingDoc, planEnv);
+
+        XMLProjectionMinimizer.minimizeProjection(planEnv);
+        
+        if (debug) {
+            debugDocumentInfo("After Projection Minimization", planEnv); //$NON-NLS-1$
+        }
+        
         // Autostage queries. try to auto-stage the planned queries
         // removal of this step should not affect overall processing
         XMLStagaingQueryPlanner.stageQueries(planEnv.mappingDoc, planEnv);
         
-        //JoinSourceNodes.joinSourceNodes(planEnv.mappingDoc, planEnv);
-        
         //Plan the various relational result sets
         XMLQueryPlanner.optimizeQueries(planEnv.mappingDoc, planEnv);
         
 		//Handle nillable nodes
         planEnv.mappingDoc = HandleNillableVisitor.execute(planEnv.mappingDoc);
-        
-        //Resolve all the "elements" aginst the result sets
-        NameInSourceResolverVisitor.resolveElements(planEnv.mappingDoc, planEnv);
-        
-        //Validate and resolve the criteria specified on the mapping nodes.
-        ValidateMappedCriteriaVisitor.validateAndCollectCriteriaElements(planEnv.mappingDoc, planEnv);
 	}
     
     static void removeExcluded(MappingNode node) {
-        for (Iterator i = node.getChildren().iterator(); i.hasNext();) {
-            MappingNode child = (MappingNode)i.next();
+        for (Iterator<MappingNode> i = node.getChildren().iterator(); i.hasNext();) {
+            MappingNode child = i.next();
             if (!(node instanceof MappingRecursiveElement) && child.isExcluded()) {
                 i.remove();
             } else {
@@ -242,15 +247,14 @@
         SelectSymbol firstSymbol = select.getSymbol(0);
 
         // 0. mark the nodes to be excluded
-        if(firstSymbol instanceof AllSymbol) {
+        if(firstSymbol instanceof MultipleElementSymbol && ((MultipleElementSymbol)firstSymbol).getGroup() == null) {
             return doc;
         }
         
         // Get all the valid nodes to be marked as included.
-        Collection validElements = ElementCollectorVisitor.getElements(select, true);
-        HashSet elements = new HashSet(validElements.size());
-        for (final Iterator i = validElements.iterator(); i.hasNext();) {
-            final ElementSymbol element = (ElementSymbol)i.next();
+        Collection<ElementSymbol> validElements = ElementCollectorVisitor.getElements(select, true);
+        HashSet<String> elements = new HashSet<String>(validElements.size());
+        for (ElementSymbol element : validElements) {
             elements.add(element.getCanonicalName());
         }
         
@@ -277,8 +281,8 @@
             return;
         }
         
-        List elements = orderBy.getSortKeys();
-		List types = orderBy.getTypes();
+        List<SingleElementSymbol> elements = orderBy.getSortKeys();
+		List<Boolean> types = orderBy.getTypes();
 
 		for (int i = 0; i< elements.size(); i++) {
 			ElementSymbol elemSymbol = (ElementSymbol) elements.get(i);
@@ -301,7 +305,7 @@
                 by = new OrderBy();
             }
             ElementSymbol mappedSymbol = (ElementSymbol)sourceNode.getSymbolMap().get(new ElementSymbol(elementNode.getNameInSource()));
-            by.addVariable((ElementSymbol)mappedSymbol.clone(), ((Boolean)types.get(i)).booleanValue());
+            by.addVariable(mappedSymbol.clone(), types.get(i));
             rs.setOrderBy(by);
 		}
 	}

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlannerEnvironment.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlannerEnvironment.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLPlannerEnvironment.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -124,7 +124,7 @@
     public ResultSetInfo getStagingTableResultsInfo(String groupName) {
         ResultSetInfo info = (ResultSetInfo)this.stagingResultsInfo.get(groupName.toUpperCase());
         if (info == null) {
-            info = new ResultSetInfo(groupName, true);            
+            info = new ResultSetInfo(groupName);            
             this.stagingResultsInfo.put(info.getResultSetName().toUpperCase(), info);
         }
         return info;

Copied: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLProjectionMinimizer.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,201 @@
+/*
+ * 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 org.teiid.query.optimizer.xml;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.Map;
+
+import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.mapping.xml.MappingAttribute;
+import org.teiid.query.mapping.xml.MappingCriteriaNode;
+import org.teiid.query.mapping.xml.MappingElement;
+import org.teiid.query.mapping.xml.MappingNode;
+import org.teiid.query.mapping.xml.MappingRecursiveElement;
+import org.teiid.query.mapping.xml.MappingSourceNode;
+import org.teiid.query.mapping.xml.MappingVisitor;
+import org.teiid.query.mapping.xml.Navigator;
+import org.teiid.query.mapping.xml.ResultSetInfo;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.SelectSymbol;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
+
+public class XMLProjectionMinimizer {
+
+	/**
+	 * Implements projection minimization through two passes over the document
+	 */
+	static void minimizeProjection(final XMLPlannerEnvironment planEnv) {
+	    final HashMap<MappingSourceNode, LinkedHashSet<ElementSymbol>> neededElements = new HashMap<MappingSourceNode, LinkedHashSet<ElementSymbol>>();
+	    
+	    //collect included elements
+	    MappingVisitor visitor = new Navigator(true, new MappingVisitor() {
+	    	@Override
+	    	public void visit(MappingAttribute attribute) {
+	    		collectElementSymbol(attribute);
+	    	}
+	
+			private void collectElementSymbol(MappingNode node) {
+				if (node.isExcluded() || node.getElementSymbol() == null) {
+	    			return;
+	    		}
+	    		MappingSourceNode msn = node.getSourceNode();
+	    		ElementSymbol es = node.getElementSymbol();
+	    		collectElementSymbol(msn, es);
+			}
+	
+			private void collectElementSymbol(
+					MappingSourceNode msn, ElementSymbol es) {
+				msn = getActualSourceNode(msn);
+				LinkedHashSet<ElementSymbol> elems = neededElements.get(msn);
+	    		if (elems == null) {
+	    			elems = new LinkedHashSet<ElementSymbol>();
+	    			neededElements.put(msn, elems);
+	    		}
+	    		elems.add(es);
+			}
+	    	
+	    	@Override
+	    	public void visit(MappingElement element) {
+	    		collectElementSymbol(element);
+	    	}
+	    	
+	    	@Override
+	    	public void visit(MappingSourceNode element) {
+	    		try {
+	        		QueryNode node = QueryUtil.getQueryNode(element.getResultName(), planEnv.getGlobalMetadata());
+	                            
+	                Collection<ElementSymbol> bindings = QueryUtil.getBindingElements(node);
+	                MappingSourceNode parent = element.getParentSourceNode();
+	                collectElementSymbols(element, bindings, parent);
+	    		} catch (TeiidException e) {
+	    			throw new TeiidRuntimeException(e);
+	    		}
+	    	}
+	
+			private void collectElementSymbols(
+					MappingSourceNode element,
+					Collection<ElementSymbol> bindings, MappingSourceNode parent) {
+				for (ElementSymbol elementSymbol : bindings) {
+					if (element != null) {
+						elementSymbol = element.getMappedSymbol(elementSymbol);
+					}
+					while (parent != null) {
+						if (parent.getActualResultSetName().equalsIgnoreCase(elementSymbol.getGroupSymbol().getNonCorrelationName())) {
+							collectElementSymbol(parent, elementSymbol);
+							break;
+						}
+						parent = parent.getParentSourceNode();
+					}
+				}
+			}
+	    	
+	    	@Override
+	    	public void visit(MappingCriteriaNode element) {
+	    		Criteria crit = element.getCriteriaNode();
+	    		if (crit == null) {
+	    			return;
+	    		}
+	    		collectElementSymbols(null, ElementCollectorVisitor.getElements(crit, true), element.getSourceNode());
+	    	}
+	    	
+	    	@Override
+	    	public void visit(MappingRecursiveElement element) {
+	    		Criteria crit = element.getCriteriaNode();
+	    		if (crit == null) {
+	    			return;
+	    		}
+	    		collectElementSymbols(null, ElementCollectorVisitor.getElements(crit, true), element.getSourceNode());
+	    	}
+	
+	    });
+	    planEnv.mappingDoc.acceptVisitor(visitor);
+	    
+	    visitor = new Navigator(true, new MappingVisitor() {
+	    	@Override
+	    	public void visit(MappingSourceNode element) {
+	    		try {
+	        		ResultSetInfo rsInfo = element.getResultSetInfo();
+	        		Query rsQuery = (Query)rsInfo.getCommand();
+	        		if (rsQuery.getSelect().isDistinct()) {
+	        			return;
+	        		}
+	        		LinkedHashSet<ElementSymbol> elements = neededElements.get(element);
+	        		if (elements != null) {
+	            		rsQuery.setSelect(new Select(LanguageObject.Util.deepClone(elements, ElementSymbol.class)));
+	        		} else {
+	        			String alias = element.getAliasResultName();
+	        			if (alias == null) {
+	        				rsQuery.setSelect(new Select(Arrays.asList(new ExpressionSymbol("foo", new Constant(1))))); //$NON-NLS-1$
+	        			} else {
+	        				MappingSourceNode actual = getActualSourceNode(element);
+	        				elements = neededElements.get(actual);
+	        				if (elements != null) {
+								Map reverseMap = QueryUtil.createSymbolMap(new GroupSymbol(element.getAliasResultName()), 
+										rsInfo.getResultSetName(),
+										ResolverUtil.resolveElementsInGroup(QueryUtil.createResolvedGroup(element.getAliasResultName(), planEnv.getGlobalMetadata()), planEnv.getGlobalMetadata()));
+								Select select = new Select(new ArrayList<SelectSymbol>(elements));
+								ExpressionMappingVisitor.mapExpressions(select, reverseMap);
+								rsQuery.setSelect(select);
+							}
+	        			}
+	        		}
+	    		} catch (TeiidException e) {
+	    			throw new TeiidRuntimeException(e);
+	    		}
+	    	}
+
+	    });
+	    planEnv.mappingDoc.acceptVisitor(visitor);
+	}
+	
+	private static MappingSourceNode getActualSourceNode(MappingSourceNode element) {
+		if (element.getAliasResultName() == null) {
+			return element;
+		}
+		String actual = element.getActualResultSetName();
+		MappingSourceNode parent = element.getParentSourceNode();
+		while (parent != null) {
+			if (parent.getActualResultSetName().equalsIgnoreCase(actual) ) {
+				return parent;
+			}
+			parent = parent.getParentSourceNode();
+		}
+		return null;
+	}
+
+}

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLQueryPlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -55,7 +55,6 @@
 import org.teiid.query.processor.relational.RelationalPlan;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.resolver.util.ResolverUtil;
-import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.lang.Drop;
@@ -68,17 +67,39 @@
 import org.teiid.query.sql.lang.Limit;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.QueryCommand;
+import org.teiid.query.sql.lang.SubqueryContainer;
 import org.teiid.query.sql.lang.SubqueryFromClause;
 import org.teiid.query.sql.lang.UnaryFromClause;
 import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.visitor.ElementCollectorVisitor;
+import org.teiid.query.sql.visitor.GroupsUsedByElementsVisitor;
+import org.teiid.query.sql.visitor.PredicateCollectorVisitor;
 import org.teiid.query.sql.visitor.StaticSymbolMappingVisitor;
 
 
 public class XMLQueryPlanner {
 
-    static void prePlanQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv) 
+    private static final class MappingSourceNodeFinder extends MappingVisitor {
+		private final GroupSymbol gs;
+		MappingSourceNode msn;
+
+		private MappingSourceNodeFinder(GroupSymbol gs) {
+			this.gs = gs;
+		}
+
+		@Override
+		public void visit(MappingSourceNode element) {
+			if (element.getAliasResultName() == null && element.getResultSetInfo().getResultSetName().equalsIgnoreCase(gs.getNonCorrelationName())) {
+				msn = element;
+				setAbort(true);
+			}
+		}
+	}
+
+	static void prePlanQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv) 
         throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
         
         MappingVisitor queryPlanVisitor = new MappingVisitor() {
@@ -86,10 +107,8 @@
             public void visit(MappingBaseNode baseNode) {
                 try {
                     // first if there are any explicit staging tables plan them first 
-                    List stagingTables = baseNode.getStagingTables();
-                    for (final Iterator i = stagingTables.iterator(); i.hasNext();) {
-                        
-                        final String tableName = (String)i.next();
+                    List<String> stagingTables = baseNode.getStagingTables();
+                    for (String tableName : stagingTables) {
                         planStagingTable(tableName, planEnv);    
                     }
                     
@@ -116,18 +135,14 @@
                 try {
                     ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
                 
-                    if (rsInfo.isJoinedWithParent()) {
-                        return;
-                    }
-                    
                     Query command = (Query)rsInfo.getCommand();
                     
                     prepareQuery(sourceNode, planEnv, command);
                     
-                    QueryUtil.rewriteQuery(command, planEnv.getGlobalMetadata(), planEnv.context);
+                    Command cmd = QueryUtil.rewriteQuery(command, planEnv.getGlobalMetadata(), planEnv.context);
                     
                     // Plan the result set.
-                    ProcessorPlan queryPlan = optimizePlan(command, planEnv);
+                    ProcessorPlan queryPlan = optimizePlan(cmd, planEnv);
                     rsInfo.setPlan(queryPlan);                    
                 } catch (Exception e) {
                     throw new TeiidRuntimeException(e);
@@ -159,7 +174,7 @@
         }
     }
     
-    static void planQueries(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv) 
+    static void planQueries(final MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv) 
         throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
 
         ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
@@ -188,8 +203,6 @@
             rsQuery.setLimit(new Limit(null, new Constant(new Integer(limit))));
         }
         
-        //prepareQuery(sourceNode, planEnv, rsQuery);
-        
         // this query is not eligible for staging; proceed normally.
         rsInfo.setCommand(rsQuery);            
     }
@@ -206,15 +219,15 @@
     static void prepareQuery(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv, QueryCommand rsQuery) 
         throws TeiidComponentException, QueryResolverException {
         
-        Collection externalGroups = getExternalGroups(sourceNode);
+        Collection<GroupSymbol> externalGroups = getExternalGroups(sourceNode);
         
         rsQuery.setExternalGroupContexts(new GroupContext(null, externalGroups));
         
 		QueryResolver.resolveCommand(rsQuery, planEnv.getGlobalMetadata());
     }
     
-    private static Collection getExternalGroups(MappingSourceNode sourceNode) {
-        Collection externalGroups = new HashSet();
+    private static Collection<GroupSymbol> getExternalGroups(MappingSourceNode sourceNode) {
+        Collection<GroupSymbol> externalGroups = new HashSet<GroupSymbol>();
 
         MappingSourceNode parentSource = sourceNode.getParentSourceNode();
         while (parentSource != null) {
@@ -228,14 +241,14 @@
     /**
      * The Criteria Source nodes are source nodes underneath the context Node.  
      */
-    private static boolean getResultSets(MappingSourceNode contextNode, Set criteriaSourceNodes, LinkedHashSet allResultSets)  {
+    private static boolean getResultSets(MappingSourceNode contextNode, Set<MappingSourceNode> criteriaSourceNodes, LinkedHashSet<MappingSourceNode> allResultSets)  {
         
         boolean singleParentage = true;
 
-        for (Iterator i = criteriaSourceNodes.iterator(); i.hasNext();) {
-            MappingSourceNode node = (MappingSourceNode)i.next();
+        for (Iterator<MappingSourceNode> i = criteriaSourceNodes.iterator(); i.hasNext();) {
+            MappingSourceNode node = i.next();
 
-            List rsStack = getResultSetStack(contextNode, node);
+            List<MappingSourceNode> rsStack = getResultSetStack(contextNode, node);
             
             if (allResultSets.containsAll(rsStack)) {
                 continue;
@@ -249,12 +262,12 @@
         return singleParentage;
     }
     
-    private static LinkedList getResultSetStack(MappingSourceNode contextNode, MappingBaseNode node) {
-        LinkedList rsStack = new LinkedList();
+    private static LinkedList<MappingSourceNode> getResultSetStack(MappingSourceNode contextNode, MappingBaseNode node) {
+        LinkedList<MappingSourceNode> rsStack = new LinkedList<MappingSourceNode>();
         
         while (node != null && node != contextNode) {
             if (node instanceof MappingSourceNode) {
-                rsStack.add(0, node);
+                rsStack.add(0, (MappingSourceNode)node);
             }
             node = node.getParentNode();
         }
@@ -270,7 +283,7 @@
         
         // this list of all the source nodes below the context, which are directly ro indirectly 
         // involved in the criteria
-        LinkedHashSet resultSets = new LinkedHashSet();
+        LinkedHashSet<MappingSourceNode> resultSets = new LinkedHashSet<MappingSourceNode>();
         
         boolean singleParentage = getResultSets(contextNode, rsInfo.getCriteriaResultSets(), resultSets);
         
@@ -286,9 +299,7 @@
         
         Query currentQuery = contextQuery;
         
-        for (Iterator i = resultSets.iterator(); i.hasNext();) {
-            MappingSourceNode rsNode = (MappingSourceNode)i.next();
-            
+        for (MappingSourceNode rsNode : resultSets) {
             ResultSetInfo childRsInfo = rsNode.getResultSetInfo();
             
             QueryNode planNode = QueryUtil.getQueryNode(childRsInfo.getResultSetName(), planEnv.getGlobalMetadata());    
@@ -299,35 +310,19 @@
             updateSymbolMap(symbolMap, childRsInfo.getResultSetName(), inlineViewName, planEnv.getGlobalMetadata());
             
             // check if the criteria has been raised, if it is then we can update this as a join.
-            if (childRsInfo.isCriteriaRaised()) {
+            if (!rsInfo.isCritNullDependent() && childRsInfo.hasInputSet() && childRsInfo.isCriteriaRaised()) {
                 Query transformationQuery = (Query) command;
                 SubqueryFromClause sfc = (SubqueryFromClause)transformationQuery.getFrom().getClauses().get(0);
                 
                 Criteria joinCriteria = ((Query)childRsInfo.getCommand()).getCriteria();
                 
-                if (joinCriteria == null) {
-                    joinCriteria = QueryRewriter.TRUE_CRITERIA;
-                }
-                
                 joinCriteria = (Criteria)joinCriteria.clone();
                 
                 //update the from clause
-                FromClause clause = (FromClause)currentQuery.getFrom().getClauses().remove(0);
+                FromClause clause = currentQuery.getFrom().getClauses().remove(0);
                 
-                JoinPredicate join = null;
+                JoinPredicate join = new JoinPredicate(clause, sfc, JoinType.JOIN_LEFT_OUTER, Criteria.separateCriteriaByAnd(joinCriteria));
                 
-                if (clause instanceof JoinPredicate) {
-                    join = (JoinPredicate)clause;
-                    
-                    FromClause right = join.getRightClause();
-                    
-                    JoinPredicate newRight = new JoinPredicate(right, sfc, JoinType.JOIN_LEFT_OUTER, Criteria.separateCriteriaByAnd(joinCriteria));
-                    
-                    join.setRightClause(newRight);
-                } else {
-                    join = new JoinPredicate(clause, sfc, JoinType.JOIN_LEFT_OUTER, Criteria.separateCriteriaByAnd(joinCriteria));
-                }
-                
                 currentQuery.getFrom().addClause(join);
                 
                 currentQuery.getSelect().setDistinct(true);
@@ -371,15 +366,87 @@
             GroupSymbol groupSymbol = QueryUtil.createResolvedGroup(rsInfo.getResultSetName(), planEnv.getGlobalMetadata());
             planEnv.addQueryNodeToMetadata(groupSymbol.getMetadataID(), modifiedNode);
         } 
+        
+        for (Criteria crit : PredicateCollectorVisitor.getPredicates(userCrit)) {
+        	handleXmlSubqueries(planEnv, crit);
+        }
     }
 
-    private static void updateSymbolMap(Map symbolMap, String oldGroup, final String newGroup, QueryMetadataInterface metadata) 
+	private static void handleXmlSubqueries(XMLPlannerEnvironment planEnv,
+			Criteria userCrit) throws QueryPlannerException {
+		if (!(userCrit instanceof SubqueryContainer<?>)) {
+			return;
+		}
+    	SubqueryContainer<?> subquery = (SubqueryContainer<?>)userCrit;
+    	if (!(subquery.getCommand() instanceof Query)) {
+    		return;
+    	}
+		Query q = (Query)subquery.getCommand();
+		if (q.getFrom() == null || q.getCriteria() == null) {
+			return;
+		}
+		List<GroupSymbol> groups = q.getFrom().getGroups();
+		if (groups.size() != 1) {
+			return;
+		}
+		final GroupSymbol gs = groups.get(0);
+		LinkedHashSet<GroupSymbol> allGroups = new LinkedHashSet<GroupSymbol>();
+		allGroups.add(gs);
+		//TODO: this group should have been marked as xml, or could attempt this step prior to place user criteria
+		if (planEnv.getGlobalMetadata().getMetadataStore().getTempGroupID(gs.getNonCorrelationName().toUpperCase()) == null) {
+			return;
+		}
+		MappingSourceNode parentMsn = findMappingSourceNode(planEnv, gs);
+		for (Criteria crit : PredicateCollectorVisitor.getPredicates(q.getCriteria())) {
+			Collection<ElementSymbol> elems = ElementCollectorVisitor.getElements(crit, false);
+			Collection<GroupSymbol> critGroups = new LinkedList<GroupSymbol>();
+			for (ElementSymbol elementSymbol : elems) {
+				if (!elementSymbol.isExternalReference()) {
+					critGroups.add(elementSymbol.getGroupSymbol());
+				}
+			}
+			for (GroupSymbol groupSymbol : critGroups) {
+				if (allGroups.contains(groupSymbol)) {
+					continue;
+				}
+				MappingSourceNode childMsn = findMappingSourceNode(planEnv, groupSymbol);
+				while (childMsn != parentMsn) {
+					if (childMsn == null) {
+						throw new QueryPlannerException(QueryPlugin.Util.getString("XMLQueryPlanner.invalid_relationship", crit, parentMsn)); //$NON-NLS-1$
+					}
+					if (!childMsn.getResultSetInfo().isCriteriaRaised()) {
+						throw new QueryPlannerException(QueryPlugin.Util.getString("XMLQueryPlanner.non_simple_relationship", crit, childMsn)); //$NON-NLS-1$
+					}
+					Query parentQuery = (Query)childMsn.getResultSetInfo().getCommand();
+					if (parentQuery.getCriteria() != null 
+							&& allGroups.addAll(GroupsUsedByElementsVisitor.getGroups(parentQuery.getCriteria()))) {
+						q.setCriteria(Criteria.combineCriteria(q.getCriteria(), (Criteria) parentQuery.getCriteria().clone()));
+					}
+					childMsn = childMsn.getParentSourceNode();
+				}
+			}
+			q.getFrom().getClauses().clear();
+			for (GroupSymbol groupSymbol : allGroups) {
+				q.getFrom().addClause(new UnaryFromClause(groupSymbol));
+			}
+			handleXmlSubqueries(planEnv, crit);
+		}
+	}
+
+	private static MappingSourceNode findMappingSourceNode(
+			XMLPlannerEnvironment planEnv, final GroupSymbol gs) {
+		MappingSourceNodeFinder finder = new MappingSourceNodeFinder(gs);
+		planEnv.mappingDoc.acceptVisitor(new Navigator(true, finder));
+		return finder.msn;
+	}
+
+    static void updateSymbolMap(Map symbolMap, String oldGroup, final String newGroup, QueryMetadataInterface metadata) 
         throws QueryResolverException,QueryMetadataException,TeiidComponentException {
         
         GroupSymbol oldGroupSymbol = new GroupSymbol(oldGroup);
         ResolverUtil.resolveGroup(oldGroupSymbol, metadata);
         
-        HashSet projectedElements = new HashSet(ResolverUtil.resolveElementsInGroup(oldGroupSymbol, metadata));
+        HashSet<ElementSymbol> projectedElements = new HashSet<ElementSymbol>(ResolverUtil.resolveElementsInGroup(oldGroupSymbol, metadata));
         
         symbolMap.putAll(QueryUtil.createSymbolMap(oldGroupSymbol, newGroup, projectedElements));
     }
@@ -417,7 +484,7 @@
 
         GroupSymbol srcGroup = QueryUtil.createResolvedGroup(srcGroupName, planEnv.getGlobalMetadata());
         
-        String intoGroupName =  "#"+stageGroupName.replace('.', '_'); //$NON-NLS-1$
+        String intoGroupName = getTempTableName(stageGroupName);
         GroupSymbol intoGroupSymbol = new GroupSymbol(intoGroupName); 
                 
         query.setInto(new Into(intoGroupSymbol));
@@ -482,11 +549,11 @@
         rsInfo.setCommand(cmd);
         rsInfo.setPlan(plan);
         
-        //set the carinality on the temp group.
+        //set the cardinality on the temp group.
         TempMetadataID intoGroupID = (TempMetadataID)intoGroupSymbol.getMetadataID();
         intoGroupID.setCardinality(cardinality);
         
-        // add the meterialization hook for the staged table to original one.
+        // add the materialization hook for the staged table to original one.
         //GroupSymbol groupSymbol = (GroupSymbol)query.getFrom().getGroups().get(0);
         planEnv.addStagingTable(srcGroup.getMetadataID(), intoGroupID);
         
@@ -503,6 +570,11 @@
         
         return true;
     }
+
+	static String getTempTableName(String stageGroupName) {
+		String intoGroupName =  "#"+stageGroupName.replace('.', '_'); //$NON-NLS-1$
+		return intoGroupName;
+	}
         
     /**
      * This builds a command in the following form; If staging table name is "FOO"

Modified: branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/optimizer/xml/XMLStagaingQueryPlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,23 +22,54 @@
 
 package org.teiid.query.optimizer.xml;
 
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
 
 import org.teiid.api.exception.query.QueryMetadataException;
+import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidRuntimeException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
 import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.mapping.xml.MappingBaseNode;
 import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingNode;
 import org.teiid.query.mapping.xml.MappingSourceNode;
 import org.teiid.query.mapping.xml.MappingVisitor;
 import org.teiid.query.mapping.xml.Navigator;
 import org.teiid.query.mapping.xml.ResultSetInfo;
+import org.teiid.query.metadata.TempMetadataStore;
 import org.teiid.query.optimizer.relational.RelationalPlanner;
+import org.teiid.query.parser.QueryParser;
+import org.teiid.query.resolver.QueryResolver;
+import org.teiid.query.resolver.util.ResolverUtil;
+import org.teiid.query.resolver.util.ResolverVisitor;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.CompareCriteria;
+import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.lang.ExistsCriteria;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.GroupBy;
+import org.teiid.query.sql.lang.Insert;
 import org.teiid.query.sql.lang.Option;
 import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
 
 
@@ -47,7 +78,6 @@
  */
 public class XMLStagaingQueryPlanner {
     
-    
     static void stageQueries(MappingDocument doc, final XMLPlannerEnvironment planEnv) 
         throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
 
@@ -86,7 +116,7 @@
     }    
     
     static boolean stagePlannedQuery(MappingSourceNode sourceNode, XMLPlannerEnvironment planEnv) 
-        throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException {
+        throws QueryPlannerException, QueryMetadataException, TeiidComponentException, QueryResolverException, QueryParserException {
     
         Option option = planEnv.xmlCommand.getOption();
         
@@ -104,7 +134,7 @@
         ResultSetInfo rsInfo = sourceNode.getResultSetInfo();
 
         // If this node has been eligible for raising, it will be eligible for staging.
-        if (!rsInfo.isCriteriaRaised()) {
+        if (rsInfo.hasInputSet() && !rsInfo.isCriteriaRaised()) {
             return false;
         }
         
@@ -114,18 +144,6 @@
             return false;
         }
         
-        //id as mapping class
-        Object metadataID = planEnv.getGlobalMetadata().getGroupID(sourceNode.getResultName());
-        if (RelationalPlanner.isNoCacheGroup(planEnv.getGlobalMetadata(), metadataID, option)) {
-            return false;
-        }
-
-        //id as generated mapping class name
-        metadataID = planEnv.getGlobalMetadata().getGroupID(sourceNode.getActualResultSetName());
-        if (RelationalPlanner.isNoCacheGroup(planEnv.getGlobalMetadata(), metadataID, option)) {
-            return false;
-        }
-        
         // get the original transformation of the mapping class before planning. 
         Query stagableQuery = (Query)QueryUtil.getQueryFromQueryNode(groupName, planEnv);
         
@@ -134,23 +152,198 @@
         //check for already staged queries
         if (groups.size() == 1) {
             GroupSymbol group = groups.iterator().next();
-            group = QueryUtil.createResolvedGroup((GroupSymbol)group.clone(), planEnv.getGlobalMetadata());
+            group = QueryUtil.createResolvedGroup(group.clone(), planEnv.getGlobalMetadata());
             if (planEnv.isStagingTable(group.getMetadataID()) && stagableQuery.getCriteria() == null) {
                 return false;
             }
         }
         
+        Criteria crit = ((Query)rsInfo.getCommand()).getCriteria();
+
+        GroupSymbol parent = null;
+        LinkedHashSet<ElementSymbol> outerReferences = new LinkedHashSet<ElementSymbol>();
+        LinkedHashSet<ElementSymbol> fkColumns = new LinkedHashSet<ElementSymbol>();
+        //see if we can perform a dependent join
+        for (Criteria conjunct : Criteria.separateCriteriaByAnd(crit)) {
+        	if (!(conjunct instanceof CompareCriteria)) {
+        		continue;
+        	}
+        	CompareCriteria cc = (CompareCriteria)conjunct;
+        	if (cc.getOperator() != CompareCriteria.EQ) {
+        		continue;
+        	}
+        	if (!(cc.getLeftExpression() instanceof ElementSymbol) 
+        			|| !(cc.getRightExpression() instanceof ElementSymbol)) {
+        		continue;
+        	}
+    		ElementSymbol les = (ElementSymbol)cc.getLeftExpression();
+    		ElementSymbol res = (ElementSymbol)cc.getRightExpression();
+    		if (les.getGroupSymbol().getNonCorrelationName().equalsIgnoreCase(groupName)) {
+				parent = res.getGroupSymbol();
+				outerReferences.add(res.clone());
+				fkColumns.add(les.clone());
+    		} else if (res.getGroupSymbol().getNonCorrelationName().equalsIgnoreCase(groupName)) {
+				parent = les.getGroupSymbol();
+				outerReferences.add(les.clone());
+				fkColumns.add(res.clone());
+    		}
+        }
+        String stagingGroupName = planEnv.getStagedResultName(groupName);  
+
+        boolean recursive = false;
+        MappingSourceNode msn = sourceNode;
+        while (!recursive && msn != null) {
+        	MappingNode mappingNode = msn.getChildren().get(0);
+			if (mappingNode instanceof MappingBaseNode) {
+            	recursive = ((MappingBaseNode)mappingNode).isRootRecursiveNode();
+        	}
+        	msn = msn.getParentSourceNode();
+        }
+        
+        if (parent != null && !recursive) {
+            stagableQuery = (Query)stagableQuery.clone();
+            String parentName = parent.getNonCorrelationName();
+            
+            String parentStagingName = planEnv.getStagedResultName(parentName);
+            GroupSymbol parentTempTable = new GroupSymbol(XMLQueryPlanner.getTempTableName(parentStagingName));
+        	ResultSetInfo parentRsInfo = planEnv.getStagingTableResultsInfo(parentStagingName);
+        	String stagingRoot = sourceNode.getParentSourceNode().getSource();
+        	
+        	boolean parentStaged = parentRsInfo.getPlan() != null;
+        	//TODO: check to see if the parent was manually staged
+        	
+        	if (!parentStaged) {
+                //TODO: if not a level 1 child we could use the old auto staging logic instead
+        		
+        		//switch the parent over to the source
+        		parentRsInfo = sourceNode.getParentSourceNode().getResultSetInfo();
+        		
+        		if (parentRsInfo.getTempTable() == null) {
+	        		//create a temp table to represent the resultset
+	                List<SingleElementSymbol> projectedSymbols = parentRsInfo.getCommand().getProjectedSymbols();
+	                ArrayList<SingleElementSymbol> elements = new ArrayList<SingleElementSymbol>(projectedSymbols.size());
+	        		for (SingleElementSymbol singleElementSymbol : projectedSymbols) {
+	        			singleElementSymbol = (SingleElementSymbol) singleElementSymbol.clone();
+						ResolverVisitor.resolveLanguageObject(singleElementSymbol, planEnv.getGlobalMetadata());
+						elements.add(singleElementSymbol);
+					}
+	                TempMetadataStore store = planEnv.getGlobalMetadata().getMetadataStore();
+	                // create a new group name and to the temp store
+	                GroupSymbol newGroup = new GroupSymbol(SourceNodePlannerVisitor.getNewName("#" + planEnv.getAliasName(parentName) + "_RS", store)); //$NON-NLS-1$ //$NON-NLS-2$
+	                newGroup.setMetadataID(store.addTempGroup(newGroup.getName(), elements, false, true));
+	
+	                parentStagingName = newGroup.getName();
+	                parentTempTable = newGroup;
+        		} else {
+        			parentStagingName = parentRsInfo.getTempTable();
+        			parentTempTable = new GroupSymbol(parentRsInfo.getTempTable());
+	                parentStaged = true;
+        		}
+        	} else {
+        		stagingRoot = parentRsInfo.getStagingRoot();
+        	}
+
+            Query query = new Query();
+            query.setSelect(new Select(Arrays.asList(new ExpressionSymbol("expr", new Constant(1))))); //$NON-NLS-1$
+
+            query.setFrom(new From(Arrays.asList(new UnaryFromClause(parentTempTable))));
+            
+            Map symbolMap = new HashMap();
+            String inlineViewName = planEnv.getAliasName(rsInfo.getResultSetName());
+            XMLQueryPlanner.updateSymbolMap(symbolMap, rsInfo.getResultSetName(), inlineViewName, planEnv.getGlobalMetadata());
+            XMLQueryPlanner.updateSymbolMap(symbolMap, parentName, parentTempTable.getName(), planEnv.getGlobalMetadata());
+            
+            crit = (Criteria) crit.clone();
+            ExpressionMappingVisitor.mapExpressions(crit, symbolMap);
+            
+            if (!stagableQuery.getSelect().isDistinct()) {
+            	query.setHaving(crit);
+                //group by is added so that subquery planning sees that we are distinct
+                query.setGroupBy(new GroupBy(new ArrayList<ElementSymbol>(outerReferences)));
+                ExpressionMappingVisitor.mapExpressions(query.getGroupBy(), symbolMap);
+            } else {
+            	query.setCriteria(crit);
+            }
+            ExistsCriteria ec = new ExistsCriteria();
+            ec.setSubqueryHint(new ExistsCriteria.SubqueryHint());
+            ec.getSubqueryHint().setDepJoin(true);
+            ec.setCommand(query);
+            Criteria existing = stagableQuery.getCriteria();
+            stagableQuery.setCriteria(Criteria.combineCriteria(existing, ec));
+            if (!XMLQueryPlanner.planStagaingQuery(false, groupName, stagingGroupName, stagableQuery, planEnv)) {
+            	return false;
+            }
+            if (!parentStaged) {
+            	//need to associate temp load/get/drop with the rsinfo for use by the execsqlinstruction
+            	Insert insert = new Insert();
+            	insert.setGroup(parentTempTable);
+            	int valCount = parentRsInfo.getCommand().getProjectedSymbols().size();
+            	ArrayList<Reference> vals = new ArrayList<Reference>(valCount);
+            	for (int i = 0; i < valCount; i++) {
+            		vals.add(new Reference(i+1));
+            	}
+            	insert.setValues(vals);
+	        	QueryResolver.resolveCommand(insert, planEnv.getGlobalMetadata());
+	        	
+	        	Command tempCommand = QueryParser.getQueryParser().parseCommand("select * from " + parentStagingName); //$NON-NLS-1$
+	        	QueryResolver.resolveCommand(tempCommand, planEnv.getGlobalMetadata());
+	        	
+            	Command dropCommand = QueryParser.getQueryParser().parseCommand("drop table " + parentStagingName); //$NON-NLS-1$
+	        	QueryResolver.resolveCommand(dropCommand, planEnv.getGlobalMetadata());
+
+	            parentRsInfo.setTempTable(parentStagingName);
+	            parentRsInfo.setTempSelect(tempCommand);
+	            parentRsInfo.setTempInsert(insert);
+	            parentRsInfo.setTempDrop(dropCommand);
+            }
+            LogManager.logDetail(LogConstants.CTX_XML_PLANNER, "Using a dependent join to load the mapping class", groupName); //$NON-NLS-1$
+            // add to the document that a staging table has been added
+            sourceNode.addStagingTable(stagingGroupName);
+            GroupSymbol tempGroup = new GroupSymbol(XMLQueryPlanner.getTempTableName(stagingGroupName));
+        	ResolverUtil.resolveGroup(tempGroup, planEnv.getGlobalMetadata());
+        	Collection<GroupSymbol> temp = Arrays.asList(tempGroup);
+        	List<ElementSymbol> fk = new ArrayList<ElementSymbol>(fkColumns.size());
+        	for (ElementSymbol elementSymbol : fkColumns) {
+        		ElementSymbol es = new ElementSymbol(elementSymbol.getShortName());
+        		ResolverVisitor.resolveLanguageObject(es, temp, planEnv.getGlobalMetadata());
+        		fk.add(es);
+			}
+            ResultSetInfo stagedInfo = planEnv.getStagingTableResultsInfo(stagingGroupName);
+        	stagedInfo.setStagingRoot(stagingRoot);
+        	stagedInfo.setAutoStaged(true);
+        	stagedInfo.setFkColumns(fk);
+        	stagedInfo.setTempTable(tempGroup.getName());
+        	
+        	rsInfo.setAutoStaged(true);
+            return true;
+        }
+
+        //id as mapping class
+        Object metadataID = planEnv.getGlobalMetadata().getGroupID(sourceNode.getResultName());
+        if (RelationalPlanner.isNoCacheGroup(planEnv.getGlobalMetadata(), metadataID, option)) {
+            return false;
+        }
+
+        //id as generated mapping class name
+        metadataID = planEnv.getGlobalMetadata().getGroupID(sourceNode.getActualResultSetName());
+        if (RelationalPlanner.isNoCacheGroup(planEnv.getGlobalMetadata(), metadataID, option)) {
+            return false;
+        }
+
         stagableQuery = (Query)stagableQuery.clone();
-                
+
         // stage the transformation query and it is successful
-        String stagingGroupName = planEnv.getStagedResultName(groupName);         
         if (!XMLQueryPlanner.planStagaingQuery(true, groupName, stagingGroupName, stagableQuery, planEnv)) {
             return false;
         }
         
         // add to the document that a staging table has been added
         sourceNode.addStagingTable(stagingGroupName);
-        
+        ResultSetInfo stagedInfo = planEnv.getStagingTableResultsInfo(stagingGroupName);
+    	stagedInfo.setAutoStaged(true);
+    	stagedInfo.setTempTable(XMLQueryPlanner.getTempTableName(stagingGroupName));
+    	
+    	rsInfo.setAutoStaged(true);
         return true;
     }
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/parser/ParseInfo.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/parser/ParseInfo.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/parser/ParseInfo.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -37,9 +37,6 @@
 	
     public int referenceCount = 0;
 
-	// This gets set according to the current clause
-	public boolean aggregatesAllowed = false;
-        
     // treat a double quoted variable as variable instead of string 
     public boolean ansiQuotedIdentifiers=Boolean.valueOf(System.getProperty("org.teiid.ansiQuotedIdentifiers", Boolean.TRUE.toString())).booleanValue(); //$NON-NLS-1$
     

Modified: branches/as7/engine/src/main/java/org/teiid/query/parser/QueryParser.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/parser/QueryParser.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/parser/QueryParser.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,6 +23,11 @@
 package org.teiid.query.parser;
 
 import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashSet;
+import java.util.List;
 
 import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.query.QueryPlugin;
@@ -186,8 +191,83 @@
     }
 
     private QueryParserException convertParserException(ParseException pe) {
-        return new QueryParserException(QueryPlugin.Util.getString("QueryParser.parsingError", pe.getMessage())); //$NON-NLS-1$                        
+        QueryParserException qpe = new QueryParserException(QueryPlugin.Util.getString("QueryParser.parsingError", getMessage(pe, 1, 10))); //$NON-NLS-1$
+        qpe.setParseException(pe);
+        if (pe.currentToken == null) {
+        	pe.currentToken = parser.token;
+        }
+        return qpe;
     }
+        
+    public static String getMessage(ParseException pe, int maxTokenSequence, int maxExpansions) {
+		if (!pe.specialConstructor) {
+			return pe.getMessage();
+		}
+		StringBuffer expected = new StringBuffer();
+		int[][] expectedTokenSequences = pe.expectedTokenSequences;
+		String[] tokenImage = pe.tokenImage;
+		String eol = pe.eol;
+		Token currentToken = pe.currentToken;
+		HashSet<List<Integer>> expansions = new HashSet<List<Integer>>();
+		Arrays.sort(expectedTokenSequences, new Comparator<int[]>() {
+			@Override
+			public int compare(int[] o1, int[] o2) {
+				return o2.length - o1.length;
+			}
+		});
+		int maxSize = expectedTokenSequences[0].length;
+		StringBuilder retval = new StringBuilder("Encountered \""); //$NON-NLS-1$
+		Token tok = currentToken.next;
+		for (int i = 0; i < maxSize; i++) {
+			if (i != 0)
+				retval.append(" "); //$NON-NLS-1$
+			if (tok.kind == 0) {
+				retval.append(tokenImage[0]);
+				break;
+			}
+			retval.append(pe.add_escapes(tok.image));
+			tok = tok.next;
+		}
+		retval.append("\" at line " + currentToken.next.beginLine + ", column " //$NON-NLS-1$ //$NON-NLS-2$
+				+ currentToken.next.beginColumn);
+		retval.append("." + eol); //$NON-NLS-1$
+		for (int i = 0; i < expectedTokenSequences.length; i++) {
+			boolean truncateStart = expectedTokenSequences[i].length == maxSize && maxSize > 1 && maxSize > maxTokenSequence;
+			int start = 0;
+			if (truncateStart) {
+				start = expectedTokenSequences[i].length - maxTokenSequence;
+			}
+			List<Integer> expansion = new ArrayList<Integer>(Math.min(maxTokenSequence, expectedTokenSequences[i].length));
+			for (int j = start; j < start+maxTokenSequence; j++) {
+				expansion.add(expectedTokenSequences[i][j]);
+			}
+			if (!expansions.add(expansion) || (!truncateStart && expectedTokenSequences[i][start] == currentToken.next.kind)) {
+				continue;
+			}
+			if (expansions.size() > maxExpansions) {
+				expected.append("...").append(eol).append("    "); //$NON-NLS-1$ //$NON-NLS-2$
+				break;
+			}
+			if (truncateStart) {
+				expected.append("... "); //$NON-NLS-1$
+			}
+			for (int j = start; j < expectedTokenSequences[i].length && j < start+maxTokenSequence; j++) {
+				expected.append(tokenImage[expectedTokenSequences[i][j]])
+						.append(" "); //$NON-NLS-1$
+			}
+			if (expectedTokenSequences[i][Math.min(maxTokenSequence, expectedTokenSequences[i].length - 1)] != 0) {
+				expected.append("..."); //$NON-NLS-1$
+			}
+			expected.append(eol).append("    "); //$NON-NLS-1$
+		}
+		if (expansions.size() == 1) {
+			retval.append("Was expecting:" + eol + "    "); //$NON-NLS-1$ //$NON-NLS-2$
+		} else {
+			retval.append("Was expecting one of:" + eol + "    "); //$NON-NLS-1$ //$NON-NLS-2$
+		}
+		retval.append(expected.toString());
+		return retval.toString();
+    }
 
     /**
      * Takes a SQL string representing an SQL expression

Modified: branches/as7/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/parser/SQLParserUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,7 +40,9 @@
 import org.teiid.query.sql.lang.QueryCommand;
 import org.teiid.query.sql.lang.SetQuery;
 import org.teiid.query.sql.lang.ExistsCriteria.SubqueryHint;
+import org.teiid.query.sql.proc.Block;
 import org.teiid.query.sql.proc.CriteriaSelector;
+import org.teiid.query.sql.proc.Statement;
 
 public class SQLParserUtil {
 	
@@ -172,7 +174,13 @@
         for (int i = 0; i < parts.length; i++) {
             if (parts[i].equalsIgnoreCase(Option.OPTIONAL)) {
                 fromClause.setOptional(true);
-            }        
+            } else if (parts[i].equalsIgnoreCase(Option.MAKEDEP)) {
+                fromClause.setMakeDep(true);
+            } else if (parts[i].equalsIgnoreCase(Option.MAKENOTDEP)) {
+                fromClause.setMakeNotDep(true);
+            } else if (parts[i].equalsIgnoreCase(FromClause.MAKEIND)) {
+                fromClause.setMakeInd(true);
+            }       
         }
     }
     
@@ -184,6 +192,8 @@
                 hint.setMergeJoin(true);
             } else if (parts[i].equalsIgnoreCase(SubqueryHint.NOUNNEST)) {
             	hint.setNoUnnest(true);
+            } else if (parts[i].equalsIgnoreCase(SubqueryHint.DJ)) {
+                hint.setDepJoin(true);
             }
         }
     	return hint;
@@ -311,4 +321,14 @@
         return setQuery;
     }
     
+    static Block asBlock(Statement stmt) {
+    	if (stmt == null) {
+    		return null;
+    	}
+    	if (stmt instanceof Block) {
+    		return (Block)stmt;
+    	}
+    	return new Block(stmt);
+    }
+    
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/BatchCollector.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/BatchCollector.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/BatchCollector.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -78,7 +78,7 @@
 		}
 
 		@Override
-		public List<?> nextTuple() throws TeiidComponentException,
+		public List<Object> nextTuple() throws TeiidComponentException,
 				TeiidProcessingException {
 			while (true) {
 				if(sourceBatch == null) {
@@ -104,7 +104,7 @@
 		}
 		
 		@SuppressWarnings("unused")
-		protected List updateTuple(List tuple) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+		protected List<?> updateTuple(List<?> tuple) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
 			return tuple;
 		}
 
@@ -150,7 +150,9 @@
             // Check for termination condition
             if(batch.getTerminationFlag()) {
             	done = true;
-            	buffer.close();
+            	if (!this.sourceNode.hasFinalBuffer()) {
+            		buffer.close();
+            	}
                 break;
             }
         }

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/QueryProcessor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/QueryProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/QueryProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,6 +34,7 @@
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.util.Assertion;
+import org.teiid.jdbc.SQLStates;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.logging.MessageLevel;
@@ -130,7 +131,7 @@
 			
 	        while(currentTime < context.getTimeSliceEnd() || context.isNonBlocking()) {
 	        	if (requestCanceled) {
-	                throw new TeiidProcessingException(QueryPlugin.Util.getString("QueryProcessor.request_cancelled", getProcessID())); //$NON-NLS-1$
+	                throw new TeiidProcessingException(SQLStates.QUERY_CANCELED, QueryPlugin.Util.getString("QueryProcessor.request_cancelled", getProcessID())); //$NON-NLS-1$
 	            }
 	        	if (currentTime > context.getTimeoutEnd()) {
 	        		throw new TeiidProcessingException("Query timed out"); //$NON-NLS-1$
@@ -168,7 +169,7 @@
 		return result;
 	}
 
-	private void init() throws TeiidComponentException, TeiidProcessingException {
+	public void init() throws TeiidComponentException, TeiidProcessingException {
 		// initialize if necessary
 		if(!initialized) {
 			reserved = this.bufferMgr.reserveBuffers(this.bufferMgr.getSchemaSize(this.getOutputElements()), BufferReserveMode.FORCE);
@@ -183,7 +184,6 @@
 		}
 	}
 
-	                   
     /**
      * Close processing and clean everything up.  Should only be called by the same thread that called process.
      */


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/processor/QueryProcessor.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/query/processor/QueryProcessor.java:3220-3275,3340-3349
/trunk/engine/src/main/java/org/teiid/query/processor/QueryProcessor.java:3188-3382

Copied: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BranchingInstruction.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/processor/proc/BranchingInstruction.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BranchingInstruction.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BranchingInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,78 @@
+/*
+ * 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 org.teiid.query.processor.proc;
+
+import org.teiid.client.plan.PlanNode;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.query.sql.proc.BranchingStatement;
+import org.teiid.query.sql.proc.BranchingStatement.BranchingMode;
+
+/**
+ * <p>This {@link ProgramInstruction} continue with the next loop when processed</p>.
+ */
+public class BranchingInstruction extends ProgramInstruction {
+	
+	private BranchingStatement bs;
+	
+    public BranchingInstruction(BranchingStatement bs) {
+    	this.bs = bs;
+	}
+
+	public String toString() {
+        return bs.toString();
+    }
+
+    public void process(ProcedurePlan env) throws TeiidComponentException {
+        Program parentProgram = env.peek();
+        
+        //find the parent program that contains the loop/while instruction
+        while(true){
+        	if (bs.getMode() == BranchingMode.LEAVE && bs.getLabel().equalsIgnoreCase(parentProgram.getLabel())) {
+        		env.pop(true);
+        		break;
+        	}
+            if(parentProgram.getCurrentInstruction() instanceof RepeatedInstruction){
+            	if (bs.getLabel() == null) {
+            		break;
+            	}
+            	RepeatedInstruction ri = (RepeatedInstruction)parentProgram.getCurrentInstruction();
+            	if (bs.getLabel().equalsIgnoreCase(ri.getLabel())) {
+            		break;
+            	}
+            }
+            env.pop(true); 
+            parentProgram = env.peek();
+        } 
+        
+        if (bs.getMode() != BranchingMode.CONTINUE) {
+        	env.incrementProgramCounter();
+        }
+    }
+    
+    public PlanNode getDescriptionProperties() {
+        return new PlanNode(bs.toString());
+    }
+    
+}

Deleted: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BreakInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BreakInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/BreakInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,49 +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 org.teiid.query.processor.proc;
-
-import org.teiid.client.plan.PlanNode;
-import org.teiid.core.TeiidComponentException;
-
-
-/**
- * <p>This {@link ProgramInstruction} break from a loop when processed</p>.
- */
-public class BreakInstruction extends ContinueInstruction {
-
-    public String toString() {
-        return "BREAK INSTRUCTION"; //$NON-NLS-1$
-    }
-
-    public void process(ProcedurePlan env) throws TeiidComponentException {
-        super.process(env);
-        env.incrementProgramCounter();
-    }
-
-    public PlanNode getDescriptionProperties() {
-        return new PlanNode("BREAK"); //$NON-NLS-1$
-    }
-
-}

Deleted: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ContinueInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ContinueInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ContinueInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,55 +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 org.teiid.query.processor.proc;
-
-import org.teiid.client.plan.PlanNode;
-import org.teiid.core.TeiidComponentException;
-
-/**
- * <p>This {@link ProgramInstruction} continue with the next loop when processed</p>.
- */
-public class ContinueInstruction extends ProgramInstruction {
-    public String toString() {
-        return "CONTINUE INSTRUCTION"; //$NON-NLS-1$
-    }
-
-    public void process(ProcedurePlan env) throws TeiidComponentException {
-        Program parentProgram = env.peek();
-        
-        //find the parent program that contains the loop/while instruction
-        while(true){            
-            if(parentProgram.getCurrentInstruction() instanceof RepeatedInstruction){
-                break;
-            }
-            env.pop(); 
-            parentProgram = env.peek();
-        } 
-    }
-    
-    public PlanNode getDescriptionProperties() {
-        return new PlanNode("CONTINUE"); //$NON-NLS-1$
-    }
-    
-}

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ExecDynamicSqlInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ExecDynamicSqlInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ExecDynamicSqlInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,9 +41,11 @@
 import org.teiid.dqp.internal.process.Request;
 import org.teiid.language.SQLConstants.Reserved;
 import org.teiid.logging.LogManager;
+import org.teiid.metadata.Column;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.metadata.TempMetadataStore;
 import org.teiid.query.optimizer.QueryOptimizer;
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
@@ -54,6 +56,7 @@
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.ProcedureReservedWords;
 import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.Create;
 import org.teiid.query.sql.lang.DynamicCommand;
 import org.teiid.query.sql.lang.Insert;
 import org.teiid.query.sql.lang.Query;
@@ -202,13 +205,22 @@
 				}
 			};
 
-            dynamicProgram = new Program();
+            dynamicProgram = new Program(false);
             dynamicProgram.addInstruction(inst);
 
             if (dynamicCommand.getIntoGroup() != null) {
                 String groupName = dynamicCommand.getIntoGroup().getCanonicalName();
                 if (!procEnv.getTempTableStore().getAllTempTables().contains(groupName)) {
-                    procEnv.getTempContext().add(groupName);
+                	//create the temp table in the parent scope
+                	Create create = new Create();
+                	create.setTable(new GroupSymbol(groupName));
+                	for (ElementSymbol es : ((Insert)command).getVariables()) {
+                		Column c = new Column();
+                		c.setName(es.getShortName());
+                		c.setRuntimeType(DataTypeManager.getDataTypeName(es.getType()));
+                		create.getColumns().add(c);
+                	}
+                    procEnv.getDataManager().registerRequest(procEnv.getContext(), create, TempMetadataAdapter.TEMP_MODEL.getName(), null, 0, -1);
                 }
             }
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/LoopInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/LoopInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/LoopInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -45,11 +45,23 @@
     private Program loopProgram;
     
     private List elements;
+    private String label;
     
-    public LoopInstruction(Program loopProgram, String rsName, ProcessorPlan plan) {
+    public LoopInstruction(Program loopProgram, String rsName, ProcessorPlan plan, String label) {
         super(rsName, plan, false);
         this.loopProgram = loopProgram;
+        this.label = label;
     }
+    
+    @Override
+    public String getLabel() {
+    	return label;
+    }
+    
+    @Override
+    public void setLabel(String label) {
+    	this.label = label;
+    }
 
     public void process(ProcedurePlan procEnv) throws TeiidComponentException {
         List currentRow = procEnv.getCurrentRow(rsName); 
@@ -74,7 +86,7 @@
      */
     public LoopInstruction clone(){
         ProcessorPlan clonedPlan = this.plan.clone();
-        return new LoopInstruction((Program)this.loopProgram.clone(), this.rsName, clonedPlan);
+        return new LoopInstruction((Program)this.loopProgram.clone(), this.rsName, clonedPlan, label);
     }
     
     public String toString() {

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ProcedurePlan.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ProcedurePlan.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/ProcedurePlan.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,21 +24,21 @@
 
 import static org.teiid.query.analysis.AnalysisRecord.*;
 
+import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.Stack;
 
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryValidatorException;
 import org.teiid.client.plan.PlanNode;
+import org.teiid.client.xa.XATransactionException;
 import org.teiid.common.buffer.BlockedException;
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.common.buffer.IndexedTupleSource;
@@ -50,7 +50,14 @@
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.util.Assertion;
+import org.teiid.dqp.internal.process.DataTierTupleSource;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.dqp.service.TransactionContext.Scope;
+import org.teiid.events.EventDistributor;
+import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
+import org.teiid.metadata.MetadataRepository;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.metadata.QueryMetadataInterface;
@@ -62,6 +69,7 @@
 import org.teiid.query.processor.QueryProcessor;
 import org.teiid.query.processor.relational.SubqueryAwareEvaluator;
 import org.teiid.query.sql.ProcedureReservedWords;
+import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
@@ -122,9 +130,6 @@
     
     private List outputElements;
     
-    private TempTableStore tempTableStore;
-    
-    private LinkedList<Set<String>> tempContext = new LinkedList<Set<String>>();
 	private SubqueryAwareEvaluator evaluator;
 	
     // Stack of programs, with current program on top
@@ -133,13 +138,19 @@
     private boolean evaluatedParams;
     
     private boolean requiresTransaction = true;
+    
+    private TransactionContext blockContext;
+    private boolean inTxn;
+    /**
+     * Resources cannot be held open across the txn boundary.  This list is a hack at ensuring the resources are closed.
+     */
+    private LinkedList<WeakReference<DataTierTupleSource>> txnTupleSources = new LinkedList<WeakReference<DataTierTupleSource>>();
 
     /**
      * Constructor for ProcedurePlan.
      */
     public ProcedurePlan(Program originalProgram) {
     	this.originalProgram = originalProgram;
-    	this.programs.add(originalProgram);
     	createVariableContext();
     }
     
@@ -154,7 +165,37 @@
         this.bufferMgr = bufferMgr;
         this.batchSize = bufferMgr.getProcessorBatchSize();
         setContext(context.clone());
-        this.dataMgr = dataMgr;
+        this.dataMgr = new ProcessorDataManager() {
+			
+			@Override
+			public TupleSource registerRequest(CommandContext context, Command command,
+					String modelName, String connectorBindingId, int nodeID, int limit)
+					throws TeiidComponentException, TeiidProcessingException {
+				TupleSource ts = parentDataMrg.registerRequest(context, command, modelName, connectorBindingId, nodeID, limit);
+				if (blockContext != null && ts instanceof DataTierTupleSource) {
+					txnTupleSources.add(new WeakReference<DataTierTupleSource>((DataTierTupleSource)ts));
+				}
+				return ts;
+			}
+			
+			@Override
+			public Object lookupCodeValue(CommandContext context, String codeTableName,
+					String returnElementName, String keyElementName, Object keyValue)
+					throws BlockedException, TeiidComponentException,
+					TeiidProcessingException {
+				return parentDataMrg.lookupCodeValue(context, codeTableName, returnElementName, keyElementName, keyValue);
+			}
+			
+			@Override
+			public MetadataRepository getMetadataRepository() {
+				return parentDataMrg.getMetadataRepository();
+			}
+			
+			@Override
+			public EventDistributor getEventDistributor() {
+				return parentDataMrg.getEventDistributor();
+			}
+		};
         this.parentDataMrg = dataMgr;
         if (evaluator == null) {
         	this.evaluator = new SubqueryAwareEvaluator(Collections.emptyMap(), getDataManager(), getContext(), this.bufferMgr);
@@ -178,12 +219,9 @@
         beginBatch = 1;
         batchRows = null;
         lastBatch = false;
-
+        inTxn = false;
         //reset program stack
-        originalProgram.resetProgramCounter();
-        this.tempContext.clear();
         programs.clear();
-    	programs.push(originalProgram);
 		LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "ProcedurePlan reset"); //$NON-NLS-1$
     }
 
@@ -218,8 +256,7 @@
 		            context.setValue(entry.getKey(), value);
 				}
     		}
-    		tempTableStore = new TempTableStore(getContext().getConnectionID());
-    		getContext().setTempTableStore(tempTableStore);
+    		this.push(originalProgram);
     	}
     	this.evaluatedParams = true;
     }
@@ -236,11 +273,28 @@
 			VariableContext context, Object value) {
 		context.setValue(param, value);
 	}
+	
+	@Override
+	public TupleBatch nextBatch() throws BlockedException,
+			TeiidComponentException, TeiidProcessingException {
+		if (blockContext != null && !this.inTxn) {
+			this.getContext().getTransactionServer().resume(blockContext);
+			this.inTxn = true;
+		} 
+		try {
+			return nextBatchDirect();
+		} finally {
+			if (blockContext != null) {
+				this.inTxn = false;
+				this.getContext().getTransactionServer().suspend(blockContext);
+			}
+		}
+	}
 
     /**
      * @see ProcessorPlan#nextBatch()
      */
-    public TupleBatch nextBatch()
+    public TupleBatch nextBatchDirect()
         throws TeiidComponentException, TeiidProcessingException, BlockedException {
 
         // Already returned results?
@@ -261,7 +315,7 @@
         // Next, attempt to return batches if processing completed
         while(! isBatchFull()) {
             // May throw BlockedException and exit here
-            List tuple = this.finalTupleSource.nextTuple();
+            List<?> tuple = this.finalTupleSource.nextTuple();
             if(tuple == null) {
             	if (outParams != null) {
             		VariableContext vc = getCurrentVariableContext();
@@ -311,7 +365,7 @@
             inst = program.getCurrentInstruction();
 	        if (inst == null){
 	        	LogManager.logTrace(org.teiid.logging.LogConstants.CTX_DQP, "Finished program", program); //$NON-NLS-1$
-                this.pop();
+                this.pop(true);
                 continue;
             }
             if (inst instanceof RepeatedInstruction) {
@@ -350,14 +404,19 @@
     			removeResults(rsName);
 			}
         }
-        if(getTempTableStore()!=null) {
-        	getTempTableStore().removeTempTables();
+        while (!programs.isEmpty()) {
+        	try {
+        		pop(false);
+        	} catch (TeiidComponentException e) {
+        		LogManager.logDetail(LogConstants.CTX_DQP, e, "Error closing program"); //$NON-NLS-1$
+        	}
         }
         if (this.evaluator != null) {
         	this.evaluator.close();
         }
-        this.tempTableStore = null;
         this.dataMgr = parentDataMrg;
+        this.txnTupleSources.clear();
+        this.blockContext = null;
     }
 
     public String toString() {
@@ -475,18 +534,19 @@
 		
 		        CommandContext subContext = getContext().clone();
 		        subContext.setVariableContext(this.currentVarContext);
-		        subContext.setTempTableStore(getTempTableStore());
 		        state = new CursorState();
 		        state.processor = new QueryProcessor(command, subContext, this.bufferMgr, this.dataMgr);
 		        state.ts = new BatchIterator(state.processor);
 		        if (procAssignments != null && state.processor.getOutputElements().size() - procAssignments.size() > 0) {
 		        	state.resultsBuffer = bufferMgr.createTupleBuffer(state.processor.getOutputElements().subList(0, state.processor.getOutputElements().size() - procAssignments.size()), getContext().getConnectionID(), TupleSourceType.PROCESSOR);
+		        } else if (this.blockContext != null) {
+		        	state.resultsBuffer = bufferMgr.createTupleBuffer(state.processor.getOutputElements(), getContext().getConnectionID(), TupleSourceType.PROCESSOR);
 		        }
 	            this.currentState = state;
         	}
         	//force execution to the first batch
         	this.currentState.ts.hasNext();
-            if (procAssignments != null) {
+        	if (procAssignments != null) {
             	while (this.currentState.ts.hasNext()) {
             		if (this.currentState.currentRow != null && this.currentState.resultsBuffer != null) {
             			this.currentState.resultsBuffer.addTuple(this.currentState.currentRow.subList(0, this.currentState.resultsBuffer.getSchema().size()));
@@ -511,6 +571,14 @@
             	}
             	this.currentState.resultsBuffer.close();
             	this.currentState.ts = this.currentState.resultsBuffer.createIndexedTupleSource();
+            } else if (this.blockContext != null) {
+            	//process fully in a block transaction
+            	while (this.currentState.ts.hasNext()) {
+            		List<?> tuple = this.currentState.ts.nextTuple();
+        			this.currentState.resultsBuffer.addTuple(tuple);
+            	}
+            	this.currentState.resultsBuffer.close();
+            	this.currentState.ts = this.currentState.resultsBuffer.createIndexedTupleSource();
             }
 	        this.cursorStates.put(rsName.toUpperCase(), this.currentState);
 	        //keep a reference to the tuple source
@@ -523,43 +591,68 @@
     }
     
     /** 
+     * @param success
      * @throws TeiidComponentException 
+     * @throws XATransactionException 
      */
-    public void pop() throws TeiidComponentException {
+    public void pop(boolean success) throws TeiidComponentException {
     	Program program = this.programs.pop();
         if (this.currentVarContext.getParentContext() != null) {
         	this.currentVarContext = this.currentVarContext.getParentContext();
         }
-        Set<String> current = getTempContext();
-
-        Set<String> tempTables = getLocalTempTables();
-
-        tempTables.addAll(current);
-        
-        if (program != originalProgram) {
-        	for (String table : tempTables) {
-	            this.tempTableStore.removeTempTableByName(table);
-	        }
-        }
-        this.tempContext.removeLast();
+    	program.getTempTableStore().removeTempTables();
+    	if (program.startedTxn() && this.blockContext != null) {
+    		TransactionService ts = this.getContext().getTransactionServer();
+    		TransactionContext tc = this.blockContext;
+    		this.blockContext = null;
+    		try {
+	    		if (!inTxn) {
+	    			this.getContext().getTransactionServer().resume(tc);
+	    		}
+	    		for (WeakReference<DataTierTupleSource> ref : txnTupleSources) {
+	    			DataTierTupleSource dtts = ref.get();
+	    			if (dtts != null) {
+	    				dtts.fullyCloseSource();
+	    			}
+	    		}
+	    		this.txnTupleSources.clear();
+	    		if (success) {
+	    			ts.commit(tc);
+	    		} else {
+	    			ts.rollback(tc);
+	    		}
+    		} catch (XATransactionException e) {
+    			throw new TeiidComponentException(e);
+    		}
+    	}
     }
     
-    public void push(Program program) {
-    	program.resetProgramCounter();
+    public void push(Program program) throws XATransactionException {
+    	program.reset(this.getContext().getConnectionID());
+    	TempTableStore tts = getTempTableStore();
+		getContext().setTempTableStore(program.getTempTableStore());
+		program.getTempTableStore().setParentTempTableStore(tts);
         this.programs.push(program);
         VariableContext context = new VariableContext(true);
         context.setParentContext(this.currentVarContext);
         this.currentVarContext = context;
         
-        Set<String> current = getTempContext();
-        
-        Set<String> tempTables = getLocalTempTables();
-        
-        current.addAll(tempTables);
-        this.tempContext.add(new HashSet<String>());
+        if (program.isAtomic()) {
+        	TransactionContext tc = this.getContext().getTransactionContext();
+        	if (tc != null && tc.getTransactionType() == Scope.NONE) {
+        		//start a transaction
+        		this.getContext().getTransactionServer().begin(tc);
+        		this.inTxn = true;
+        		this.blockContext = tc;
+        		this.peek().setStartedTxn(true);
+        	}
+        }
     }
     
     public void incrementProgramCounter() throws TeiidComponentException {
+    	if (this.programs.isEmpty()) {
+    		return;
+    	}
         Program program = peek();
         ProgramInstruction instr = program.getCurrentInstruction();
         if (instr instanceof RepeatedInstruction) {
@@ -569,27 +662,7 @@
         peek().incrementProgramCounter();
     }
 
-    /** 
-     * @return
-     */
-    private Set<String> getLocalTempTables() {
-        Set<String> tempTables = this.tempTableStore.getAllTempTables();
-        
-        //determine what was created in this scope
-        for (int i = 0; i < tempContext.size() - 1; i++) {
-            tempTables.removeAll(tempContext.get(i));
-        }
-        return tempTables;
-    }
-
-    public Set<String> getTempContext() {
-        if (this.tempContext.isEmpty()) {
-            tempContext.addLast(new HashSet<String>());
-        }
-        return this.tempContext.getLast();
-    }
-
-    public List getCurrentRow(String rsName) throws TeiidComponentException {
+    public List<?> getCurrentRow(String rsName) throws TeiidComponentException {
         return getCursorState(rsName.toUpperCase()).currentRow;
     }
 
@@ -682,7 +755,10 @@
      * @since 5.5
      */
     public TempTableStore getTempTableStore() {
-        return this.tempTableStore;
+    	if (this.programs.isEmpty()) {
+    		return null;
+    	}
+        return this.peek().getTempTableStore();
     }
 
     boolean evaluateCriteria(Criteria condition) throws BlockedException, TeiidProcessingException, TeiidComponentException {

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/Program.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/Program.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/Program.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,6 +27,8 @@
 
 import org.teiid.client.plan.PlanNode;
 import org.teiid.query.processor.ProcessorPlan;
+import org.teiid.query.sql.proc.Statement.Labeled;
+import org.teiid.query.tempdata.TempTableStore;
 
 
 /**
@@ -34,17 +36,47 @@
  * ProgramInstructions, such as {@link IfInstruction} and {@link WhileInstruction} may 
  * have pointers to sub programs.
  */
-public class Program implements Cloneable {
+public class Program implements Cloneable, Labeled {
 
     private List<ProgramInstruction> programInstructions;
     private int counter = 0;
+    private boolean atomic;
+    private String label;
+    private TempTableStore tempTables;
+    private boolean startedTxn;
 
 	/**
 	 * Constructor for Program.
 	 */
-	public Program() {
-		super();
+	public Program(boolean atomic) {
+		this.atomic = atomic;
 	}
+	
+	public void setStartedTxn(boolean startedTxn) {
+		this.startedTxn = startedTxn;
+	}
+	
+	public boolean startedTxn() {
+		return startedTxn;
+	}
+	
+    @Override
+    public String getLabel() {
+    	return label;
+    }
+    
+    @Override
+    public void setLabel(String label) {
+    	this.label = label;
+    }
+    
+	public boolean isAtomic() {
+		return atomic;
+	}
+	
+	public TempTableStore getTempTableStore() {
+		return tempTables;
+	}
 
     /**
      * Returns the next instruction to be executed, or null if there are
@@ -79,8 +111,10 @@
     /**
      * Resets this program, so it can be run through again.
      */
-    public void resetProgramCounter(){
+    public void reset(String sessionId){
         counter = 0;
+        this.tempTables = new TempTableStore(sessionId);
+        this.startedTxn = false;
     }
 
     int getProgramCounter(){
@@ -115,7 +149,7 @@
      * Produces a deep clone.
      */
     public Object clone(){
-        Program program = new Program();
+        Program program = new Program(atomic);
         program.counter = this.counter;
         
         if (this.programInstructions != null){
@@ -125,7 +159,7 @@
             }
             program.programInstructions = clonedInstructions;
         }
-        
+        program.label = label;
         return program;
     }
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/RepeatedInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/RepeatedInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/RepeatedInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,9 +24,10 @@
 
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.sql.proc.Statement.Labeled;
 
 
-public interface RepeatedInstruction {
+public interface RepeatedInstruction extends Labeled {
     
     public boolean testCondition(ProcedurePlan procEnv) throws TeiidComponentException, TeiidProcessingException;
     

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/proc/WhileInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/proc/WhileInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/proc/WhileInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,11 +43,23 @@
 
     // criteria for the while block
     private Criteria condition;
+    private String label;
 
-    public WhileInstruction(Program program, Criteria condition){
+    public WhileInstruction(Program program, Criteria condition, String label){
         this.whileProgram = program;
         this.condition = condition;
+        this.label = label;
     }
+    
+    @Override
+    public String getLabel() {
+    	return label;
+    }
+    
+    @Override
+    public void setLabel(String label) {
+    	this.label = label;
+    }
 
     public void process(ProcedurePlan env) throws TeiidComponentException {
         //do nothing
@@ -61,7 +73,7 @@
      * Returns a deep clone
      */
     public WhileInstruction clone(){
-        return new WhileInstruction((Program)this.whileProgram.clone(), this.condition);
+        return new WhileInstruction((Program)this.whileProgram.clone(), this.condition, this.label);
     }
 
     public String toString() {

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/AccessNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,6 +26,8 @@
 
 import java.util.ArrayList;
 import java.util.Collections;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
 import java.util.List;
 
 import org.teiid.api.exception.query.QueryValidatorException;
@@ -43,6 +45,14 @@
 import org.teiid.query.processor.ProcessorDataManager;
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.util.CommandContext;
 
 
@@ -63,6 +73,10 @@
     private int reserved;
     private int schemaSize;
     
+    private Object[] projection;
+    private List<SelectSymbol> originalSelect;
+	private Object modelId;
+    
     protected AccessNode() {
 		super();
 	}
@@ -93,6 +107,14 @@
     public Command getCommand() {
         return this.command;
     }
+    
+    public void setModelId(Object id) {
+    	this.modelId = id;
+    }
+    
+    public Object getModelId() {
+    	return this.modelId;
+    }
 
 	public void setModelName(String name) {
 		this.modelName = name;
@@ -136,7 +158,72 @@
 			//We hardcode an upper limit on currency because these commands have potentially large in-memory value sets
         } while (!processCommandsIndividually() && hasNextCommand() && this.tupleSources.size() < Math.min(MAX_CONCURRENT, this.getContext().getUserRequestSourceConcurrency()));
 	}
+	
+	public boolean isShouldEvaluate() {
+		return shouldEvaluate;
+	}
 
+	public void minimizeProject(Command atomicCommand) {
+		if (!(atomicCommand instanceof Query)) {
+			return;
+		}
+		Query query = (Query)atomicCommand;
+		Select select = query.getSelect();
+		List<SelectSymbol> symbols = select.getSymbols();
+		if (symbols.size() == 1) {
+			return;
+		}
+		boolean shouldProject = false;
+		LinkedHashMap<Expression, Integer> uniqueSymbols = new LinkedHashMap<Expression, Integer>();
+		projection = new Object[symbols.size()];
+		this.originalSelect = new ArrayList<SelectSymbol>(query.getSelect().getSymbols());
+		int i = 0;
+		int j = 0;
+		for (Iterator<SelectSymbol> iter = symbols.iterator(); iter.hasNext(); ) {
+			SingleElementSymbol ss = (SingleElementSymbol) iter.next();
+			Expression ex = SymbolMap.getExpression(ss);
+			if (ex instanceof Constant) {
+				projection[i] = ex;
+				if (iter.hasNext() || j!=0) {
+					iter.remove();
+					shouldProject = true;
+				} else {
+					projection[i] = j++;
+				}
+			} else {
+				Integer index = uniqueSymbols.get(ex);
+				if (index == null) {
+					uniqueSymbols.put(ex, j);
+					index = j++;
+				} else {
+					iter.remove();
+					shouldProject = true;
+				}
+				projection[i] = index;
+			}
+			i++;
+		}
+		if (!shouldProject) {
+			this.projection = new Object[0];
+		} else if (query.getOrderBy() != null) {
+			for (OrderByItem item : query.getOrderBy().getOrderByItems()) {
+				Integer index = uniqueSymbols.get(SymbolMap.getExpression(item.getSymbol()));
+				if (index != null) {
+					item.setExpressionPosition(index);
+					item.setSymbol((SingleElementSymbol) select.getSymbols().get(index));
+				}
+			}
+		}
+	}
+	
+	public List<SelectSymbol> getOriginalSelect() {
+		return originalSelect;
+	}
+	
+	public Object[] getProjection() {
+		return projection;
+	}
+
 	static void rewriteAndEvaluate(Command atomicCommand, Evaluator eval, CommandContext context, QueryMetadataInterface metadata)
 			throws TeiidProcessingException, TeiidComponentException {
 		try {
@@ -183,6 +270,17 @@
 	        		
 	        		while ((tuple = tupleSource.nextTuple()) != null) {
 	                    returnedRows = true;
+	                    if (this.projection != null && this.projection.length > 0) {
+	                    	List<Object> newTuple = new ArrayList<Object>(this.projection.length);
+	                    	for (Object object : this.projection) {
+								if (object instanceof Integer) {
+									newTuple.add(tuple.get((Integer)object));
+								} else {
+									newTuple.add(((Constant)object).getValue());
+								}
+							}
+	                    	tuple = newTuple;
+	                    }
 	                    addBatchRow(tuple);
 	                    
 	                    if (isBatchFull()) {
@@ -217,7 +315,7 @@
         	}
         	
         	if (!this.tupleSources.isEmpty()) {
-        		throw BlockedException.INSTANCE;
+        		throw BlockedException.block(getContext().getRequestId(), "Blocking on source request(s)."); //$NON-NLS-1$
         	}
         }
         
@@ -246,6 +344,10 @@
 
 	private void registerRequest(Command atomicCommand)
 			throws TeiidComponentException, TeiidProcessingException {
+		if (shouldEvaluate) {
+			projection = null;
+			minimizeProject(atomicCommand);
+		}
 		int limit = -1;
 		if (getParent() instanceof LimitNode) {
 			LimitNode parent = (LimitNode)getParent();
@@ -295,8 +397,13 @@
 	protected void copy(AccessNode source, AccessNode target){
 		super.copy(source, target);
 		target.modelName = source.modelName;
+		target.modelId = source.modelId;
 		target.connectorBindingId = source.connectorBindingId;
 		target.shouldEvaluate = source.shouldEvaluate;
+		if (!source.shouldEvaluate) {
+			target.projection = source.projection;
+			target.originalSelect = source.originalSelect;
+		}
 		target.command = source.command;
 	}
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentCriteriaProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -51,6 +51,7 @@
 import org.teiid.query.sql.lang.SetCriteria;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.util.ValueIterator;
 
 
@@ -87,18 +88,21 @@
         public void sort() throws BlockedException,
                    TeiidComponentException, TeiidProcessingException {
             if (dvs == null) {
-            	//TODO: detect if we're already distinct
-            	if (sortUtility == null) {
-            		List<Expression> sortSymbols = new ArrayList<Expression>(dependentSetStates.size());
-	                List<Boolean> sortDirection = new ArrayList<Boolean>(sortSymbols.size());
-	                for (int i = 0; i < dependentSetStates.size(); i++) {
-	                    sortDirection.add(Boolean.valueOf(OrderBy.ASC));
-	                    sortSymbols.add(dependentSetStates.get(i).valueExpression);
-	                }
-	                DependentValueSource originalVs = (DependentValueSource)dependentNode.getContext().getVariableContext().getGlobalValue(valueSource);
-	                this.sortUtility = new SortUtility(originalVs.getTupleBuffer().createIndexedTupleSource(), sortSymbols, sortDirection, Mode.DUP_REMOVE, dependentNode.getBufferManager(), dependentNode.getConnectionID(), originalVs.getTupleBuffer().getSchema());
-            	}
-            	dvs = new DependentValueSource(sortUtility.sort());
+                DependentValueSource originalVs = (DependentValueSource)dependentNode.getContext().getVariableContext().getGlobalValue(valueSource);
+                if (!originalVs.isDistinct()) {
+	            	if (sortUtility == null) {
+	            		List<SingleElementSymbol> sortSymbols = new ArrayList<SingleElementSymbol>(dependentSetStates.size());
+		                List<Boolean> sortDirection = new ArrayList<Boolean>(sortSymbols.size());
+		                for (int i = 0; i < dependentSetStates.size(); i++) {
+		                    sortDirection.add(Boolean.valueOf(OrderBy.ASC));
+		                    sortSymbols.add((SingleElementSymbol)dependentSetStates.get(i).valueExpression);
+		                }
+		                this.sortUtility = new SortUtility(originalVs.getTupleBuffer().createIndexedTupleSource(), sortSymbols, sortDirection, Mode.DUP_REMOVE, dependentNode.getBufferManager(), dependentNode.getConnectionID(), originalVs.getTupleBuffer().getSchema());
+	            	}
+	            	dvs = new DependentValueSource(sortUtility.sort());
+                } else {
+                	dvs = originalVs;
+                }
             	for (SetState setState : dependentSetStates) {
                     setState.valueIterator = dvs.getValueIterator(setState.valueExpression);
                     if (setState.maxNdv > 0 && setState.maxNdv < dvs.getTupleBuffer().getRowCount()) {
@@ -363,8 +367,10 @@
         return hasNextCommand;
     }
     
-    public Criteria replaceDependentCriteria(AbstractSetCriteria crit, SetState state) {
+    public Criteria replaceDependentCriteria(AbstractSetCriteria crit, SetState state) throws TeiidComponentException {
     	if (state.overMax) {
+            DependentValueSource originalVs = (DependentValueSource)dependentNode.getContext().getVariableContext().getGlobalValue(((DependentSetCriteria)crit).getContextSymbol());
+            originalVs.setUnused(true);
     		return QueryRewriter.TRUE_CRITERIA;
     	}
     	if (state.replacement.isEmpty()) {

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/DependentValueSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -48,6 +48,8 @@
 
     private TupleBuffer buffer;
     private Map<Expression, Set<Object>> cachedSets;
+    private boolean unused; //TODO: use this value instead of the context
+    private boolean distinct;
     
     public DependentValueSource(TupleBuffer tupleSourceID) {
         this.buffer = tupleSourceID;
@@ -105,5 +107,23 @@
     	}
     	return result;
     }
+    
+    @Override
+    public boolean isUnused() {
+		return unused;
+	}
+    
+    @Override
+    public void setUnused(boolean unused) {
+		this.unused = unused;
+	}
+    
+    public boolean isDistinct() {
+		return distinct;
+	}
+    
+    public void setDistinct(boolean distinct) {
+		this.distinct = distinct;
+	}
            
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/EnhancedSortMergeJoinStrategy.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -55,6 +55,8 @@
  */
 public class EnhancedSortMergeJoinStrategy extends MergeJoinStrategy {
 	
+	private boolean semiDep;
+	
 	private TupleSource currentSource;
 	private SourceState sortedSource;
 	private SourceState notSortedSource;
@@ -65,6 +67,7 @@
 	private int[] reverseIndexes;
 	private List<?> sortedTuple;
 	private boolean repeatedMerge;
+	private boolean validSemiDep;
 	
 	/**
 	 * Number of index batches we'll allow to marked as prefers memory regardless of buffer space
@@ -224,6 +227,17 @@
         	this.sortedSource = this.leftSource;
         	this.notSortedSource = this.rightSource;
 
+    		if (semiDep && this.leftSource.isDistinct()) {
+    			this.rightSource.getTupleBuffer();
+    			if (!this.joinNode.getDependentValueSource().isUnused()) {
+    				//sort is not needed
+    				this.processingSortRight = SortOption.NOT_SORTED;
+    				this.validSemiDep = true;
+    				//TODO: this requires full buffering and performs an unnecessary projection
+    				return;
+    			}
+        	}
+
         	if (!repeatedMerge) {
         		createIndex(this.leftSource, this.processingSortLeft == SortOption.ALREADY_SORTED);
         	} else {
@@ -295,6 +309,12 @@
 	    		if (currentTuple == null) {
 	    			return;
 	    		}
+	    		if (validSemiDep) {
+	    			List<?> tuple = this.currentTuple;
+	    			this.currentTuple = null;
+	    			this.joinNode.addBatchRow(outputTuple(this.leftSource.getOuterVals(), tuple));
+	    			continue;
+	    		}
 	        	List<?> key = RelationalNode.projectTuple(this.notSortedSource.getExpressionIndexes(), this.currentTuple);
 	        	tb = new TupleBrowser(this.index, new CollectionTupleSource(Arrays.asList(key).iterator()), OrderBy.ASC);
 	    	}
@@ -319,12 +339,18 @@
     
     @Override
     public EnhancedSortMergeJoinStrategy clone() {
-    	return new EnhancedSortMergeJoinStrategy(this.sortLeft, this.sortRight);
+    	EnhancedSortMergeJoinStrategy clone = new EnhancedSortMergeJoinStrategy(this.sortLeft, this.sortRight);
+    	clone.semiDep = this.semiDep;
+    	return clone;
     }
     
     @Override
     public String getName() {
-    	return "ENHANCED SORT JOIN"; //$NON-NLS-1$
+    	return "ENHANCED SORT JOIN" + (semiDep?" [SEMI]":""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
     }
+    
+    public void setSemiDep(boolean semiDep) {
+		this.semiDep = semiDep;
+	}
        	
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/GroupingNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,12 +22,10 @@
 
 package org.teiid.query.processor.relational;
 
-import static org.teiid.query.analysis.AnalysisRecord.PROP_GROUP_COLS;
-import static org.teiid.query.analysis.AnalysisRecord.PROP_SORT_MODE;
+import static org.teiid.query.analysis.AnalysisRecord.*;
 
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.List;
 import java.util.ListIterator;
 import java.util.Map;
@@ -42,6 +40,7 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.language.SortSpecification.NullOrdering;
 import org.teiid.query.eval.Evaluator;
 import org.teiid.query.function.aggregate.AggregateFunction;
 import org.teiid.query.function.aggregate.ArrayAgg;
@@ -56,6 +55,7 @@
 import org.teiid.query.function.aggregate.XMLAgg;
 import org.teiid.query.processor.BatchCollector;
 import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.BatchCollector.BatchProducer;
 import org.teiid.query.processor.relational.SortUtility.Mode;
 import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.lang.OrderByItem;
@@ -65,20 +65,48 @@
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.symbol.TextLine;
 import org.teiid.query.sql.symbol.AggregateSymbol.Type;
+import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.util.CommandContext;
 
 
 public class GroupingNode extends RelationalNode {
 
-    // Grouping columns set by the planner 
-	private List sortElements;
-	private List sortTypes;
+    static class ProjectingTupleSource extends
+			BatchCollector.BatchProducerTupleSource {
+    	
+    	private Evaluator eval;
+    	private List<Expression> collectedExpressions;
+    	
+		ProjectingTupleSource(BatchProducer sourceNode, Evaluator eval, List<Expression> expressions) {
+			super(sourceNode);
+			this.eval = eval;
+			this.collectedExpressions = expressions;
+		}
+
+		@Override
+		protected List<Object> updateTuple(List<?> tuple) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
+			int columns = collectedExpressions.size();
+		    List<Object> exprTuple = new ArrayList<Object>(columns);
+		    for(int col = 0; col<columns; col++) { 
+		        // The following call may throw BlockedException, but all state to this point
+		        // is saved in class variables so we can start over on building this tuple
+		        Object value = eval.evaluate(collectedExpressions.get(col), tuple);
+		        exprTuple.add(value);
+		    }
+		    return exprTuple;
+		}
+	}
+
+	// Grouping columns set by the planner 
+	private List<OrderByItem> orderBy;
 	private boolean removeDuplicates;
+	private SymbolMap outputMapping;
     
     // Collection phase
     private int phase = COLLECTION;
     private Map elementMap;                    // Map of incoming symbol to index in source elements
     private List<Expression> collectedExpressions;         // Collected Expressions
+    private int distinctCols = -1;
        
     // Sort phase
     private SortUtility sortUtility;
@@ -87,12 +115,14 @@
     
     // Group phase
     private AggregateFunction[] functions;
-    private List lastRow;
-	private List currentGroupTuple;
+    private List<?> lastRow;
+	private List<?> currentGroupTuple;
+	private Evaluator eval;
 
     private static final int COLLECTION = 1;
     private static final int SORT = 2;
     private static final int GROUP = 3;
+	private int[] indexes;
 
 	public GroupingNode(int nodeID) {
 		super(nodeID);
@@ -120,19 +150,13 @@
 		this.removeDuplicates = removeDuplicates;
 	}
 
-    /**
-     * Called by the planner to initialize the grouping node.  Set the list of grouping
-     * expressions - these may be either elements or expressions and the list itself may
-     * be null to indicate an implied grouping on all columns
-     * @param groupingElements
-     * @since 4.2
-     */
-    public void setGroupingElements(List groupingElements) {
-        this.sortElements = groupingElements;
-        if(groupingElements != null) {
-            sortTypes = Collections.nCopies(groupingElements.size(), Boolean.valueOf(OrderBy.ASC));
-        }
-    }
+    public void setOrderBy(List<OrderByItem> orderBy) {
+		this.orderBy = orderBy;
+	}
+    
+    public void setOutputMapping(SymbolMap outputMapping) {
+		this.outputMapping = outputMapping;
+	}
 
 	@Override
 	public void initialize(CommandContext context, BufferManager bufferManager,
@@ -144,13 +168,22 @@
 		}
 		
         // Incoming elements and lookup map for evaluating expressions
-        List sourceElements = this.getChildren()[0].getElements();
+        List<SingleElementSymbol> sourceElements = this.getChildren()[0].getElements();
         this.elementMap = createLookupMap(sourceElements);
 
     	// List should contain all grouping columns / expressions as we need those for sorting
-        if(this.sortElements != null) {
-            this.collectedExpressions = new ArrayList<Expression>(this.sortElements.size() + getElements().size());
-            this.collectedExpressions.addAll(sortElements);
+        if(this.orderBy != null) {
+            this.collectedExpressions = new ArrayList<Expression>(this.orderBy.size() + getElements().size());
+            for (OrderByItem item : this.orderBy) {
+            	Expression ex = SymbolMap.getExpression(item.getSymbol());
+                this.collectedExpressions.add(ex);
+			}
+            if (removeDuplicates) {
+            	for (SingleElementSymbol ses : sourceElements) {
+            		collectExpression(SymbolMap.getExpression(ses));
+            	}
+            	distinctCols = collectedExpressions.size();
+            }
         } else {
             this.collectedExpressions = new ArrayList<Expression>(getElements().size());
         }
@@ -158,12 +191,14 @@
         // Construct aggregate function state accumulators
         functions = new AggregateFunction[getElements().size()];
         for(int i=0; i<getElements().size(); i++) {
-            SingleElementSymbol symbol = (SingleElementSymbol)getElements().get(i);
+            Expression symbol = (Expression) getElements().get(i);
+            if (this.outputMapping != null) {
+            	symbol = outputMapping.getMappedExpression((ElementSymbol)symbol);
+            }
             Class<?> outputType = symbol.getType();
             Class<?> inputType = symbol.getType();
             if(symbol instanceof AggregateSymbol) {
                 AggregateSymbol aggSymbol = (AggregateSymbol) symbol;
-                
                 if(aggSymbol.getExpression() == null) {
                     functions[i] = new Count();
                 } else {
@@ -198,7 +233,6 @@
                 		break;                		
                 	default:
                 		functions[i] = new StatsFunction(function);
-                	
                 	}
 
                     if(aggSymbol.isDistinct() && !function.equals(NonReserved.MIN) && !function.equals(NonReserved.MAX)) {
@@ -218,7 +252,7 @@
                 			OrderByItem item = iterator.next();
                 			orderIndecies[iterator.previousIndex()] = collectExpression(item.getSymbol());
                 			element = new ElementSymbol(String.valueOf(iterator.previousIndex()));
-                            element.setType(inputType);
+                            element.setType(item.getSymbol().getType());
                 			schema.add(element);
                 			OrderByItem newItem = item.clone();
                 			newItem.setSymbol(element);
@@ -232,6 +266,9 @@
                 	}
                     functions[i].setExpressionIndex(index);
                 }
+            	if (aggSymbol.getCondition() != null) {
+                	functions[i].setConditionIndex(collectExpression(aggSymbol.getCondition()));
+                }
             } else {
                 functions[i] = new ConstantFunction();
                 functions[i].setExpressionIndex(this.collectedExpressions.indexOf(symbol));
@@ -276,38 +313,39 @@
     }
 	
 	public TupleSource getCollectionTupleSource() {
-		
 		final RelationalNode sourceNode = this.getChildren()[0];
-		
-		return new BatchCollector.BatchProducerTupleSource(sourceNode) {
-			
-			Evaluator eval = new Evaluator(elementMap, getDataManager(), getContext());
-			
-			@Override
-			protected List updateTuple(List tuple) throws ExpressionEvaluationException, BlockedException, TeiidComponentException {
-				int columns = collectedExpressions.size();
-	            List exprTuple = new ArrayList(columns);
-	            for(int col = 0; col<columns; col++) { 
-	                // The following call may throw BlockedException, but all state to this point
-	                // is saved in class variables so we can start over on building this tuple
-	                Object value = eval.evaluate(collectedExpressions.get(col), tuple);
-	                exprTuple.add(value);
-	            }
-	            return exprTuple;
-			}
-		};
-		
+		return new ProjectingTupleSource(sourceNode, eval, collectedExpressions);
 	}
 
     private void collectionPhase() {
-        if(this.sortElements == null) {
+    	eval = new Evaluator(elementMap, getDataManager(), getContext());
+        if(this.orderBy == null) {
             // No need to sort
             this.groupTupleSource = getCollectionTupleSource();
             this.phase = GROUP;
         } else {
-            this.sortUtility = new SortUtility(getCollectionTupleSource(), sortElements,
-                                                sortTypes, removeDuplicates?Mode.DUP_REMOVE_SORT:Mode.SORT, getBufferManager(),
-                                                getConnectionID(), collectedExpressions);
+        	List<NullOrdering> nullOrdering = new ArrayList<NullOrdering>(orderBy.size());
+        	List<Boolean> sortTypes = new ArrayList<Boolean>(orderBy.size());
+        	int size = orderBy.size();
+        	if (this.removeDuplicates) {
+        		//sort on all inputs
+        		size = distinctCols;
+        	}
+        	int[] sortIndexes = new int[size];
+        	for (int i = 0; i < size; i++) {
+        		if (i < this.orderBy.size()) {
+        			OrderByItem item = this.orderBy.get(i);
+        			nullOrdering.add(item.getNullOrdering());
+        			sortTypes.add(item.isAscending());
+        		} else {
+        			nullOrdering.add(null);
+        			sortTypes.add(OrderBy.ASC);
+        		}
+        		sortIndexes[i] = i; 
+        	}
+        	this.indexes = Arrays.copyOf(sortIndexes, orderBy.size());
+            this.sortUtility = new SortUtility(getCollectionTupleSource(), removeDuplicates?Mode.DUP_REMOVE_SORT:Mode.SORT, getBufferManager(),
+                    getConnectionID(), collectedExpressions, sortTypes, nullOrdering, sortIndexes);
             this.phase = SORT;
         }
     }
@@ -333,9 +371,9 @@
                 // First row we've seen
                 lastRow = currentGroupTuple;
 
-            } else if(! sameGroup(currentGroupTuple, lastRow)) {
+            } else if(! sameGroup(indexes, currentGroupTuple, lastRow)) {
                 // Close old group
-                List row = new ArrayList(functions.length);
+                List<Object> row = new ArrayList<Object>(functions.length);
                 for(int i=0; i<functions.length; i++) {
                     row.add( functions[i].getResult() );
                     functions[i].reset();
@@ -355,9 +393,9 @@
             updateAggregates(currentGroupTuple);
             currentGroupTuple = null;
         }
-        if(lastRow != null || sortElements == null) {
+        if(lastRow != null || orderBy == null) {
             // Close last group
-            List row = new ArrayList(functions.length);
+            List<Object> row = new ArrayList<Object>(functions.length);
             for(int i=0; i<functions.length; i++) {
                 row.add( functions[i].getResult() );
             }
@@ -369,17 +407,14 @@
         return pullBatch();
     }
 
-    private boolean sameGroup(List newTuple, List oldTuple) {
-        // Check for no grouping columns
-        if(sortElements == null) {
-            return true;
-        }
+	public static boolean sameGroup(int[] indexes, List<?> newTuple, List<?> oldTuple) {
+		if (indexes == null) {
+			return true;
+		}
+		for(int i=indexes.length-1; i>=0; i--) {
+            Object oldValue = oldTuple.get(indexes[i]);
+            Object newValue = newTuple.get(indexes[i]);
 
-        // Walk backwards through sort cols as the last columns are most likely to be different
-        for(int i=sortElements.size()-1; i>=0; i--) {
-            Object oldValue = oldTuple.get(i);
-            Object newValue = newTuple.get(i);
-
             if(oldValue == null) {
                 if(newValue != null) {
                     return false;
@@ -397,7 +432,7 @@
         return true;
     }
 
-    private void updateAggregates(List tuple)
+    private void updateAggregates(List<?> tuple)
     throws TeiidComponentException, TeiidProcessingException {
 
         for(int i=0; i<functions.length; i++) {
@@ -414,15 +449,18 @@
 
 	protected void getNodeString(StringBuffer str) {
 		super.getNodeString(str);
-		str.append(sortElements);
+		str.append(orderBy);
+		if (outputMapping != null) {
+			str.append(outputMapping);
+		}
 	}
 
 	public Object clone(){
 		GroupingNode clonedNode = new GroupingNode(super.getID());
 		super.copy(this, clonedNode);
-		clonedNode.sortElements = sortElements;
-		clonedNode.sortTypes = sortTypes;
 		clonedNode.removeDuplicates = removeDuplicates;
+		clonedNode.outputMapping = outputMapping;
+		clonedNode.orderBy = orderBy;
 		return clonedNode;
 	}
 
@@ -430,15 +468,14 @@
         // Default implementation - should be overridden
     	PlanNode props = super.getDescriptionProperties();
 
-        if(sortElements != null) {
-            int elements = sortElements.size();
+        if(orderBy != null) {
+            int elements = orderBy.size();
             List<String> groupCols = new ArrayList<String>(elements);
             for(int i=0; i<elements; i++) {
-                groupCols.add(this.sortElements.get(i).toString());
+                groupCols.add(this.orderBy.get(i).toString());
             }
             props.addProperty(PROP_GROUP_COLS, groupCols);
         }
-        
         props.addProperty(PROP_SORT_MODE, String.valueOf(this.removeDuplicates));
 
         return props;

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/JoinNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -75,6 +75,8 @@
     private Map combinedElementMap;
     private int[] projectionIndexes;
     
+    private DependentValueSource dvs;
+    
     public JoinNode(int nodeID) {
         super(nodeID);
     }
@@ -182,7 +184,9 @@
             this.joinStrategy.loadLeft();
             if (isDependent()) { 
                 TupleBuffer buffer = this.joinStrategy.leftSource.getTupleBuffer();
-                this.getContext().getVariableContext().setGlobalValue(this.dependentValueSource, new DependentValueSource(buffer));
+                dvs = new DependentValueSource(buffer);
+                dvs.setDistinct(this.joinStrategy.leftSource.isDistinct());
+                this.getContext().getVariableContext().setGlobalValue(this.dependentValueSource, dvs);
             }
             state = State.LOAD_RIGHT;
         }
@@ -270,13 +274,24 @@
         this.dependentValueSource = dependentValueSource;
     }
     
+    public String getDependentValueSourceName() {
+		return dependentValueSource;
+	}
+    
     public void closeDirect() {
         super.closeDirect();
         joinStrategy.close();
         if (this.getContext() != null && this.dependentValueSource != null) {
         	this.getContext().getVariableContext().setGlobalValue(this.dependentValueSource, null);
         }
+        this.dvs = null;
     }
+    
+    @Override
+    public void reset() {
+    	super.reset();
+    	this.dvs = null;
+    }
 
     public JoinType getJoinType() {
         return this.joinType;
@@ -310,5 +325,9 @@
         	throw BATCH_AVILABLE;
         }
     }
+    
+    public DependentValueSource getDependentValueSource() {
+		return dvs;
+	}
 
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectIntoNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -222,7 +222,7 @@
     	}
         // RESPONSE_PROCESSING: process tuple sources
         if (tupleSourcesProcessed < requestsRegistered) {
-            throw BlockedException.INSTANCE;
+        	throw BlockedException.block(getContext().getRequestId(), "Blocking on insert update count"); //$NON-NLS-1$
         }
                 
     }

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/ProjectNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,7 +22,7 @@
 
 package org.teiid.query.processor.relational;
 
-import static org.teiid.query.analysis.AnalysisRecord.PROP_SELECT_COLS;
+import static org.teiid.query.analysis.AnalysisRecord.*;
 
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -37,26 +37,24 @@
 import org.teiid.common.buffer.TupleBatch;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
-import org.teiid.core.util.Assertion;
-import org.teiid.query.QueryPlugin;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.processor.ProcessorDataManager;
-import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.ExpressionSymbol;
-import org.teiid.query.sql.symbol.SelectSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.util.CommandContext;
 
 
 public class ProjectNode extends SubqueryAwareRelationalNode {
 
-	private List selectSymbols;
+	private List<? extends SingleElementSymbol> selectSymbols;
 
     // Derived element lookup map
     private Map elementMap;
     private boolean needsProject = true;
+    private List<Expression> expressions;
+    private int[] projectionIndexes;
 
     // Saved state when blocked on evaluating a row - must be reset
     private TupleBatch currentBatch;
@@ -81,11 +79,11 @@
      * return List of select symbols
      * @return List of select symbols
      */
-    public List getSelectSymbols() {
+    public List<? extends SingleElementSymbol> getSelectSymbols() {
         return this.selectSymbols;
     }
 
-	public void setSelectSymbols(List symbols) {
+	public void setSelectSymbols(List<? extends SingleElementSymbol> symbols) {
 		this.selectSymbols = symbols;
 	}
 	
@@ -95,56 +93,51 @@
 		super.initialize(context, bufferManager, dataMgr);
 
         // Do this lazily as the node may be reset and re-used and this info doesn't change
-        if(elementMap == null) {
-            //in the case of select with no from, there is no child node
-            //simply return at this point
-            if(this.getChildren()[0] == null){
-                elementMap = new HashMap();
-                return;
-            }
+        if(elementMap != null) {
+        	return;
+        }
+    	this.projectionIndexes = new int[this.selectSymbols.size()];
+    	Arrays.fill(this.projectionIndexes, -1);
+    	
+    	this.expressions = new ArrayList<Expression>(this.selectSymbols.size());
+    	for (SingleElementSymbol ses : this.selectSymbols) {
+			this.expressions.add(SymbolMap.getExpression(ses));
+		}
+        //in the case of select with no from, there is no child node
+        //simply return at this point
+        if(this.getChildren()[0] == null){
+            elementMap = new HashMap();
+            return;
+        }
 
-            // Create element lookup map for evaluating project expressions
-            List childElements = this.getChildren()[0].getElements();
-            this.elementMap = createLookupMap(childElements);
+        // Create element lookup map for evaluating project expressions
+        List childElements = this.getChildren()[0].getElements();
+        this.elementMap = createLookupMap(childElements);
 
-            // Check whether project needed at all - this occurs if:
-            // 1. outputMap == null (see previous block)
-            // 2. project elements are either elements or aggregate symbols (no processing required)
-            // 3. order of input values == order of output values
-            if(childElements.size() > 0) {
-                // Start by assuming project is not needed
-                needsProject = false;
-                
-                if(childElements.size() != getElements().size()) {
-                    needsProject = true;                    
-                } else {
-                    for(int i=0; i<selectSymbols.size(); i++) {
-                        SelectSymbol symbol = (SelectSymbol) selectSymbols.get(i);
-                        
-                        if(symbol instanceof AliasSymbol) {
-                            Integer index = (Integer) elementMap.get(symbol);
-                            if(index != null && index.intValue() == i) {
-                                continue;
-                            }
-                            symbol = ((AliasSymbol)symbol).getSymbol();
-                        }
-    
-                        if(symbol instanceof ElementSymbol || symbol instanceof AggregateSymbol) {
-                            Integer index = (Integer) elementMap.get(symbol);
-                            if(index == null || index.intValue() != i) {
-                                // input / output element order is not the same
-                                needsProject = true;
-                                break;
-                            }
-    
-                        } else {
-                            // project element is either a constant or a function
-                            needsProject = true;
-                            break;
-                        }
-                    }
+        // Check whether project needed at all - this occurs if:
+        // 1. outputMap == null (see previous block)
+        // 2. project elements are either elements or aggregate symbols (no processing required)
+        // 3. order of input values == order of output values
+        needsProject = childElements.size() != getElements().size();
+        for(int i=0; i<selectSymbols.size(); i++) {
+            SingleElementSymbol symbol = selectSymbols.get(i);
+            
+            if(symbol instanceof AliasSymbol) {
+                Integer index = (Integer) elementMap.get(symbol);
+                if(index != null && index.intValue() == i) {
+                	projectionIndexes[i] = index;
+                    continue;
                 }
+                symbol = ((AliasSymbol)symbol).getSymbol();
             }
+
+            Integer index = (Integer) elementMap.get(symbol);
+            if(index == null || index.intValue() != i) {
+                // input / output element order is not the same
+                needsProject = true;
+            } else {
+            	projectionIndexes[i] = index;
+            }
         }
     }
 	
@@ -171,14 +164,14 @@
         }
 
         while (currentRow <= currentBatch.getEndRow() && !isBatchFull()) {
-    		List tuple = currentBatch.getTuple(currentRow);
+    		List<?> tuple = currentBatch.getTuple(currentRow);
 
-			List projectedTuple = new ArrayList(selectSymbols.size());
+			List<Object> projectedTuple = new ArrayList<Object>(selectSymbols.size());
 
 			// Walk through symbols
-            for(int i=0; i<selectSymbols.size(); i++) {
-				SelectSymbol symbol = (SelectSymbol) selectSymbols.get(i);
-				updateTuple(symbol, tuple, projectedTuple);
+            for(int i=0; i<expressions.size(); i++) {
+				Expression symbol = expressions.get(i);
+				updateTuple(symbol, i, tuple, projectedTuple);
 			}
 
             // Add to batch
@@ -196,28 +189,14 @@
     	return pullBatch();
 	}
 
-	private void updateTuple(SelectSymbol symbol, List values, List tuple)
+	private void updateTuple(Expression symbol, int projectionIndex, List<?> values, List<Object> tuple)
 		throws BlockedException, TeiidComponentException, ExpressionEvaluationException {
 
-        if (symbol instanceof AliasSymbol) {
-            // First check AliasSymbol itself
-            Integer index = (Integer) elementMap.get(symbol);
-            if(index != null) {
-                tuple.add(values.get(index.intValue()));
-                return;
-            }   
-            // Didn't find it, so try aliased symbol below
-            symbol = ((AliasSymbol)symbol).getSymbol();
-        }
-        
-        Integer index = (Integer) elementMap.get(symbol);
-        if(index != null) {
-			tuple.add(values.get(index.intValue()));
-        } else if(symbol instanceof ExpressionSymbol) {
-            Expression expression = ((ExpressionSymbol)symbol).getExpression();
-			tuple.add(getEvaluator(this.elementMap).evaluate(expression, values));
-        } else {
-            Assertion.failed(QueryPlugin.Util.getString("ERR.015.006.0034", symbol.getClass().getName())); //$NON-NLS-1$
+        int index = this.projectionIndexes[projectionIndex];
+        if(index != -1) {
+			tuple.add(values.get(index));
+        } else { 
+			tuple.add(getEvaluator(this.elementMap).evaluate(symbol, values));
 		}
 	}
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,6 +24,7 @@
 
 import static org.teiid.query.analysis.AnalysisRecord.*;
 
+import java.util.ArrayList;
 import java.util.List;
 
 import org.teiid.client.plan.PlanNode;
@@ -112,7 +113,10 @@
 		try {
 			while ((tuple = this.outputTs.nextTuple()) != null) {
 				//resize to remove unrelated columns
-				addBatchRow(tuple.subList(0, this.getElements().size()));
+				if (this.getElements().size() < tuple.size()) {
+					tuple = new ArrayList<Object>(tuple.subList(0, this.getElements().size()));
+				}
+				addBatchRow(tuple);
 				if (this.isBatchFull()) {
 					return pullBatch();
 				}

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortUtility.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -45,6 +45,7 @@
 import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.lang.OrderByItem;
 import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
 
 
 /**
@@ -108,19 +109,12 @@
 	private Collection<List<?>> workingTuples;
     
     public SortUtility(TupleSource sourceID, List<OrderByItem> items, Mode mode, BufferManager bufferMgr,
-                        String groupName, List schema) {
-        this.source = sourceID;
-        this.mode = mode;
-        this.bufferManager = bufferMgr;
-        this.groupName = groupName;
-        this.schema = schema;
-        this.schemaSize = bufferManager.getSchemaSize(this.schema);
-        int distinctIndex = items != null? items.size() - 1:0;
+                        String groupName, List<? extends Expression> schema) {
         List<Expression> sortElements = null;
         List<Boolean> sortTypes = null;
         List<NullOrdering> nullOrderings = null;
         if (items == null) {
-    		sortElements = (List<Expression>) this.schema;
+    		sortElements = (List<Expression>) schema;
     		sortTypes = Collections.nCopies(sortElements.size(), OrderBy.ASC);
         } else {
         	sortElements = new ArrayList(items.size());
@@ -147,12 +141,34 @@
             cols[iter.previousIndex()] = schema.indexOf(elem);
             Assertion.assertTrue(cols[iter.previousIndex()] != -1);
         }
+        init(sourceID, mode, bufferMgr, groupName, schema, sortTypes,
+				nullOrderings, cols);
+    }
+    
+    public SortUtility(TupleSource sourceID, Mode mode, BufferManager bufferMgr,
+			String groupName, List<? extends Expression> schema,
+			List<Boolean> sortTypes, List<NullOrdering> nullOrderings,
+			int[] cols) {
+    	init(sourceID, mode, bufferMgr, groupName, schema, sortTypes, nullOrderings, cols);
+    }
+
+	private void init(TupleSource sourceID, Mode mode, BufferManager bufferMgr,
+			String groupName, List<? extends Expression> schema,
+			List<Boolean> sortTypes, List<NullOrdering> nullOrderings,
+			int[] cols) {
+		this.source = sourceID;
+        this.mode = mode;
+        this.bufferManager = bufferMgr;
+        this.groupName = groupName;
+        this.schema = schema;
+        this.schemaSize = bufferManager.getSchemaSize(this.schema);
         this.comparator = new ListNestedSortComparator(cols, sortTypes);
+        int distinctIndex = cols.length - 1;
         this.comparator.setDistinctIndex(distinctIndex);
         this.comparator.setNullOrdering(nullOrderings);
     }
     
-    public SortUtility(TupleSource ts, List expressions, List<Boolean> types,
+    public SortUtility(TupleSource ts, List<? extends SingleElementSymbol> expressions, List<Boolean> types,
 			Mode mode, BufferManager bufferManager, String connectionID, List schema) {
 		this(ts, new OrderBy(expressions, types).getOrderByItems(), mode, bufferManager, connectionID, schema);
 	}

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SortingFilter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -158,4 +158,9 @@
         // Return
         return this.proxy.getResult();
     }
+    
+    @Override
+    public boolean respectsNull() {
+    	return this.proxy.respectsNull();
+    }
 }


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/SubqueryAwareEvaluator.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/TextTableNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/TextTableNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/TextTableNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -51,9 +51,6 @@
 /**
  * Handles text file processing.
  * 
- * TODO: unix style escape handling \t \n, etc. - see also the unescape function
- * TODO: allow for escaping with fixed parsing
- * TODO: allow for fixed parsing without new lines
  * TODO: allow for a configurable line terminator
  */
 public class TextTableNode extends SubqueryAwareRelationalNode {
@@ -211,14 +208,21 @@
 					if (eof) {
 						return null;
 					}
-					continue; //skip empty lines
+					if (table.isUsingRowDelimiter()) {
+						continue; //skip empty lines
+					}
 				}
-			    if (exact && sb.length() < lineWidth) {
-			    	throw new TeiidProcessingException(QueryPlugin.Util.getString("TextTableNode.invalid_width", sb.length(), lineWidth, textLine, systemId)); //$NON-NLS-1$
-			    }
-				return sb.toString();
+				if (table.isUsingRowDelimiter()) {
+				    if (exact && sb.length() < lineWidth) {
+				    	throw new TeiidProcessingException(QueryPlugin.Util.getString("TextTableNode.invalid_width", sb.length(), lineWidth, textLine, systemId)); //$NON-NLS-1$
+				    }
+					return sb.toString();
+				}
 		    }
 		    sb.append(c);
+		    if (exact && sb.length() == maxLength && !table.isUsingRowDelimiter()) {
+		    	return sb.toString();
+		    }
 		    if (sb.length() > maxLength) {
 		    	if (exact) {
 		    		sb.deleteCharAt(sb.length() - 1);
@@ -433,7 +437,7 @@
 		int beginIndex = 0;
 		for (TextColumn col : table.getColumns()) {
 			String val = new String(line.substring(beginIndex, beginIndex + col.getWidth()));
-			addValue(result, false, val);
+			addValue(result, col.isNoTrim(), val);
 			beginIndex += col.getWidth();
 		}
 		return result;

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/UnionAllNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -129,7 +129,7 @@
             
         } else if(activeSources > 0) {
             // Didn't get a batch but there are active sources so we are blocked
-            throw BlockedException.INSTANCE;
+        	throw BlockedException.block(getContext().getRequestId(), "Blocking on union source."); //$NON-NLS-1$
         } else {
             // No batch and no active sources - return empty termination batch (should never happen but just in case)
             outputBatch = new TupleBatch(outputRow, Collections.EMPTY_LIST);

Copied: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/WindowFunctionProjectNode.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/processor/relational/WindowFunctionProjectNode.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/WindowFunctionProjectNode.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/WindowFunctionProjectNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,547 @@
+/*
+ * 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 org.teiid.query.processor.relational;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.teiid.api.exception.query.ExpressionEvaluationException;
+import org.teiid.api.exception.query.FunctionExecutionException;
+import org.teiid.common.buffer.BlockedException;
+import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.IndexedTupleSource;
+import org.teiid.common.buffer.STree;
+import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.TupleSource;
+import org.teiid.common.buffer.BufferManager.TupleSourceType;
+import org.teiid.common.buffer.STree.InsertMode;
+import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.language.SortSpecification.NullOrdering;
+import org.teiid.query.eval.Evaluator;
+import org.teiid.query.function.aggregate.AggregateFunction;
+import org.teiid.query.function.aggregate.ArrayAgg;
+import org.teiid.query.function.aggregate.Avg;
+import org.teiid.query.function.aggregate.Count;
+import org.teiid.query.function.aggregate.Max;
+import org.teiid.query.function.aggregate.Min;
+import org.teiid.query.function.aggregate.RankingFunction;
+import org.teiid.query.function.aggregate.StatsFunction;
+import org.teiid.query.function.aggregate.Sum;
+import org.teiid.query.function.aggregate.TextAgg;
+import org.teiid.query.function.aggregate.XMLAgg;
+import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.processor.relational.GroupingNode.ProjectingTupleSource;
+import org.teiid.query.processor.relational.SortUtility.Mode;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.lang.OrderByItem;
+import org.teiid.query.sql.symbol.AggregateSymbol;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.WindowFunction;
+import org.teiid.query.sql.symbol.WindowSpecification;
+import org.teiid.query.sql.symbol.AggregateSymbol.Type;
+import org.teiid.query.sql.util.SymbolMap;
+import org.teiid.query.util.CommandContext;
+
+
+public class WindowFunctionProjectNode extends SubqueryAwareRelationalNode {
+	
+	private static final List<Integer> SINGLE_VALUE_ID = Arrays.asList(0);
+
+	private enum Phase {
+		COLLECT,
+		PROCESS,
+		OUTPUT
+	}
+	
+	private static class WindowFunctionInfo {
+		WindowFunction function;
+		int expressionIndex = -1;
+		int conditionIndex = -1;
+		int outputIndex;
+	}
+	
+	private static class WindowSpecificationInfo {
+		List<Integer> groupIndexes = new ArrayList<Integer>();
+		List<Integer> sortIndexes = new ArrayList<Integer>();
+		List<NullOrdering> nullOrderings = new ArrayList<NullOrdering>();
+		List<Boolean> orderType = new ArrayList<Boolean>();
+		List<WindowFunctionInfo> functions = new ArrayList<WindowFunctionInfo>();
+		List<WindowFunctionInfo> rowValuefunctions = new ArrayList<WindowFunctionInfo>();
+	}
+	
+	private LinkedHashMap<WindowSpecification, WindowSpecificationInfo> windows = new LinkedHashMap<WindowSpecification, WindowSpecificationInfo>();
+	private LinkedHashMap<Expression, Integer> expressionIndexes;
+	private LinkedHashMap<Integer, Integer> passThrough = new LinkedHashMap<Integer, Integer>();
+	
+	private Map elementMap;
+	
+	//processing state
+	private Phase phase = Phase.COLLECT;
+	private TupleBuffer tb;
+	private TupleSource inputTs;
+	private STree[] partitionMapping;
+	private STree[] valueMapping;
+	private STree[] rowValueMapping;
+	private IndexedTupleSource outputTs;
+	
+	public WindowFunctionProjectNode(int nodeId) {
+		super(nodeId);
+	}
+	
+	protected WindowFunctionProjectNode() {
+	}
+	
+	@Override
+	public void reset() {
+		super.reset();
+		this.tb = null;
+		this.inputTs = null;
+		this.phase = Phase.COLLECT;
+		this.partitionMapping = null;
+		this.valueMapping = null;
+		this.rowValueMapping = null;
+		this.outputTs = null;
+	}
+	
+	@Override
+	public void closeDirect() {
+		if (tb != null) {
+			tb.remove();
+			tb = null;
+		}
+		removeMappings(partitionMapping);
+		partitionMapping = null;
+		removeMappings(valueMapping);
+		valueMapping = null;
+		removeMappings(rowValueMapping);
+		rowValueMapping = null;
+	}
+
+	private void removeMappings(STree[] mappings) {
+		if (mappings != null) {
+			for (STree tree : mappings) {
+				if (tree != null) {
+					tree.remove();
+				}
+			}
+		}
+	}
+	
+	public Object clone(){
+		WindowFunctionProjectNode clonedNode = new WindowFunctionProjectNode();
+        this.copy(this, clonedNode);
+        clonedNode.windows = windows;
+        clonedNode.expressionIndexes = expressionIndexes;
+        clonedNode.passThrough = passThrough;
+		return clonedNode;
+	}
+	
+	/**
+	 * This state can be determined prior to initialize and is the same for all nodes,
+	 * so it is moved into it's own init routine
+	 */
+	public void init() {
+		expressionIndexes = new LinkedHashMap<Expression, Integer>();
+		for (int i = 0; i < getElements().size(); i++) {
+			Expression ex = SymbolMap.getExpression((Expression) getElements().get(i));
+			if (ex instanceof WindowFunction) {
+				WindowFunction wf = (WindowFunction)ex;
+				WindowSpecification ws = wf.getWindowSpecification();
+				WindowSpecificationInfo wsi = windows.get(ws);
+				if (wsi == null) {
+					wsi = new WindowSpecificationInfo();
+					windows.put(wf.getWindowSpecification(), wsi);
+					if (ws.getPartition() != null) {
+						for (Expression ex1 : ws.getPartition()) {
+							Integer index = getIndex(ex1);
+							wsi.groupIndexes.add(index);
+							wsi.orderType.add(OrderBy.ASC);
+							wsi.nullOrderings.add(null);
+						}
+					}
+					if (ws.getOrderBy() != null) {
+						for (OrderByItem item : ws.getOrderBy().getOrderByItems()) {
+							Expression ex1 = SymbolMap.getExpression(item.getSymbol());
+							Integer index = getIndex(ex1);
+							wsi.sortIndexes.add(index);
+							wsi.orderType.add(item.isAscending());
+							wsi.nullOrderings.add(item.getNullOrdering());
+						}
+					}
+				}
+				WindowFunctionInfo wfi = new WindowFunctionInfo();
+				wfi.function = wf;
+				ex = wf.getFunction().getExpression();
+				if (ex != null) {
+					wfi.expressionIndex = getIndex(ex);
+				}
+				if (wf.getFunction().getCondition() != null) {
+					ex = wf.getFunction().getCondition();
+					wfi.conditionIndex = getIndex(ex);
+				}
+				wfi.outputIndex = i;
+				if (wf.getFunction().getAggregateFunction() == Type.ROW_NUMBER) {
+					wsi.rowValuefunctions.add(wfi);
+				} else {
+					wsi.functions.add(wfi);
+				}
+			} else {
+				int index = getIndex(ex);
+				passThrough.put(i, index);
+			}
+		}
+	}
+
+	@Override
+	protected TupleBatch nextBatchDirect() throws BlockedException,
+			TeiidComponentException, TeiidProcessingException {
+		
+		if (phase == Phase.COLLECT) {
+			saveInput();
+			phase = Phase.PROCESS;
+			partitionMapping = new STree[this.windows.size()];
+			valueMapping = new STree[this.windows.size()];
+			rowValueMapping = new STree[this.windows.size()];
+		}
+		
+		if (phase == Phase.PROCESS) {
+			buildResults();
+			phase = Phase.OUTPUT;
+		}
+		
+		if (phase == Phase.OUTPUT) {
+			if (outputTs == null) {
+				outputTs = tb.createIndexedTupleSource(true);
+			}
+			while (outputTs.hasNext()) {
+				List<?> tuple = outputTs.nextTuple();
+				int rowId = (Integer)tuple.get(tuple.size() - 1);
+				int size = getElements().size();
+				ArrayList<Object> outputRow = new ArrayList<Object>(size);
+				for (int i = 0; i < size; i++) {
+					outputRow.add(null);
+				}
+				for (Map.Entry<Integer, Integer> entry : passThrough.entrySet()) {
+					outputRow.set(entry.getKey(), tuple.get(entry.getValue()));
+				}
+				List<Map.Entry<WindowSpecification, WindowSpecificationInfo>> specs = new ArrayList<Map.Entry<WindowSpecification,WindowSpecificationInfo>>(windows.entrySet());
+				for (int specIndex = 0; specIndex < specs.size(); specIndex++) {
+					Map.Entry<WindowSpecification, WindowSpecificationInfo> entry = specs.get(specIndex);
+					List<?> idRow = Arrays.asList(rowId);
+					List<WindowFunctionInfo> functions = entry.getValue().rowValuefunctions;
+					if (!functions.isEmpty()) {
+						List<?> valueRow = rowValueMapping[specIndex].find(idRow);
+						for (int i = 0; i < functions.size(); i++) {
+							WindowFunctionInfo wfi = functions.get(i);
+							outputRow.set(wfi.outputIndex, valueRow.get(i+1));
+						}
+					}
+					functions = entry.getValue().functions;
+					if (!functions.isEmpty()) {
+						if (partitionMapping[specIndex] != null) {
+							idRow = partitionMapping[specIndex].find(idRow);
+							idRow = idRow.subList(1, 2);
+						} else {
+							idRow = SINGLE_VALUE_ID;
+						}
+						List<?> valueRow = valueMapping[specIndex].find(idRow);
+						for (int i = 0; i < functions.size(); i++) {
+							WindowFunctionInfo wfi = functions.get(i);
+							outputRow.set(wfi.outputIndex, valueRow.get(i+1));
+						}
+					}
+				}
+				this.addBatchRow(outputRow);
+				if (this.isBatchFull()) {
+					return pullBatch();
+				}
+			}
+			terminateBatches();
+		}
+		return this.pullBatch();
+	}
+
+	/**
+	 * Build the results by maintaining indexes that either map
+	 * rowid->values
+	 * or
+	 * rowid->partitionid and partitionid->values
+	 * 
+	 * TODO use the size hint for tree balancing
+	 */
+	private void buildResults() throws TeiidComponentException,
+			TeiidProcessingException, FunctionExecutionException,
+			ExpressionEvaluationException {
+		List<Map.Entry<WindowSpecification, WindowSpecificationInfo>> specs = new ArrayList<Map.Entry<WindowSpecification,WindowSpecificationInfo>>(windows.entrySet());
+		for (int specIndex = 0; specIndex < specs.size(); specIndex++) {
+			Map.Entry<WindowSpecification, WindowSpecificationInfo> entry = specs.get(specIndex);
+			WindowSpecificationInfo info = entry.getValue();
+			IndexedTupleSource specificationTs = tb.createIndexedTupleSource();
+			boolean multiGroup = false;
+			int[] partitionIndexes = null;
+			int[] orderIndexes = null;
+
+			//if there is partitioning or ordering, then sort
+			if (!info.orderType.isEmpty()) {
+				multiGroup = true;
+				int[] sortKeys = new int[info.orderType.size()];
+				int i = 0;
+				if (!info.groupIndexes.isEmpty()) {
+					for (Integer sortIndex : info.groupIndexes) {
+						sortKeys[i++] = sortIndex;
+					}
+					partitionIndexes = Arrays.copyOf(sortKeys, info.groupIndexes.size());
+				}
+				if (!info.sortIndexes.isEmpty()) {
+					for (Integer sortIndex : info.sortIndexes) {
+						sortKeys[i++] = sortIndex;
+					}
+					orderIndexes = Arrays.copyOfRange(sortKeys, info.groupIndexes.size(), info.groupIndexes.size() + info.sortIndexes.size());
+				}
+				if (!info.functions.isEmpty()) {
+					ElementSymbol key = new ElementSymbol("rowId"); //$NON-NLS-1$
+					key.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+					ElementSymbol value = new ElementSymbol("partitionId"); //$NON-NLS-1$
+					key.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+					List<ElementSymbol> elements = Arrays.asList(key, value);
+					partitionMapping[specIndex] = this.getBufferManager().createSTree(elements, this.getConnectionID(), 1);
+				}
+				SortUtility su = new SortUtility(specificationTs, Mode.SORT, this.getBufferManager(), this.getConnectionID(), tb.getSchema(), info.orderType, info.nullOrderings, sortKeys);
+				TupleBuffer sorted = su.sort();
+				specificationTs = sorted.createIndexedTupleSource(true);
+			}
+			List<AggregateFunction> aggs = initializeAccumulators(info.functions, specIndex, false);
+			List<AggregateFunction> rowValueAggs = initializeAccumulators(info.rowValuefunctions, specIndex, true);
+
+			int groupId = 0;
+			List<?> lastRow = null;
+			while (specificationTs.hasNext()) {
+				List<?> tuple = specificationTs.nextTuple();
+				if (multiGroup) {
+				    if (lastRow != null) {
+				    	boolean samePartition = GroupingNode.sameGroup(partitionIndexes, tuple, lastRow);
+				    	if (!aggs.isEmpty() && (!samePartition || !GroupingNode.sameGroup(orderIndexes, tuple, lastRow))) {
+			        		saveValues(specIndex, aggs, groupId, samePartition, false);
+		        			groupId++;
+				    	}
+		        		saveValues(specIndex, rowValueAggs, lastRow.get(lastRow.size() - 1), samePartition, true);
+		        	}
+				    if (!aggs.isEmpty()) {
+			        	List<Object> partitionTuple = Arrays.asList(tuple.get(tuple.size() - 1), groupId);
+						partitionMapping[specIndex].insert(partitionTuple, InsertMode.NEW, -1);
+				    }
+		        }
+		        for (AggregateFunction function : aggs) {
+		        	function.addInput(tuple);
+		        }
+		        for (AggregateFunction function : rowValueAggs) {
+		        	function.addInput(tuple);
+		        }
+		        lastRow = tuple;
+			}
+		    if(lastRow != null) {
+		    	saveValues(specIndex, aggs, groupId, true, false);
+		    	saveValues(specIndex, rowValueAggs, lastRow.get(lastRow.size() - 1), true, true);
+		    }
+		}
+	}
+
+	private void saveValues(int specIndex,
+			List<AggregateFunction> aggs, Object id,
+			boolean samePartition, boolean rowValue) throws FunctionExecutionException,
+			ExpressionEvaluationException, TeiidComponentException,
+			TeiidProcessingException {
+		if (aggs.isEmpty()) {
+			return;
+		}
+		List<Object> row = new ArrayList<Object>(aggs.size() + 1);
+		row.add(id);
+		for (AggregateFunction function : aggs) {
+			row.add(function.getResult());
+			if (!samePartition) {
+				function.reset();
+			}
+		}
+		if (rowValue) {
+			rowValueMapping[specIndex].insert(row, InsertMode.NEW, -1);
+		} else {
+			valueMapping[specIndex].insert(row, InsertMode.ORDERED, -1);	
+		}
+	}
+
+	/**
+	 * TODO: consolidate with {@link GroupingNode}
+	 * @param functions
+	 * @param specIndex
+	 * @param rowValues
+	 * @return
+	 */
+	private List<AggregateFunction> initializeAccumulators(List<WindowFunctionInfo> functions, int specIndex, boolean rowValues) {
+		List<AggregateFunction> aggs = new ArrayList<AggregateFunction>(functions.size());
+		if (functions.isEmpty()) {
+			return aggs;
+		}
+		//initialize the function accumulators
+		List<ElementSymbol> elements = new ArrayList<ElementSymbol>(functions.size() + 1);
+		ElementSymbol key = new ElementSymbol("id"); //$NON-NLS-1$
+		key.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+		elements.add(key);
+
+		CommandContext context = this.getContext();
+		for (WindowFunctionInfo wfi : functions) {
+			AggregateSymbol aggSymbol = wfi.function.getFunction();
+		    Class<?> outputType = aggSymbol.getType();
+		    ElementSymbol value = new ElementSymbol("val"); //$NON-NLS-1$
+		    value.setType(outputType);
+		    elements.add(value);
+		    Class<?> inputType = aggSymbol.getType();
+		    if (aggSymbol.getExpression() != null) {
+		    	inputType = aggSymbol.getExpression().getType();
+		    }
+			Type function = aggSymbol.getAggregateFunction();
+			AggregateFunction af = null;
+			switch (function) {
+			case RANK:
+			case DENSE_RANK:
+				af = new RankingFunction(function);
+				break;
+			case ROW_NUMBER: //same as count(*)
+			case COUNT:
+				af = new Count();
+				break;
+			case SUM:
+				af = new Sum();
+				break;
+			case AVG:
+				af = new Avg();
+				break;
+			case MIN:
+				af = new Min();
+				break;
+			case MAX:
+				af = new Max();
+				break;
+			case XMLAGG:
+				af = new XMLAgg(context);
+				break;
+			case ARRAY_AGG:
+				af = new ArrayAgg(context);
+				break;                		
+			case TEXTAGG:
+				af = new TextAgg(context, (TextLine)aggSymbol.getExpression());
+				break;                		
+			default:
+				af = new StatsFunction(function);
+			}
+
+			af.setExpressionIndex(wfi.expressionIndex);
+			af.setConditionIndex(wfi.conditionIndex);
+			af.initialize(outputType, inputType);
+			aggs.add(af);
+		}
+		
+		if (!aggs.isEmpty()) {
+			if (!rowValues) {
+				valueMapping[specIndex] = this.getBufferManager().createSTree(elements, this.getConnectionID(), 1);
+			} else {
+				rowValueMapping[specIndex] = this.getBufferManager().createSTree(elements, this.getConnectionID(), 1);
+			}
+		}
+
+		return aggs;
+	}
+
+	/**
+	 * Save the input generating any necessary expressions and adding a row id
+	 * @param collectedExpressions
+	 * @return
+	 * @throws TeiidComponentException
+	 * @throws TeiidProcessingException
+	 */
+	private void saveInput()
+			throws TeiidComponentException, TeiidProcessingException {
+		if (inputTs == null) {
+			List<Expression> collectedExpressions = new ArrayList<Expression>(expressionIndexes.keySet());
+			Evaluator eval = new Evaluator(elementMap, getDataManager(), getContext());
+			final RelationalNode sourceNode = this.getChildren()[0];
+			inputTs = new ProjectingTupleSource(sourceNode, eval, collectedExpressions) {
+				int index = 0;
+				@Override
+				public List<Object> nextTuple() throws TeiidComponentException,
+						TeiidProcessingException {
+					List<Object> tuple = super.nextTuple();
+					if (tuple != null) {
+						tuple.add(index++);
+					}
+					return tuple;
+				}
+			};
+			List<ElementSymbol> schema = new ArrayList<ElementSymbol>(collectedExpressions.size() + 1);
+			int index = 0;
+			for (Expression ex : collectedExpressions) {
+				ElementSymbol es = new ElementSymbol(String.valueOf(index++));
+				es.setType(ex.getType());
+				schema.add(es);
+			}
+			//add in the row id
+			ElementSymbol es = new ElementSymbol(String.valueOf(index++));
+			es.setType(DataTypeManager.DefaultDataClasses.INTEGER);
+			schema.add(es);
+			tb = this.getBufferManager().createTupleBuffer(schema, this.getConnectionID(), TupleSourceType.PROCESSOR);
+		}
+		
+		List<?> tuple = null;
+		while ((tuple = inputTs.nextTuple()) != null) {
+			tb.addTuple(tuple);
+		}
+		tb.close();
+		inputTs.closeSource();
+		inputTs = null;
+	}
+
+	private Integer getIndex(Expression ex) {
+		Integer index = expressionIndexes.get(ex);
+		if (index == null) {
+			index = expressionIndexes.size();
+			expressionIndexes.put(ex, index);
+		}
+		return index;
+	}
+	
+	@Override
+	public void initialize(CommandContext context, BufferManager bufferManager,
+			ProcessorDataManager dataMgr) {
+		super.initialize(context, bufferManager, dataMgr);
+		List sourceElements = this.getChildren()[0].getElements();
+        this.elementMap = createLookupMap(sourceElements);
+	}
+    
+}

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/relational/XMLTableNode.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/relational/XMLTableNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/relational/XMLTableNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,6 +29,7 @@
 import java.util.Map;
 
 import net.sf.saxon.om.Item;
+import net.sf.saxon.om.NodeInfo;
 import net.sf.saxon.om.SequenceIterator;
 import net.sf.saxon.sxpath.XPathDynamicContext;
 import net.sf.saxon.sxpath.XPathExpression;
@@ -42,8 +43,12 @@
 import org.teiid.api.exception.query.ExpressionEvaluationException;
 import org.teiid.common.buffer.BlockedException;
 import org.teiid.common.buffer.TupleBatch;
+import org.teiid.common.buffer.TupleBuffer;
+import org.teiid.common.buffer.BufferManager.TupleSourceType;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.types.XMLType;
 import org.teiid.query.QueryPlugin;
@@ -51,11 +56,15 @@
 import org.teiid.query.sql.lang.XMLTable;
 import org.teiid.query.sql.lang.XMLTable.XMLColumn;
 import org.teiid.query.xquery.saxon.SaxonXQueryExpression.Result;
+import org.teiid.query.xquery.saxon.SaxonXQueryExpression.RowProcessor;
 
 /**
  * Handles xml table processing.
+ * 
+ * When streaming the results will be fully built and stored in a buffer
+ * before being returned
  */
-public class XMLTableNode extends SubqueryAwareRelationalNode {
+public class XMLTableNode extends SubqueryAwareRelationalNode implements RowProcessor {
 
 	private static Map<Class<?>, BuiltInAtomicType> typeMapping = new HashMap<Class<?>, BuiltInAtomicType>();
 	
@@ -74,6 +83,10 @@
 	private int rowCount = 0;
 	private Item item;
 	
+	private TupleBuffer buffer;
+	private int outputRow = 1;
+	private boolean usingOutput;
+	
 	public XMLTableNode(int nodeID) {
 		super(nodeID);
 	}
@@ -81,6 +94,10 @@
 	@Override
 	public void closeDirect() {
 		super.closeDirect();
+		if(this.buffer != null) {
+    		this.buffer.remove();
+        	this.buffer = null;
+        }
 		reset();
 	}
 	
@@ -93,6 +110,9 @@
 		}
 		item = null;
 		rowCount = 0;
+		outputRow = 1;
+		usingOutput = false;
+		this.buffer = null;
 	}
 	
 	public void setTable(XMLTable table) {
@@ -116,31 +136,62 @@
 	protected TupleBatch nextBatchDirect() throws BlockedException,
 			TeiidComponentException, TeiidProcessingException {
 		
-		if (result == null) {
-			setReferenceValues(this.table);
-			result = getEvaluator(Collections.emptyMap()).evaluateXQuery(this.table.getXQueryExpression(), this.table.getPassing(), null);
+		evaluate();
+		
+		if (this.table.getXQueryExpression().isStreaming()) {
+			TupleBatch batch = this.buffer.getBatch(outputRow);
+			outputRow = batch.getEndRow() + 1;
+			return batch;
 		}
 		
 		while (!isBatchFull() && !isLastBatch()) {
-			processRow();
+			if (item == null) {
+				try {
+					item = result.iter.next();
+				} catch (XPathException e) {
+					throw new TeiidProcessingException(e, QueryPlugin.Util.getString("XMLTableNode.error", e.getMessage())); //$NON-NLS-1$
+				}
+				rowCount++;
+				if (item == null) {
+					terminateBatches();
+					break;
+				}
+			}
+			addBatchRow(processRow());
 		}
 		return pullBatch();
 	}
 
-	private void processRow() throws ExpressionEvaluationException, BlockedException,
-			TeiidComponentException, TeiidProcessingException {
-		if (item == null) {
+	private void evaluate() throws TeiidComponentException,
+			ExpressionEvaluationException, BlockedException,
+			TeiidProcessingException {
+		if (result == null) {
+			if (this.buffer == null && this.table.getXQueryExpression().isStreaming()) {
+				this.buffer = this.getBufferManager().createTupleBuffer(getOutputElements(), getConnectionID(), TupleSourceType.PROCESSOR); 
+			}
+			setReferenceValues(this.table);
 			try {
-				item = result.iter.next();
-			} catch (XPathException e) {
-				throw new TeiidProcessingException(e, QueryPlugin.Util.getString("XMLTableNode.error", e.getMessage())); //$NON-NLS-1$
+				result = getEvaluator(Collections.emptyMap()).evaluateXQuery(this.table.getXQueryExpression(), this.table.getPassing(), null, this);
+				if (this.buffer != null) {
+					this.buffer.close();
+					if (!usingOutput) {
+						this.buffer.setForwardOnly(true);
+					}
+				}
+			} catch (TeiidRuntimeException e) {
+				if (e.getCause() instanceof TeiidComponentException) {
+					throw (TeiidComponentException)e.getCause();
+				}
+				if (e.getCause() instanceof TeiidProcessingException) {
+					throw (TeiidProcessingException)e.getCause();
+				}
+				throw e;
 			}
-			rowCount++;
-			if (item == null) {
-				terminateBatches();
-				return;
-			}
 		}
+	}
+
+	private List<?> processRow() throws ExpressionEvaluationException, BlockedException,
+			TeiidComponentException, TeiidProcessingException {
 		List<Object> tuple = new ArrayList<Object>(projectedColumns.size());
 		for (XMLColumn proColumn : projectedColumns) {
 			if (proColumn.isOrdinal()) {
@@ -167,8 +218,10 @@
 					if (pathIter.next() != null) {
 						throw new TeiidProcessingException(QueryPlugin.Util.getString("XMLTableName.multi_value", proColumn.getName())); //$NON-NLS-1$
 					}
-					Object value = Value.convertToJava(colItem);
-					if (value instanceof Item) {
+					Object value = colItem;
+					if (value instanceof AtomicValue) {
+						value = Value.convertToJava(colItem);
+					} else if (value instanceof Item) {
 						Item i = (Item)value;
 						BuiltInAtomicType bat = typeMapping.get(proColumn.getSymbol().getType());
 						if (bat != null) {
@@ -190,7 +243,34 @@
 			}
 		}
 		item = null;
-		addBatchRow(tuple);
+		return tuple;
 	}
+	
+	@Override
+	public boolean hasFinalBuffer() {
+		return this.table.getXQueryExpression().isStreaming();
+	}
+	
+	@Override
+	public TupleBuffer getFinalBuffer() throws BlockedException,
+			TeiidComponentException, TeiidProcessingException {
+		evaluate();
+		usingOutput = true;
+    	TupleBuffer finalBuffer = this.buffer;
+    	this.buffer = null;
+		close();
+		return finalBuffer;
+	}
+	
+	@Override
+	public void processRow(NodeInfo row) {
+		this.item = row;
+		rowCount++;
+		try {
+			this.buffer.addTuple(processRow());
+		} catch (TeiidException e) {
+			throw new TeiidRuntimeException(e);
+		}
+	}
 		
 }
\ No newline at end of file

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecSqlInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecSqlInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecSqlInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,7 +36,7 @@
  * Executes a SQL statement, defines a result set.
  */
 public class ExecSqlInstruction extends ProcessorInstruction {
-    private String resultSetName;
+    String resultSetName;
     ResultSetInfo info;
     
     public ExecSqlInstruction(String resultSetName, ResultSetInfo info) {
@@ -48,15 +48,20 @@
     public XMLContext process(XMLProcessorEnvironment env, XMLContext context)
         throws BlockedException, TeiidComponentException, TeiidProcessingException{
 
-        LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"SQL: Result set DOESN'T exist:",resultSetName}); //$NON-NLS-1$
-        PlanExecutor executor = context.getResultExecutor(resultSetName);
-        if (executor == null) {
-            executor = env.createResultExecutor(resultSetName, info);
-            context.setResultExecutor(resultSetName, executor);
-        }
+        execute(env, context);
         
+        env.incrementCurrentProgramCounter();
+        return context;
+    }
+
+	protected void execute(XMLProcessorEnvironment env, XMLContext context)
+			throws TeiidComponentException, BlockedException,
+			TeiidProcessingException {
+		LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"SQL: Result set DOESN'T exist:",resultSetName}); //$NON-NLS-1$
+        PlanExecutor executor = getPlanExecutor(env, context);
+        
         // this execute can throw the blocked exception
-        executor.execute(context.getReferenceValues());
+        executor.execute(context.getReferenceValues(), false);
         
         // now that we done executing the plan; remove the plan from context
         context.removeResultExecutor(resultSetName);
@@ -64,10 +69,17 @@
         // save this executioner in the context, so that all the nodes
         // below can access the data.
         context.setResultSet(this.resultSetName, executor);
-        
-        env.incrementCurrentProgramCounter();
-        return context;
-    }
+	}
+
+	public PlanExecutor getPlanExecutor(XMLProcessorEnvironment env,
+			XMLContext context) throws TeiidComponentException {
+		PlanExecutor executor = context.getResultExecutor(resultSetName);
+        if (executor == null) {
+            executor = env.createResultExecutor(resultSetName, info);
+            context.setResultExecutor(resultSetName, executor);
+        }
+		return executor;
+	}
     
     public String toString() {
         return "SQL  " + resultSetName; //$NON-NLS-1$ 

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecStagingTableInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecStagingTableInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/ExecStagingTableInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,13 +24,10 @@
 
 import static org.teiid.query.analysis.AnalysisRecord.*;
 
-import java.util.Map;
-
 import org.teiid.client.plan.PlanNode;
 import org.teiid.common.buffer.BlockedException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
-import org.teiid.logging.LogManager;
 import org.teiid.query.mapping.xml.ResultSetInfo;
 
 
@@ -38,20 +35,14 @@
 /** 
  * This instruction is to start loading a staging table. The difference between the loading the 
  * staging table and execute sql node is that sql node will capture the results and save them in
- * the context object, where as staging does not care about the results, beacuse they are actully
+ * the context object, where as staging does not care about the results, because they are actually
  * stored in the temp table store, will be accessed by required query directly from there, as these
  * results are nothing do with producing the document directly.
- * 
- * NOTE: In future we can improve this to load parallelly, if there are more than single 
- * staging table defined on the mapping document
  */
-public class ExecStagingTableInstruction extends ProcessorInstruction {
-    String resultSetName;
-    ResultSetInfo info;
+public class ExecStagingTableInstruction extends ExecSqlInstruction {
     
     public ExecStagingTableInstruction(String resultName, ResultSetInfo info) {
-        this.resultSetName = resultName;
-        this.info = info;
+    	super(resultName, info);
     }
     
     /** 
@@ -61,19 +52,8 @@
         throws BlockedException, TeiidComponentException, TeiidProcessingException {
         
         if (!env.isStagingTableLoaded(this.resultSetName)) {
-            LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"SQL: Result set DOESN'T exist:",resultSetName}); //$NON-NLS-1$
+        	super.execute(env, context);
             
-            PlanExecutor executor = context.getResultExecutor(resultSetName);
-            if (executor == null) {
-                executor = env.createResultExecutor(resultSetName, info);
-                context.setResultExecutor(resultSetName, executor);
-            }
-            
-            // this execute can throw the blocked exception; note that staging tables will not have any
-            // bound references; they are not part of the document; so they do not know about document
-            // details.
-            Map referenceValues = null;
-            executor.execute(referenceValues);
             env.markStagingTableAsLoaded(this.resultSetName);
             
             // now that we done executing the plan; remove the plan from context

Deleted: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/JoinedWhileInstruction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,145 +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 org.teiid.query.processor.xml;
-
-import java.util.List;
-import java.util.Map;
-
-import org.teiid.client.plan.PlanNode;
-import org.teiid.common.buffer.BlockedException;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidProcessingException;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.util.VariableContext;
-
-
-/**
- * Loop instruction on the result set execute before this instruction.
- */
-public class JoinedWhileInstruction extends WhileInstruction {
-
-    private Integer mappingClassNumber;
-    private ElementSymbol mappingClassSymbol;
-    private String originalResultSet;
-
-    /**
-     * Constructor for WhileInstruction.
-     */
-    public JoinedWhileInstruction(String rsName,
-                                  Integer mappingClassNumber,
-                                  ElementSymbol mappingClassSymbol, String originalResultSet) {
-        super(rsName);
-        this.mappingClassNumber = mappingClassNumber;
-        this.mappingClassSymbol = mappingClassSymbol;
-        this.originalResultSet = originalResultSet;
-    }
-
-    /**
-     * @see ProcessorInstruction#process(ProcessorEnvironment)
-     */
-    public XMLContext process(XMLProcessorEnvironment env,
-                              XMLContext context) throws BlockedException,
-                                                 TeiidComponentException,
-                                                 TeiidProcessingException {
-
-        List values = context.getCurrentRow(getResultSetName());
-
-        if (values == null) {
-            env.incrementCurrentProgramCounter();
-            return context;
-        }
-
-        List outputElements = context.getOutputElements(getResultSetName());
-
-        int index = outputElements.indexOf(mappingClassSymbol);
-
-        Object value = values.get(index);
-
-        VariableContext varContext = context.getVariableContext();
-
-        // move on to the next row and don't push the program
-        if (value == null) {
-            if (Boolean.TRUE.equals(getFirst(varContext))) {
-                context.getNextRow(getResultSetName());                
-            }
-            setFirst(varContext, Boolean.TRUE);
-            env.incrementCurrentProgramCounter();
-            return context;
-        }
-
-        boolean canConsume = true;
-
-        // TODO: this is very inefficient. each root should check only its values and pass that value through the context
-        // TODO: likewise the context update below should also only involve the columns from this context
-        if (!Boolean.TRUE.equals(getFirst(varContext))) {
-            Map previousValues = getPreviousValues(varContext); 
-
-            if (previousValues != null) {
-                for (int i = 0; i < index - 1 && canConsume; i++) {
-                    Object previousValue = previousValues.get(outputElements.get(i));
-                    Object currentValue = values.get(i);
-                    if (previousValue != null) {
-                        if (!previousValue.equals(currentValue)) {
-                            canConsume = false;
-                        }
-                    } else if (currentValue != null) {
-                        canConsume = false;
-                    }
-                }
-            }
-        }
-        
-        // consume this row only if the parent values are the same
-        if (value.equals(mappingClassNumber) && canConsume) {
-            //it is not necessary to push the values back into the context here
-            setPreviousValues(varContext, context.getReferenceValues());
-            
-            pushProgram(env, context, values);
-            
-            setFirst(varContext, Boolean.FALSE);
-        } else {
-            setFirst(varContext, Boolean.TRUE);
-            
-            env.incrementCurrentProgramCounter();
-            return context;
-        }
-
-        return context;
-    }
-    
-    Boolean getFirst(VariableContext varContext) {
-        return (Boolean)varContext.getValue(new ElementSymbol("$" + getResultSetName() + "$" + originalResultSet + "$first")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    void setFirst(VariableContext varContext, Boolean value) {
-        varContext.setValue(new ElementSymbol("$" + getResultSetName()  + "$" + originalResultSet + "$first"), value); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    }
-
-    public String toString() {
-        return "JOINED " + originalResultSet + " " + super.toString(); //$NON-NLS-1$ //$NON-NLS-2$ 
-    }
-
-    public PlanNode getDescriptionProperties() {
-        return new PlanNode("JOINED LOOP"); //$NON-NLS-1$ 
-    }
-}

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/PlanExecutor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/PlanExecutor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/PlanExecutor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -39,8 +39,9 @@
     /**
      * Execute the plan   
      * @param referenceValues - values for any external references
+     * @param openOnly
      */
-    public void execute(Map referenceValues) throws TeiidComponentException, BlockedException, TeiidProcessingException;
+    public void execute(Map referenceValues, boolean openOnly) throws TeiidComponentException, BlockedException, TeiidProcessingException;
 
     /**
      * Get the ElementSymbol list which represents the schema of the result set

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/RelationalPlanExecutor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/RelationalPlanExecutor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/RelationalPlanExecutor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,32 +27,53 @@
 
 import org.teiid.common.buffer.BlockedException;
 import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.IndexedTupleSource;
+import org.teiid.common.buffer.TupleSource;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.mapping.xml.ResultSetInfo;
+import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.processor.BatchIterator;
 import org.teiid.query.processor.ProcessorDataManager;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.processor.QueryProcessor;
+import org.teiid.query.sql.lang.Insert;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.util.VariableContext;
+import org.teiid.query.tempdata.AlterTempTable;
 import org.teiid.query.util.CommandContext;
 
-
-
 /** 
  * This is a helper class which can execute a supplied relational plan and supply
  * resulting query results to the caller.
- * Note: in future we would want to replace this class with submitting the requests directly to
- * process worker queue.
  */
 class RelationalPlanExecutor implements PlanExecutor {
     
-    QueryProcessor internalProcessor;
+    private final class TempLoadTupleSource implements TupleSource {
+		@Override
+		public List<?> nextTuple() throws TeiidComponentException,
+				TeiidProcessingException {
+			try {
+				List<?> tuple = tupleSource.nextTuple();
+				if (tuple == null) {
+					doneLoading = true;
+				}
+				return tuple;
+			} catch (BlockedException e) {
+				return null;
+			}
+		}
 
+		@Override
+		public void closeSource() {
+			tupleSource.closeSource();
+		}
+	}
+
+	QueryProcessor internalProcessor;
+
     // information about the result set.
     ResultSetInfo resultInfo;
     // buffer store
@@ -60,16 +81,20 @@
     // flag to denote the end of rows
     boolean endOfRows = false;
     // results after the execution bucket.
-    IndexedTupleSource tupleSource;
+    TupleSource tupleSource;
     // cached current row of results.
-    List currentRow;
+    List<?> currentRow;
     int currentRowNumber = 0;
+    private ProcessorDataManager dataManager;
+    private boolean executed;
+    private boolean doneLoading;
     
     public RelationalPlanExecutor (ResultSetInfo resultInfo, CommandContext context, ProcessorDataManager dataMgr, BufferManager bufferMgr) 
         throws TeiidComponentException{
         
         this.resultInfo = resultInfo;
         this.bufferMgr = bufferMgr;
+        this.dataManager = dataMgr;
         
         ProcessorPlan plan = resultInfo.getPlan();
         CommandContext subContext = context.clone();
@@ -87,15 +112,49 @@
 
     /**
      * @throws TeiidProcessingException 
-     * @see org.teiid.query.processor.xml.PlanExecutor#execute(java.util.Map)
+     * @see org.teiid.query.processor.xml.PlanExecutor#execute(java.util.Map, boolean)
      */
-    public void execute(Map referenceValues) throws TeiidComponentException, BlockedException, TeiidProcessingException {        
+    public void execute(Map referenceValues, boolean openOnly) throws TeiidComponentException, BlockedException, TeiidProcessingException {        
         if (this.tupleSource == null) {
         	setReferenceValues(referenceValues);
             this.tupleSource = new BatchIterator(internalProcessor);
+            if (openOnly) {
+            	internalProcessor.init();
+            }
         }
-        //force execution
-        this.tupleSource.hasNext();
+        if (!openOnly && !executed) {
+	        String tempTable = this.resultInfo.getTempTable();
+			if (tempTable != null && !doneLoading && !this.resultInfo.isAutoStaged()) {
+	        	LogManager.logDetail(LogConstants.CTX_XML_PLAN, "Loading result set temp table", tempTable); //$NON-NLS-1$
+
+	        	Insert insert = this.resultInfo.getTempInsert();
+	        	insert.setTupleSource(new TempLoadTupleSource());
+	        	this.dataManager.registerRequest(this.internalProcessor.getContext(), insert, TempMetadataAdapter.TEMP_MODEL.getName(), null, 0, -1);
+	        	if (!doneLoading) {
+	        		throw BlockedException.block("Blocking on result set load"); //$NON-NLS-1$
+	        	}
+        		internalProcessor.closeProcessing();
+				AlterTempTable att = new AlterTempTable(tempTable);
+				//mark the temp table as non-updatable
+				this.dataManager.registerRequest(this.internalProcessor.getContext(), att, TempMetadataAdapter.TEMP_MODEL.getName(), null, 0, -1);
+        		this.tupleSource = this.dataManager.registerRequest(this.internalProcessor.getContext(), this.resultInfo.getTempSelect(), TempMetadataAdapter.TEMP_MODEL.getName(), null, 0, -1);
+	        }
+			//force execution
+        	currentRow();
+        	
+			if (this.resultInfo.isAutoStaged() && tempTable != null) {
+				AlterTempTable att = new AlterTempTable(tempTable);
+				int size = (Integer)this.currentRow.get(0);
+				if (size > this.bufferMgr.getProcessorBatchSize() * 2) {
+					//TODO: if the parent is small, then this is not necessary
+					att.setIndexColumns(this.resultInfo.getFkColumns());
+				}
+				this.dataManager.registerRequest(this.internalProcessor.getContext(), att, TempMetadataAdapter.TEMP_MODEL.getName(), null, 0, -1);
+			}
+
+			this.currentRowNumber = 0;
+			this.executed = true;
+        }
     }    
     
     void setReferenceValues(Map<ElementSymbol, Object> referencesValues) {
@@ -117,7 +176,9 @@
         if (!endOfRows) {
 
             // get the next row
-            this.currentRow = this.tupleSource.nextTuple();     
+        	if (this.currentRow == null || this.currentRowNumber > 0) {
+        		this.currentRow = this.tupleSource.nextTuple();     
+        	}
             this.currentRowNumber++;
 
             // check if we walked over the row limit
@@ -154,6 +215,19 @@
      */
     public void close() throws TeiidComponentException {
 		this.internalProcessor.closeProcessing();
+		if (this.tupleSource != null) {
+			this.tupleSource.closeSource();
+		}
+		String rsTempTable = this.resultInfo.getTempTable();
+		if (rsTempTable != null) {
+        	LogManager.logDetail(LogConstants.CTX_XML_PLAN, "Unloading result set temp table", rsTempTable); //$NON-NLS-1$
+        	internalProcessor.closeProcessing();
+        	try {
+				this.tupleSource = this.dataManager.registerRequest(this.internalProcessor.getContext(), this.resultInfo.getTempDrop(), TempMetadataAdapter.TEMP_MODEL.getName(), null, 0, -1);
+			} catch (TeiidProcessingException e) {
+		        LogManager.logDetail(org.teiid.logging.LogConstants.CTX_XML_PLAN, e, "Error dropping result set temp table", rsTempTable); //$NON-NLS-1$
+			}
+        }
         LogManager.logTrace(org.teiid.logging.LogConstants.CTX_XML_PLAN, new Object[]{"closed executor", resultInfo.getResultSetName()}); //$NON-NLS-1$
     }
   

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLContext.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,12 +43,12 @@
 class XMLContext {
 
     // map between variables and their values
-    Map resultsMap = new HashMap();
+    Map<String, PlanExecutor> resultsMap = new HashMap<String, PlanExecutor>();
     
     // reference to the parent variable context
     XMLContext parentContext;
     
-    Map executorMap = new HashMap();
+    Map<String, PlanExecutor> executorMap = new HashMap<String, PlanExecutor>();
     
     VariableContext variableContext = new VariableContext();
     
@@ -56,14 +56,12 @@
      * Constructor for VariableContext.
      */
     public XMLContext() {
-        this.resultsMap = new HashMap();
     }
     
     /**
      * Constructor for VariableContext.
      */
     public XMLContext(XMLContext parent) {
-        this.resultsMap = new HashMap();
         this.parentContext = parent;
         this.variableContext.setParentContext(parent.variableContext);
     }
@@ -77,8 +75,8 @@
      * @param aliasResultName
      * @return
      */
-    public List getCurrentRow(String aliasResultName) throws TeiidComponentException, TeiidProcessingException {
-        PlanExecutor executor = (PlanExecutor)this.resultsMap.get(aliasResultName);
+    public List<?> getCurrentRow(String aliasResultName) throws TeiidComponentException, TeiidProcessingException {
+        PlanExecutor executor = this.resultsMap.get(aliasResultName);
         if (executor == null) {
             if (this.parentContext != null) {
                 return this.parentContext.getCurrentRow(aliasResultName);
@@ -94,8 +92,8 @@
      * @return
      * @throws TeiidComponentException
      */
-    public List getNextRow(String aliasResultName) throws TeiidComponentException, TeiidProcessingException {
-        PlanExecutor executor = (PlanExecutor)this.resultsMap.get(aliasResultName);
+    public List<?> getNextRow(String aliasResultName) throws TeiidComponentException, TeiidProcessingException {
+        PlanExecutor executor = this.resultsMap.get(aliasResultName);
         if (executor == null) {
             if (this.parentContext != null) {
                 return this.parentContext.getNextRow(aliasResultName);
@@ -119,7 +117,7 @@
      * as there may be another resultset with same name. (recursive condition) 
      */
     public void removeResultSet(String resultName) throws TeiidComponentException {
-        PlanExecutor executor = (PlanExecutor)this.resultsMap.remove(resultName);
+        PlanExecutor executor = this.resultsMap.remove(resultName);
         if (executor != null) {
             executor.close();
         }
@@ -132,8 +130,8 @@
      * @return
      * @throws TeiidComponentException
      */
-    public List getOutputElements(String resultName) throws TeiidComponentException {
-        PlanExecutor executor = (PlanExecutor)this.resultsMap.get(resultName);
+    public List<?> getOutputElements(String resultName) throws TeiidComponentException {
+        PlanExecutor executor = this.resultsMap.get(resultName);
         if (executor == null) {
             if (this.parentContext != null) {
                 return this.parentContext.getOutputElements(resultName);
@@ -160,7 +158,7 @@
      * @return
      */
     public PlanExecutor getResultExecutor(String resultName) {
-        return (PlanExecutor)this.executorMap.get(resultName);
+        return this.executorMap.get(resultName);
     }
 
     /**
@@ -186,10 +184,13 @@
     
 
     void setVariableValues(String resultSetName,
-                                   List row) throws TeiidComponentException {
+                                   List<?> row) throws TeiidComponentException {
         List elements = getOutputElements(resultSetName);
         
         for (int index = 0; index < elements.size(); index++) {
+        	if (!(elements.get(index) instanceof ElementSymbol)) {
+        		continue;
+        	}
             ElementSymbol symbol = (ElementSymbol)elements.get(index);
             variableContext.setValue(new ElementSymbol(resultSetName + ElementSymbol.SEPARATOR + symbol.getShortName()), row.get(index));
         }

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLPlan.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLPlan.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLPlan.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -155,7 +155,7 @@
         
         while(true){
         	// do the xml processing.
-            ProcessorInstruction inst = env.getCurrentInstruction();
+            ProcessorInstruction inst = env.getCurrentInstruction(this.context);
             while (inst != null){
             	LogManager.logTrace(LogConstants.CTX_XML_PLAN, "Executing instruction", inst); //$NON-NLS-1$
                 this.context = inst.process(this.env, this.context);
@@ -186,7 +186,7 @@
         	        TupleBatch batch = new TupleBatch(nextBatchCount++, Arrays.asList(Arrays.asList(xml)));
         	        return batch;
                 }
-                inst = env.getCurrentInstruction();
+                inst = env.getCurrentInstruction(this.context);
             }
             
         	TupleBatch batch = new TupleBatch(nextBatchCount++, Collections.EMPTY_LIST); 

Modified: branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLProcessorEnvironment.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLProcessorEnvironment.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/processor/xml/XMLProcessorEnvironment.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,10 +26,12 @@
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedList;
+import java.util.List;
 import java.util.Set;
 
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidProcessingException;
 import org.teiid.logging.LogManager;
 import org.teiid.logging.MessageLevel;
 import org.teiid.query.mapping.xml.ResultSetInfo;
@@ -84,6 +86,7 @@
     private static class ProgramState {
         private Program program;
         private int programCounter = 0;
+        private int lookaheadCounter;
         private int recursionCount = NOT_RECURSIVE;
         
         private static final int NOT_RECURSIVE = 0;
@@ -156,7 +159,7 @@
         this.programStack.addFirst(programState);
     }
 
-    public ProcessorInstruction getCurrentInstruction() {
+    public ProcessorInstruction getCurrentInstruction(XMLContext context) throws TeiidComponentException, TeiidProcessingException {
         ProgramState programState = this.programStack.getFirst();
         
         //Case 5266: account for an empty program on to the stack; 
@@ -171,6 +174,30 @@
             return null;
         }
         
+        //start all siblings
+        List<ProcessorInstruction> instrs = programState.program.getProcessorInstructions();
+        if (programState.programCounter >= programState.lookaheadCounter && instrs.size() > programState.programCounter + 1) {
+        	for (programState.lookaheadCounter = programState.programCounter; programState.lookaheadCounter < instrs.size(); programState.lookaheadCounter++) {
+        		ProcessorInstruction pi = instrs.get(programState.lookaheadCounter);
+        		boolean staging = false;
+        		if (pi instanceof ExecStagingTableInstruction) {
+        			staging = true;
+        			ExecStagingTableInstruction esti = (ExecStagingTableInstruction)pi;
+        			if (!esti.info.isAutoStaged()) {
+        				//need to load staging tables prior to source queries
+        				break;
+        			}
+        		}
+        		if (pi instanceof ExecSqlInstruction) {
+        			ExecSqlInstruction esi = (ExecSqlInstruction)pi;
+        			if (!staging && esi.info.isAutoStaged() && esi.info.getTempTable() == null) {
+        				continue; //derived load
+        			}
+        			PlanExecutor pe = esi.getPlanExecutor(this, context);
+        			pe.execute(context.getReferenceValues(), true);
+        		}
+        	}
+        }
         return programState.program.getInstructionAt(programState.programCounter);
     }
     
@@ -251,8 +278,6 @@
         ProgramState initialProgramState = this.programStack.getLast();
         ProgramState newState = new ProgramState();
         newState.program = initialProgramState.program;
-        newState.programCounter = 0;
-        newState.recursionCount = ProgramState.NOT_RECURSIVE;
         clone.programStack.addFirst(newState);
                
         // XML results form and format

Modified: branches/as7/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/resolver/command/InsertResolver.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -97,9 +97,9 @@
         
         if (insert.getVariables().isEmpty()) {
             if (insert.getGroup().isResolved()) {
-                List variables = ResolverUtil.resolveElementsInGroup(insert.getGroup(), metadata);
-                for (Iterator i = variables.iterator(); i.hasNext();) {
-                    insert.addVariable((ElementSymbol)((ElementSymbol)i.next()).clone());
+                List<ElementSymbol> variables = ResolverUtil.resolveElementsInGroup(insert.getGroup(), metadata);
+                for (Iterator<ElementSymbol> i = variables.iterator(); i.hasNext();) {
+                    insert.addVariable(i.next().clone());
                 }
             } else {
                 for (int i = 0; i < values.size(); i++) {
@@ -135,7 +135,7 @@
         	List<Reference> references = new ArrayList<Reference>(insert.getVariables().size());
         	for (int i = 0; i < insert.getVariables().size(); i++) {
         		Reference ref = new Reference(i);
-        		ref.setType(((ElementSymbol)insert.getVariables().get(i)).getType());
+        		ref.setType(insert.getVariables().get(i).getType());
 				references.add(ref);
 			}
         	insert.setValues(references);
@@ -178,11 +178,11 @@
         }
         
         Iterator valueIter = values.iterator();
-        Iterator varIter = insert.getVariables().iterator();
+        Iterator<ElementSymbol> varIter = insert.getVariables().iterator();
         while(valueIter.hasNext()) {
             // Walk through both elements and expressions, which should match up
 			Expression expression = (Expression) valueIter.next();
-			ElementSymbol element = (ElementSymbol) varIter.next();
+			ElementSymbol element = varIter.next();
 			
 			if (!usingQuery) {
 				ResolverUtil.setDesiredType(expression, element.getType(), insert);
@@ -198,7 +198,7 @@
                     //TODO: a special case here is a projected literal
                     throw new QueryResolverException(QueryPlugin.Util.getString("InsertResolver.cant_convert_query_type", new Object[] {expression, expression.getType().getName(), element, element.getType().getName()})); //$NON-NLS-1$
                 }
-            } else if (element.getType() == null && expression.getType() != null && !usingQuery)  {
+            } else if (element.getType() == null && expression.getType() != null)  {
                 element.setType(expression.getType());
                 newValues.add(expression);
             } else {

Modified: branches/as7/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/resolver/command/SimpleQueryResolver.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -76,12 +76,11 @@
 import org.teiid.query.sql.lang.XMLTable;
 import org.teiid.query.sql.navigator.PostOrderNavigator;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
@@ -89,8 +88,6 @@
 
 public class SimpleQueryResolver implements CommandResolver {
 
-    private static final String ALL_IN_GROUP_SUFFIX = ".*"; //$NON-NLS-1$
-
     /** 
      * @see org.teiid.query.resolver.CommandResolver#resolveCommand(org.teiid.query.sql.lang.Command, org.teiid.query.metadata.TempMetadataAdapter, boolean)
      */
@@ -107,14 +104,14 @@
             ResolverVisitor visitor = (ResolverVisitor)qrv.getVisitor();
 			visitor.throwException(true);
         } catch (TeiidRuntimeException e) {
-            if (e.getChild() instanceof QueryMetadataException) {
-                throw (QueryMetadataException)e.getChild();
+            if (e.getCause() instanceof QueryMetadataException) {
+                throw (QueryMetadataException)e.getCause();
             }
-            if (e.getChild() instanceof QueryResolverException) {
-                throw (QueryResolverException)e.getChild();
+            if (e.getCause() instanceof QueryResolverException) {
+                throw (QueryResolverException)e.getCause();
             }
-            if (e.getChild() instanceof TeiidComponentException) {
-                throw (TeiidComponentException)e.getChild();
+            if (e.getCause() instanceof TeiidComponentException) {
+                throw (TeiidComponentException)e.getCause();
             }
             throw e;
         }
@@ -127,7 +124,7 @@
         	ResolverUtil.resolveOrderBy(query.getOrderBy(), query, metadata);
         }
         
-        List symbols = query.getSelect().getProjectedSymbols();
+        List<SingleElementSymbol> symbols = query.getSelect().getProjectedSymbols();
         
         if (query.getInto() != null) {
             GroupSymbol symbol = query.getInto().getGroup();
@@ -185,18 +182,18 @@
         }
 	}
 
-    private static GroupSymbol resolveAllInGroup(AllInGroupSymbol allInGroupSymbol, Set<GroupSymbol> groups, QueryMetadataInterface metadata) throws QueryResolverException, QueryMetadataException, TeiidComponentException {       
-        String name = allInGroupSymbol.getName();
-        int index = name.lastIndexOf(ALL_IN_GROUP_SUFFIX);
-        String groupAlias = name.substring(0, index);
-        List<GroupSymbol> groupSymbols = ResolverUtil.findMatchingGroups(groupAlias.toUpperCase(), groups, metadata);
+    private static GroupSymbol resolveAllInGroup(MultipleElementSymbol allInGroupSymbol, Set<GroupSymbol> groups, QueryMetadataInterface metadata) throws QueryResolverException, QueryMetadataException, TeiidComponentException {       
+        String groupAlias = allInGroupSymbol.getGroup().getCanonicalName();
+        List<GroupSymbol> groupSymbols = ResolverUtil.findMatchingGroups(groupAlias, groups, metadata);
         if(groupSymbols.isEmpty() || groupSymbols.size() > 1) {
             String msg = QueryPlugin.Util.getString(groupSymbols.isEmpty()?"ERR.015.008.0047":"SimpleQueryResolver.ambiguous_all_in_group", allInGroupSymbol);  //$NON-NLS-1$ //$NON-NLS-2$
             QueryResolverException qre = new QueryResolverException(msg);
             qre.addUnresolvedSymbol(new UnresolvedSymbolDescription(allInGroupSymbol.toString(), msg));
             throw qre;
         }
-
+        GroupSymbol gs = allInGroupSymbol.getGroup();
+        allInGroupSymbol.setGroup(groupSymbols.get(0).clone());
+        allInGroupSymbol.getGroup().setOutputName(gs.getOutputName());
         return groupSymbols.get(0);
     }
     
@@ -260,14 +257,19 @@
             }
         }
         
-        public void visit(AllSymbol obj) {
+        public void visit(MultipleElementSymbol obj) {
+        	// Determine group that this symbol is for
             try {
                 List<ElementSymbol> elementSymbols = new ArrayList<ElementSymbol>();
-                for (GroupSymbol group : currentGroups) {
+                Collection<GroupSymbol> groups = currentGroups;
+                if (obj.getGroup() != null) {
+                	groups = Arrays.asList(resolveAllInGroup(obj, currentGroups, metadata));
+                }
+                for (GroupSymbol group : groups) {
                     elementSymbols.addAll(resolveSelectableElements(group));
                 }
                 obj.setElementSymbols(elementSymbols);
-            } catch (TeiidComponentException err) {
+            } catch (TeiidException err) {
                 throw new TeiidRuntimeException(err);
             } 
         }
@@ -281,7 +283,7 @@
             // Look for elements that are not selectable and remove them
             for (ElementSymbol element : elements) {
                 if(metadata.elementSupports(element.getMetadataID(), SupportConstants.Element.SELECT)) {
-                    element = (ElementSymbol)element.clone();
+                    element = element.clone();
                     element.setGroupSymbol(group);
                 	result.add(element);
                 }
@@ -289,19 +291,6 @@
             return result;
         }
         
-        public void visit(AllInGroupSymbol obj) {
-            // Determine group that this symbol is for
-            try {
-                GroupSymbol group = resolveAllInGroup(obj, currentGroups, metadata);
-                
-                List<ElementSymbol> elements = resolveSelectableElements(group);
-                
-                obj.setElementSymbols(elements);
-            } catch (TeiidException err) {
-                throw new TeiidRuntimeException(err);
-            } 
-        }
-        
         public void visit(ScalarSubquery obj) {
             resolveSubQuery(obj, this.currentGroups);
         }
@@ -368,6 +357,9 @@
 			}
         }
         
+        /**
+		 * @param tfr  
+		 */
         public LinkedHashSet<GroupSymbol> preTableFunctionReference(TableFunctionReference tfr) {
         	LinkedHashSet<GroupSymbol> saved = new LinkedHashSet<GroupSymbol>(this.currentGroups);
         	if (allowImplicit) {
@@ -468,7 +460,7 @@
 			from.addClause(new SubqueryFromClause("X", storedProcedureCommand)); //$NON-NLS-1$
 			procQuery.setFrom(from);
 			Select select = new Select();
-			select.addSymbol(new AllInGroupSymbol("X.*")); //$NON-NLS-1$
+			select.addSymbol(new MultipleElementSymbol("X")); //$NON-NLS-1$
 			procQuery.setSelect(select);
 			
 			List<String> accessPatternElementNames = new LinkedList<String>();
@@ -571,7 +563,7 @@
                 
         public void visit(From obj) {
             assert currentGroups.isEmpty();
-            for (FromClause clause : (List<FromClause>)obj.getClauses()) {
+            for (FromClause clause : obj.getClauses()) {
 				checkImplicit(clause);
 			}
             super.visit(obj);

Modified: branches/as7/engine/src/main/java/org/teiid/query/resolver/command/UpdateProcedureResolver.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/resolver/command/UpdateProcedureResolver.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/resolver/command/UpdateProcedureResolver.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -194,7 +194,7 @@
             			switch (param.getParameterType()) {
         	            case ParameterInfo.OUT:
         	            case ParameterInfo.RETURN_VALUE:
-        	            	if (!isAssignable(metadata, param)) {
+        	            	if (param.getExpression() != null && !isAssignable(metadata, param)) {
         	                    throw new QueryResolverException(QueryPlugin.Util.getString("UpdateProcedureResolver.only_variables", param.getExpression())); //$NON-NLS-1$
         	            	}
         	            	sp.setCallableStatement(true);
@@ -312,11 +312,6 @@
                 
                 resolveBlock(command, loopStmt.getBlock(), externalGroups, metadata);
                 break;
-            case Statement.TYPE_BREAK:
-            case Statement.TYPE_CONTINUE:
-                break;
-            default:
-                throw new QueryResolverException("ERR.015.008.0015", QueryPlugin.Util.getString("ERR.015.008.0015", statement.getType())); //$NON-NLS-1$ //$NON-NLS-2$
         }
     }
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/resolver/command/XMLQueryResolver.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,86 +25,242 @@
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Iterator;
+import java.util.LinkedList;
 import java.util.List;
+import java.util.TreeMap;
 
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.util.StringUtil;
 import org.teiid.query.QueryPlugin;
+import org.teiid.query.mapping.xml.MappingAttribute;
+import org.teiid.query.mapping.xml.MappingBaseNode;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingElement;
+import org.teiid.query.mapping.xml.MappingVisitor;
+import org.teiid.query.mapping.xml.Navigator;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataAdapter;
+import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.metadata.TempMetadataID.Type;
 import org.teiid.query.resolver.CommandResolver;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.resolver.util.ResolverUtil;
 import org.teiid.query.resolver.util.ResolverVisitor;
+import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.lang.GroupContext;
 import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SubqueryContainer;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.SelectSymbol;
-import org.teiid.query.sql.visitor.CommandCollectorVisitor;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
+import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
 
 
 /**
  */
 public class XMLQueryResolver implements CommandResolver {
+	
+	private final class SubSelectVisitor extends MappingVisitor {
+		private final List<ElementSymbol> selectElems;
+		private final ResolvingNode root;
+		private final String mc;
+		private String source;
 
-    /**
+		private SubSelectVisitor(List<ElementSymbol> selectElems,
+				ResolvingNode root, String mc) {
+			this.selectElems = selectElems;
+			this.root = root;
+			this.mc = mc;
+		}
+
+		@Override
+		public void visit(MappingBaseNode baseNode) {
+			if (baseNode.getSource() != null && baseNode.getFullyQualifiedName().equalsIgnoreCase(mc)) {
+				source = baseNode.getSource();
+			}
+		}
+
+		@Override
+		public void visit(MappingElement element) {
+			visit((MappingBaseNode)element);
+			String nis = element.getNameInSource();
+			getMappingClassColumn(nis, element.getFullyQualifiedName());
+		}
+
+		private void getMappingClassColumn(String nis, String fqn) {
+			if (nis == null || source == null) {
+				return;
+			}
+			String name = nis.substring(0, nis.lastIndexOf('.'));
+			if (source.equalsIgnoreCase(name)) {
+				selectElems.add(root.find(fqn));
+			}
+		}
+
+		@Override
+		public void visit(MappingAttribute attribute) {
+			getMappingClassColumn(attribute.getNameInSource(), attribute.getFullyQualifiedName());
+		}
+	}
+
+	private static final class ResolvingNode {
+		ElementSymbol elementSymbol;
+		TreeMap<String, ResolvingNode> children = new TreeMap<String, ResolvingNode>(String.CASE_INSENSITIVE_ORDER);
+		
+		public void add(String name, ElementSymbol symbol) {
+			if (name == null) {
+				this.elementSymbol = symbol;
+				return;
+			}
+			int index = name.lastIndexOf('.');
+			String childName = name;
+			if (index >= 0) {
+				childName = name.substring(0, index);
+				name = name.substring(index + 1, name.length());
+			} else {
+				childName = null;
+			}
+			ResolvingNode child = children.get(name);
+			if (child == null) {
+				child = new ResolvingNode();
+				children.put(name, child);
+			}
+			child.add(childName, symbol);
+		}
+		
+		public <T extends Collection<ElementSymbol>> T values(T values) {
+			if (elementSymbol != null) {
+				values.add(elementSymbol);
+			}
+			for (ResolvingNode node : children.values()) {
+				node.values(values);
+			}
+			return values;
+		}
+		
+		public ElementSymbol find(String name) {
+			int index = name.lastIndexOf('.');
+			String part = name;
+			if (index > 0) {
+				part = name.substring(index + 1, name.length());
+				name = name.substring(0, index);
+			} else {
+				name = null;
+			}
+			ResolvingNode r = children.get(part);
+			if (r == null) {
+				return null;
+			}
+			if (name == null) {
+				return r.elementSymbol;
+			}
+			return r.find(name);
+		}
+		
+		public void addAll(Collection<ElementSymbol> elems) {
+			for (ElementSymbol es : elems) {
+				this.add(es.getName(), es);
+			}
+		}
+		
+		public List<ElementSymbol> values() {
+			return values(new LinkedList<ElementSymbol>());
+		}
+	}
+
+	/**
      * @see org.teiid.query.resolver.CommandResolver#resolveCommand(org.teiid.query.sql.lang.Command, TempMetadataAdapter, boolean)
      */
 	public void resolveCommand(Command command, TempMetadataAdapter metadata, boolean resolveNullLiterals)
 		throws QueryMetadataException, QueryResolverException, TeiidComponentException {
+		resolveCommand((Query)command, null, metadata);
+	}
 
-		Query query = (Query) command;
-
+	public void resolveCommand(Query query, GroupSymbol docGroup, TempMetadataAdapter metadata)
+	throws QueryMetadataException, QueryResolverException, TeiidComponentException {
 		// set isXML flag
-		query.setIsXML(true);
+		query.setIsXML(docGroup == null);
 
 		// get the group on this query
 		Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(query, true);
 		GroupSymbol group = groups.iterator().next();
 
+		boolean subQuery = true;
+		if (docGroup == null) {
+			docGroup = group;
+			subQuery = false;
+		}
+		
+		if (subQuery && group.getDefinition() != null) {
+			throw new QueryResolverException(QueryPlugin.Util.getString("XMLQueryResolver.aliased_subquery", group)); //$NON-NLS-1$
+		}
+
 		//external groups
         GroupContext externalGroups = query.getExternalGroupContexts();
 
 		// valid elements for select
-		List<ElementSymbol> validSelectElems = getElementsInDocument(group, metadata);
-		resolveXMLSelect(query, group, validSelectElems, metadata);
+        List<ElementSymbol> validElems = ResolverUtil.resolveElementsInGroup(docGroup, metadata);
+        final ResolvingNode root = new ResolvingNode();
+        ResolvingNode selectRoot = root;
+        if (subQuery) {
+        	validElems = getElementsUnderNode(group.getMetadataID(), validElems, metadata);
+        }
+        root.addAll(validElems);
+		if (subQuery) {
+        	//the select can only be to the mapping class itself
+        	MappingDocument doc = (MappingDocument) metadata.getMappingNode(docGroup.getMetadataID());
+    		final String mc = group.getNonCorrelationName();
+    		List<ElementSymbol> selectElems = new LinkedList<ElementSymbol>();
+            doc.acceptVisitor(new Navigator(true, new SubSelectVisitor(selectElems, root, mc)));
+			selectRoot = new ResolvingNode();
+			selectRoot.addAll(selectElems);
+        }
+		
+		resolveXMLSelect(subQuery, query, group, selectRoot, metadata);
 
 		// valid elements for criteria and order by
-		Collection<ElementSymbol> validCriteriaElements = collectValidCriteriaElements(group, metadata);
+		root.addAll(collectTempElements(group, metadata));
 
 		Criteria crit = query.getCriteria();
 		OrderBy orderBy = query.getOrderBy();
-        
-        List<Command> commands = CommandCollectorVisitor.getCommands(query);
-        for (Command subCommand : commands) {
-            QueryResolver.setChildMetadata(subCommand, command);
-            
-            QueryResolver.resolveCommand(subCommand, metadata.getMetadata());
-        }
-        
+		
 		if(crit != null) {
-			resolveXMLCriteria(crit, externalGroups, validCriteriaElements, metadata);
+	        List<SubqueryContainer> commands = ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(crit);
+	        if (!commands.isEmpty()) {
+	        	TempMetadataAdapter tma = new TempMetadataAdapter(metadata, new TempMetadataStore());
+	        	if (!subQuery) {
+	        		addPseudoSubqueryGroups(tma, group, docGroup);
+	        	}
+		        for (SubqueryContainer subCommand : commands) {
+		            QueryResolver.setChildMetadata(subCommand.getCommand(), query);
+		            if (subCommand.getCommand() instanceof Query && QueryResolver.isXMLQuery((Query)subCommand.getCommand(), tma)) {
+		            	resolveCommand((Query)subCommand.getCommand(), docGroup, tma);
+		            } else {
+		            	QueryResolver.resolveCommand(subCommand.getCommand(), metadata.getMetadata());
+		            }
+		        }
+	        }
+
+			resolveXMLCriteria(crit, externalGroups, root, metadata);
 			// Resolve functions in current query
 			ResolverVisitor.resolveLanguageObject(crit, metadata);
 		}
 
 		// resolve any orderby specified on the query
 		if(orderBy != null) {
-			resolveXMLOrderBy(orderBy, externalGroups, validCriteriaElements, metadata);
+			resolveXMLOrderBy(orderBy, externalGroups, root, metadata);
 		}
         
         //we throw exceptions in these cases, since the clauses will not be resolved
@@ -117,6 +273,34 @@
         }	
     }
 
+	private void addPseudoSubqueryGroups(final TempMetadataAdapter metadata,
+			GroupSymbol group, GroupSymbol docGroup)
+			throws TeiidComponentException, QueryMetadataException {
+		/*
+		 * The next section of resolving logic adds in pseduo groups that can be used
+		 * in subqueries
+		 */
+		MappingDocument doc = (MappingDocument) metadata.getMappingNode(docGroup.getMetadataID());
+		
+		final String prefix = group.getNonCorrelationName() + ElementSymbol.SEPARATOR;
+
+        doc.acceptVisitor(new Navigator(true, new MappingVisitor() {
+        	@Override
+        	public void visit(MappingBaseNode baseNode) {
+        		if (baseNode.getSource() == null) {
+        			return;
+        		}
+        		if (StringUtil.startsWithIgnoreCase(baseNode.getFullyQualifiedName(), prefix)) {
+        			try {
+						ResolverUtil.addTempGroup(metadata, new GroupSymbol(baseNode.getFullyQualifiedName()), Collections.EMPTY_LIST, false).setMetadataType(Type.XML);
+					} catch (QueryResolverException e) {
+						throw new TeiidRuntimeException(e);
+					}
+        		}
+        	}
+        }));
+	}
+
     /**
      * Method resolveXMLSelect.
      * @param select Select clause in user command
@@ -128,7 +312,7 @@
      * @throws QueryMetadataException if resolving fails
      * @throws TeiidComponentException if resolving fails
      */
-	void resolveXMLSelect(Query query, GroupSymbol group, List<ElementSymbol> validElements, QueryMetadataInterface metadata)
+	void resolveXMLSelect(boolean subquery, Query query, GroupSymbol group, ResolvingNode validElements, QueryMetadataInterface metadata)
 		throws QueryMetadataException, TeiidComponentException, QueryResolverException {
         
         GroupContext externalGroups = null;
@@ -152,47 +336,38 @@
 
 				// There are other cases of "xml", such as, element name = "xml",
 				// but those are ok because those will be resolved later as normal elements
-				String symbolName = ss.getName();
-				if(symbolName.equalsIgnoreCase("xml") || symbolName.equalsIgnoreCase(group.getName() + ".xml")) { //$NON-NLS-1$ //$NON-NLS-2$
+				ElementSymbol es = (ElementSymbol)ss;
+				String symbolName = es.getName();
+				if(!subquery && (symbolName.equalsIgnoreCase("xml") || symbolName.equalsIgnoreCase(group.getName() + ".xml"))) { //$NON-NLS-1$ //$NON-NLS-2$
 					if(elements.size() != 1) {
 						throw new QueryResolverException(QueryPlugin.Util.getString("XMLQueryResolver.xml_only_valid_alone")); //$NON-NLS-1$
 					}
 					select.clearSymbols();
-                    AllSymbol all = new AllSymbol();
-                    all.setElementSymbols(validElements);
+                    MultipleElementSymbol all = new MultipleElementSymbol();
+                    all.setElementSymbols(validElements.values());
 					select.addSymbol(all);
 					query.setSelect(select);
 					return;
 				}
                 // normal elements
-				resolveElement((ElementSymbol)ss, validElements, externalGroups, metadata);
-			} else if (ss instanceof AllInGroupSymbol) {
+				resolveElement(es, validElements, externalGroups, metadata);
+			} else if (ss instanceof MultipleElementSymbol) {
 				// Resolve the element with "*" case. such as "A.*"
 				// by stripping off the ".*" part,
-				String symbolName = ss.getName();
-				int index = symbolName.indexOf("*"); //$NON-NLS-1$
-				String elementPart = symbolName.substring(0, index-1);
+                MultipleElementSymbol all =  (MultipleElementSymbol)ss;
 
                 // Check for case where we have model.doc.*
-                if(elementPart.equalsIgnoreCase(group.getName())) {
-                    select.clearSymbols();
-                    AllSymbol all = new AllSymbol();
-                    all.setElementSymbols(validElements);
-                    select.addSymbol(all);
-                    query.setSelect(select);
-                } else {
-                    // resovlve the node which is specified
-                    ElementSymbol elementSymbol = new ElementSymbol(elementPart);
-                    resolveElement(elementSymbol, validElements, externalGroups, metadata);
+                if(all.getGroup() == null || all.getGroup().getName().equalsIgnoreCase(group.getName())) {
+                    all.setElementSymbols(validElements.values());
+    				return;
+                }
+                // resovlve the node which is specified
+                ElementSymbol elementSymbol = new ElementSymbol(all.getGroup().getName());
+                resolveElement(elementSymbol, validElements, externalGroups, metadata);
 
-                    // now find all the elements under this node and set as elements.
-                    List<ElementSymbol> elementsInNode = getElementsUnderNode(elementSymbol, validElements, metadata);
-                    ((AllInGroupSymbol)ss).setElementSymbols(elementsInNode);
-                }
-			} else if (ss instanceof AllSymbol) {
-                AllSymbol all =  (AllSymbol)ss;
-                all.setElementSymbols(validElements);
-				return;
+                // now find all the elements under this node and set as elements.
+                List<ElementSymbol> elementsInNode = getElementsUnderNode(elementSymbol.getMetadataID(), validElements.values(), metadata);
+                all.setElementSymbols(elementsInNode);
 			} else if (ss instanceof ExpressionSymbol) {
                 throw new QueryResolverException(QueryPlugin.Util.getString("XMLQueryResolver.no_expressions_in_select")); //$NON-NLS-1$
             } else if (ss instanceof AliasSymbol) {
@@ -202,30 +377,12 @@
 		}
 	}
         
-    /**
-     * Collect all fully-qualified valid elements.  These can then be used to
-     * validate elements used in the query.  It's easier to look up the valid
-     * elements because the user is allow to used any partially-qualified name,
-     * which makes the logic for doing lookups essentially impossible with the
-     * existing metadata interface.
-     * @param group Document group
-     * @param metadata Metadata interface
-     * @return Collection of ElementSymbol for each possible valid element
-     * @throws QueryMetadataException
-     * @throws TeiidComponentException
-     * @throws QueryResolverException
-     */
-    public static Collection<ElementSymbol> collectValidCriteriaElements(GroupSymbol group, QueryMetadataInterface metadata)
-        throws QueryMetadataException, TeiidComponentException, QueryResolverException {
-
-        // Get all groups and elements
-        List<ElementSymbol> validElements = getElementsInDocument(group, metadata);
-
+    public static Collection<ElementSymbol> collectTempElements(GroupSymbol group, QueryMetadataInterface metadata)
+        throws QueryMetadataException, TeiidComponentException {
+    	ArrayList<ElementSymbol> validElements = new ArrayList<ElementSymbol>();
         // Create GroupSymbol for temp groups and add to groups
-        Collection tempGroups = metadata.getXMLTempGroups(group.getMetadataID());
-        Iterator tempGroupIter = tempGroups.iterator();
-        while(tempGroupIter.hasNext()) {
-            Object tempGroupID = tempGroupIter.next();
+        Collection<?> tempGroups = metadata.getXMLTempGroups(group.getMetadataID());
+        for (Object tempGroupID : tempGroups) {
             String name = metadata.getFullName(tempGroupID);
             GroupSymbol tempGroup = new GroupSymbol(name);
             tempGroup.setMetadataID(tempGroupID);
@@ -235,7 +392,6 @@
         return validElements;
     }
 
-
     /**
      * <p> Resolve the criteria specified on the XML query. The elements specified on the criteria should
      * be present on one of the mapping node objects passed to this method, or else be an element on a
@@ -255,7 +411,7 @@
      * @param metadata QueryMetadataInterface the metadata(for resolving criteria on temp groups)
      * @throws QueryResolverException if any of the above fail conditions are met
      */
-    public static void resolveXMLCriteria(Criteria criteria,GroupContext externalGroups, Collection<ElementSymbol> validElements, QueryMetadataInterface metadata)
+    public static void resolveXMLCriteria(LanguageObject criteria,GroupContext externalGroups, ResolvingNode validElements, QueryMetadataInterface metadata)
         throws QueryMetadataException, TeiidComponentException, QueryResolverException {
 
         // Walk through each element in criteria and check against valid elements
@@ -278,7 +434,7 @@
      * @throws QueryMetadataException if resolving fails
      * @throws TeiidComponentException if resolving fails
      */
-    static void resolveXMLOrderBy(OrderBy orderBy, GroupContext externalGroups, Collection<ElementSymbol> validElements, QueryMetadataInterface metadata)
+    static void resolveXMLOrderBy(OrderBy orderBy, GroupContext externalGroups, ResolvingNode validElements, QueryMetadataInterface metadata)
         throws QueryMetadataException, TeiidComponentException, QueryResolverException {
 
         // Walk through each element in OrderBy clause and check against valid elements
@@ -298,107 +454,69 @@
 	 * @throws QueryMetadataException
 	 * @throws TeiidComponentException
 	 */
-    static void resolveElement(ElementSymbol elem, Collection<ElementSymbol> validElements, GroupContext externalGroups, QueryMetadataInterface metadata)
+    static void resolveElement(ElementSymbol elem, ResolvingNode validElements, GroupContext externalGroups, QueryMetadataInterface metadata)
         throws QueryResolverException, QueryMetadataException, TeiidComponentException {
         
         // Get exact matching name
-        String critElemName = elem.getName();
-        String critElemNameSuffix = "." + elem.getCanonicalName(); //$NON-NLS-1$
+        String partialName = elem.getName();
+        String fullName = partialName;
 
-        // Prepare results
-        ElementSymbol exactMatch = null;
-        List<ElementSymbol> partialMatches = new ArrayList<ElementSymbol>(2);     // anything over 1 is an error and should be rare
+        ResolvingNode current = validElements;
+    	String part = partialName;
+        for (int i = 0; partialName != null; i++) {
+        	int index = partialName.lastIndexOf('.');
+        	if (index < 0) {
+        		part = partialName;
+        		partialName = null;
+        	} else {
+        		part = partialName.substring(index + 1, partialName.length());
+        		partialName = partialName.substring(0, index);
+        	}
+			current = current.children.get(part);
+			if (current == null) {
+				if (i == 0 && part.charAt(0) != '@') {
+					//handle attribute case
+					part = '@' + part;
+					current = validElements.children.get(part);
+					if (current != null) {
+						continue;
+					}
+				}
+				try {
+	                ResolverVisitor.resolveLanguageObject(elem, Collections.EMPTY_LIST, externalGroups, metadata);
+	                return;
+	            } catch (QueryResolverException e) {
+	                throw new QueryResolverException(e, "ERR.015.008.0019", QueryPlugin.Util.getString("ERR.015.008.0019", fullName)); //$NON-NLS-1$ //$NON-NLS-2$
+	            }
+			}
+		}
 
-        //List of XML attributes that might match the criteria element,
-        //if the criteria is specified without the optional "@" sign
-        List<ElementSymbol> attributeMatches = new ArrayList<ElementSymbol>(2);
+        List<ElementSymbol> partialMatches = current.values();
 
-        // look up name based on ID match - will work for uuid version
-        try {
+        if (partialMatches.size() != 1) {
+        	// Found multiple matches
+            throw new QueryResolverException("ERR.015.008.0020", QueryPlugin.Util.getString("ERR.015.008.0020", fullName)); //$NON-NLS-1$ //$NON-NLS-2$
+        } 
 
-            Object elementID = metadata.getElementID(critElemName);
-
-            if(elementID != null) {
-                critElemName = metadata.getFullName(elementID);
-            }
-        } catch(QueryMetadataException e) {
-            //e.printStackTrace();
-            // ignore and go on
-        }
-
-        // Walk through each valid element looking for a match
-        for (ElementSymbol currentElem : validElements) {
-            // Look for exact match
-            if(currentElem.getName().equalsIgnoreCase(critElemName)) {
-                exactMatch = currentElem;
-                break;
-            }
-
-            if(currentElem.getName().toUpperCase().endsWith(critElemNameSuffix)) {
-                partialMatches.add(currentElem);
-            } else {
-                // The criteria element might be referring to an
-                // XML attribute, but might not have the optional
-                // "@" sign
-                String currentElemName = currentElem.getName();
-                int atSignIndex = currentElemName.indexOf("@"); //$NON-NLS-1$
-                if (atSignIndex != -1){
-                    currentElemName = StringUtil.replace(currentElemName, "@", ""); //$NON-NLS-1$ //$NON-NLS-2$
-                    if(currentElemName.equalsIgnoreCase(critElemName)) {
-                        attributeMatches.add(currentElem);
-                    } else {
-                        currentElemName = currentElemName.toUpperCase();
-                        if(currentElemName.endsWith(critElemNameSuffix)) {
-                            attributeMatches.add(currentElem);
-                        }
-                    }
-                }
-            }
-        }
-
-        // Check for single partial match
-        if(exactMatch == null){
-            if (partialMatches.size() == 1) {
-                exactMatch = partialMatches.get(0);
-            } else if (partialMatches.size() == 0 && attributeMatches.size() == 1){
-                exactMatch = attributeMatches.get(0);
-            }
-        }
-
-        if(exactMatch != null) {
-            String name = elem.getOutputName();
-            // Resolve based on exact match
-            elem.setShortName(exactMatch.getShortName());
-            elem.setShortCanonicalName(exactMatch.getShortCanonicalName());
-            elem.setMetadataID(exactMatch.getMetadataID());
-            elem.setType(exactMatch.getType());
-            elem.setGroupSymbol(exactMatch.getGroupSymbol());
-            elem.setOutputName(name);
-        } else if(partialMatches.size() == 0 && attributeMatches.size() == 0){
-            try {
-                ResolverVisitor.resolveLanguageObject(elem, Collections.EMPTY_LIST, externalGroups, metadata);
-            } catch (QueryResolverException e) {
-                throw new QueryResolverException(e, "ERR.015.008.0019", QueryPlugin.Util.getString("ERR.015.008.0019", critElemName)); //$NON-NLS-1$ //$NON-NLS-2$
-            }
-        } else {
-            // Found multiple matches
-            throw new QueryResolverException("ERR.015.008.0020", QueryPlugin.Util.getString("ERR.015.008.0020", critElemName)); //$NON-NLS-1$ //$NON-NLS-2$
-        }
+        ElementSymbol exactMatch = partialMatches.get(0);
+        String name = elem.getOutputName();
+        // Resolve based on exact match
+        elem.setShortName(exactMatch.getShortName());
+        elem.setShortCanonicalName(exactMatch.getShortCanonicalName());
+        elem.setMetadataID(exactMatch.getMetadataID());
+        elem.setType(exactMatch.getType());
+        elem.setGroupSymbol(exactMatch.getGroupSymbol());
+        elem.setOutputName(name);
     }
 
-    static List<ElementSymbol> getElementsInDocument(GroupSymbol group, QueryMetadataInterface metadata)
-        throws QueryMetadataException, TeiidComponentException {
-        return ResolverUtil.resolveElementsInGroup(group, metadata);
-    }
-    
-    static List<ElementSymbol> getElementsUnderNode(ElementSymbol node, List<ElementSymbol> validElements, QueryMetadataInterface metadata) 
+    static List<ElementSymbol> getElementsUnderNode(Object mid, Collection<ElementSymbol> validElements, QueryMetadataInterface metadata) 
         throws TeiidComponentException, QueryMetadataException {
         
         List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
-        String nodeName = metadata.getFullName(node.getMetadataID());
+        String nodeName = metadata.getFullName(mid);
         for (ElementSymbol validElement : validElements) {
             String qualifiedName = validElement.getName();
-            if (qualifiedName.equals(nodeName) || qualifiedName.startsWith(nodeName+ElementSymbol.SEPARATOR)) {
+            if (StringUtil.startsWithIgnoreCase(qualifiedName, nodeName) && (qualifiedName.length() == nodeName.length() || qualifiedName.charAt(nodeName.length()) == '.')) {
                 elements.add(validElement);
             }
         }

Modified: branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -333,7 +333,7 @@
     	List<SingleElementSymbol> knownElements = command.getProjectedQuery().getSelect().getProjectedSymbols();
     	
     	boolean isSimpleQuery = false;
-    	List fromClauseGroups = Collections.emptyList();
+    	List<GroupSymbol> fromClauseGroups = Collections.emptyList();
         
         if (command instanceof Query) {
         	Query query = (Query)command;
@@ -938,7 +938,7 @@
 			return;
 		}
 		if (query.getFrom().getClauses().size() == 1) {
-			findKeyPreserved((FromClause)query.getFrom().getClauses().get(0), keyPreservingGroups, metadata);
+			findKeyPreserved(query.getFrom().getClauses().get(0), keyPreservingGroups, metadata);
 			return;
 		}
 		//non-ansi join

Modified: branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/resolver/util/ResolverVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,9 +34,11 @@
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.api.exception.query.UnresolvedSymbolDescription;
+import org.teiid.core.CoreConstants;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.types.DataTypeManager.DefaultDataClasses;
+import org.teiid.core.util.StringUtil;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.function.FunctionDescriptor;
 import org.teiid.query.function.FunctionForm;
@@ -57,6 +59,7 @@
 import org.teiid.query.sql.lang.SubqueryCompareCriteria;
 import org.teiid.query.sql.lang.SubquerySetCriteria;
 import org.teiid.query.sql.navigator.PostOrderNavigator;
+import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.CaseExpression;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.DerivedColumn;
@@ -74,7 +77,9 @@
 
 public class ResolverVisitor extends LanguageVisitor {
     
-    private static class ElementMatch {
+    private static final String SYS_PREFIX = CoreConstants.SYSTEM_MODEL + '.';
+
+	private static class ElementMatch {
     	ElementSymbol element;
     	GroupSymbol group;
     	
@@ -423,6 +428,17 @@
 			handleException(e);
 		}
     }
+    
+    @Override
+    public void visit(AggregateSymbol obj) {
+    	if (obj.getCondition() != null) {
+			try {
+				obj.setCondition(ResolverUtil.convertExpression(obj.getCondition(), DataTypeManager.DefaultDataTypes.BOOLEAN, metadata));
+			} catch (QueryResolverException e) {
+				handleException(e);
+			}
+    	}
+    }
 
     public TeiidComponentException getComponentException() {
         return this.componentException;
@@ -517,11 +533,11 @@
 	    
 	    if(fd.getName().equalsIgnoreCase(FunctionLibrary.CONVERT) || fd.getName().equalsIgnoreCase(FunctionLibrary.CAST)) {
 	        String dataType = (String) ((Constant)args[1]).getValue();
-	        Class dataTypeClass = DataTypeManager.getDataTypeClass(dataType);
+	        Class<?> dataTypeClass = DataTypeManager.getDataTypeClass(dataType);
 	        fd = library.findTypedConversionFunction(args[0].getType(), dataTypeClass);
 	
 	        // Verify that the type conversion from src to type is even valid
-	        Class srcTypeClass = args[0].getType();
+	        Class<?> srcTypeClass = args[0].getType();
 	        if(srcTypeClass != null && dataTypeClass != null &&
 	           !srcTypeClass.equals(dataTypeClass) &&
 	           !DataTypeManager.isTransformable(srcTypeClass, dataTypeClass)) {
@@ -533,9 +549,11 @@
 			fd = library.copyFunctionChangeReturnType(fd, lookup.getReturnElement().getType());
 	    } 
 	
-	    // Resolve the function
 	    function.setFunctionDescriptor(fd);
 	    function.setType(fd.getReturnType());
+	    if (CoreConstants.SYSTEM_MODEL.equals(fd.getSchema()) && StringUtil.startsWithIgnoreCase(function.getName(), SYS_PREFIX)) {
+	    	function.setName(function.getName().substring(SYS_PREFIX.length()));
+	    }
 	}
 
 	/**

Modified: branches/as7/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/rewriter/QueryRewriter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -52,8 +52,11 @@
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.types.Transform;
 import org.teiid.core.util.Assertion;
 import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.language.SQLConstants;
+import org.teiid.language.Like.MatchMode;
 import org.teiid.language.SQLConstants.NonReserved;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.eval.Evaluator;
@@ -64,7 +67,6 @@
 import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.metadata.TempMetadataID;
 import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.optimizer.relational.rules.NewCalculateCostUtil;
 import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria;
 import org.teiid.query.optimizer.relational.rules.RulePlaceAccess;
 import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria.PlannedResult;
@@ -240,6 +242,7 @@
      * @throws QueryValidatorException
      */
 	private Command rewriteCommand(Command command, boolean removeOrderBy) throws TeiidComponentException, TeiidProcessingException{
+		boolean oldRewriteAggs = rewriteAggs;
 		QueryMetadataInterface oldMetadata = metadata;
 		CreateUpdateProcedureCommand oldProcCommand = procCommand;
         
@@ -299,6 +302,7 @@
             	break;
 		}
         
+        this.rewriteAggs = oldRewriteAggs;
         this.metadata = oldMetadata;
         this.procCommand = oldProcCommand;
         return command;
@@ -322,19 +326,14 @@
 
 	private Block rewriteBlock(Block block)
 								 throws TeiidComponentException, TeiidProcessingException{
-		List statements = block.getStatements();
-        Iterator stmtIter = statements.iterator();
+		List<Statement> statements = block.getStatements();
+        Iterator<Statement> stmtIter = statements.iterator();
 
-		List newStmts = new ArrayList(statements.size());
+		List<Statement> newStmts = new ArrayList<Statement>(statements.size());
 		// plan each statement in the block
         while(stmtIter.hasNext()) {
-			Statement stmnt = (Statement) stmtIter.next();
-			Object newStmt = rewriteStatement(stmnt);
-			if(newStmt instanceof Statement) {
-				newStmts.add(newStmt);
-			} else if (newStmt instanceof List) {
-			    newStmts.addAll((List)newStmt);
-            }
+			Statement stmnt = stmtIter.next();
+			rewriteStatement(stmnt, newStmts);
         }
 
         block.setStatements(newStmts);
@@ -342,7 +341,7 @@
         return block;
 	 }
 
-	private Object rewriteStatement(Statement statement)
+	private void rewriteStatement(Statement statement, List<Statement> newStmts)
 								 throws TeiidComponentException, TeiidProcessingException{
 
         // evaluate the HAS Criteria on the procedure and rewrite
@@ -356,13 +355,15 @@
 				ifStmt.setCondition(evalCrit);
 				if(evalCrit.equals(TRUE_CRITERIA)) {
 					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
-					return ifblock.getStatements();
+					newStmts.addAll(ifblock.getStatements());
+					return;
 				} else if(evalCrit.equals(FALSE_CRITERIA) || evalCrit.equals(UNKNOWN_CRITERIA)) {
 					if(ifStmt.hasElseBlock()) {
 						Block elseBlock = rewriteBlock(ifStmt.getElseBlock());
-						return elseBlock.getStatements();
+						newStmts.addAll(elseBlock.getStatements());
+						return;
 					} 
-                    return null;
+                    return;
 				} else {
 					Block ifblock = rewriteBlock(ifStmt.getIfBlock());
 					ifStmt.setIfBlock(ifblock);
@@ -371,7 +372,7 @@
 						ifStmt.setElseBlock(elseBlock);
 					}
 				}
-				return ifStmt;
+				break;
             case Statement.TYPE_ERROR: 
             case Statement.TYPE_DECLARE:
             case Statement.TYPE_ASSIGNMENT:
@@ -383,7 +384,7 @@
 					expr = rewriteExpressionDirect(expr);
 	                exprStmt.setExpression(expr);
 				}
-				return exprStmt;
+				break;
             case Statement.TYPE_COMMAND:
 				CommandStatement cmdStmt = (CommandStatement) statement;
                 rewriteSubqueryContainer(cmdStmt, false);
@@ -391,10 +392,10 @@
 				if(cmdStmt.getCommand().getType() == Command.TYPE_UPDATE) {
                     Update update = (Update)cmdStmt.getCommand();
                     if (update.getChangeList().isEmpty()) {
-                        return null;
+                        return;
                     }
 				}
-                return statement;
+				break;
             case Statement.TYPE_LOOP: 
                 LoopStatement loop = (LoopStatement)statement; 
                 
@@ -403,10 +404,9 @@
                 rewriteBlock(loop.getBlock());
                 
                 if (loop.getBlock().getStatements().isEmpty()) {
-                    return null;
+                    return;
                 }
-                
-                return loop;
+                break;
             case Statement.TYPE_WHILE:
                 WhileStatement whileStatement = (WhileStatement) statement;
                 Criteria crit = whileStatement.getCondition();
@@ -416,18 +416,16 @@
                 if(crit.equals(TRUE_CRITERIA)) {
                     throw new QueryValidatorException(QueryPlugin.Util.getString("QueryRewriter.infinite_while")); //$NON-NLS-1$
                 } else if(crit.equals(FALSE_CRITERIA) || crit.equals(UNKNOWN_CRITERIA)) {
-                    return null;
+                    return;
                 } 
                 whileStatement.setBlock(rewriteBlock(whileStatement.getBlock()));
                 
                 if (whileStatement.getBlock().getStatements().isEmpty()) {
-                    return null;
+                    return;
                 }
-                
-                return whileStatement;
-			default:
-				return statement;
+                break;
 		}
+		newStmts.add(statement);
 	}
     
     /** 
@@ -605,9 +603,9 @@
         From from = query.getFrom();
         if(from != null){
             List<FromClause> clauses = new ArrayList<FromClause>(from.getClauses().size());
-            Iterator clauseIter = from.getClauses().iterator();
+            Iterator<FromClause> clauseIter = from.getClauses().iterator();
             while(clauseIter.hasNext()) {
-                clauses.add( rewriteFromClause(query, (FromClause) clauseIter.next()) );
+                clauses.add( rewriteFromClause(query, clauseIter.next()) );
             }
             from.setClauses(clauses);
         } else {
@@ -634,7 +632,7 @@
         }
         
         if (from != null && !query.getIsXML()) {
-        	writeSubqueriesAsJoins(query);
+        	rewriteSubqueriesAsJoins(query);
         }
 
         query = rewriteGroupBy(query);
@@ -667,7 +665,7 @@
         return query;
     }
 
-	private void writeSubqueriesAsJoins(Query query)
+	private void rewriteSubqueriesAsJoins(Query query)
 			throws TeiidComponentException, QueryMetadataException,
 			QueryResolverException {
 		if (query.getCriteria() == null) {
@@ -704,16 +702,6 @@
 			if (!rmc.planQuery(groups, requiresDistinct, plannedResult)) {
 				continue;
 			}
-			if (requiresDistinct) {
-				//check for key preservation
-				HashSet<GroupSymbol> keyPreservingGroups = new HashSet<GroupSymbol>();
-				ResolverUtil.findKeyPreserved(query, keyPreservingGroups, metadata);
-				if (NewCalculateCostUtil.usesKey(plannedResult.leftExpressions, keyPreservingGroups, metadata, true) && plannedResult.madeDistinct) {
-					//if key perserved then the semi-join will remain in-tact without make the other query distinct
-					plannedResult.madeDistinct = false;
-					plannedResult.query.getSelect().setDistinct(false);
-				}
-			}
 			crits.remove();
 			
 			GroupSymbol viewName = RulePlaceAccess.recontextSymbol(new GroupSymbol("X"), names); //$NON-NLS-1$
@@ -722,9 +710,9 @@
 			Query q = createInlineViewQuery(viewName, plannedResult.query, metadata, plannedResult.query.getSelect().getProjectedSymbols());
 			
 			Iterator<SingleElementSymbol> iter = q.getSelect().getProjectedSymbols().iterator();
-		    HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
+		    HashMap<Expression, Expression> expressionMap = new HashMap<Expression, Expression>();
 		    for (SingleElementSymbol symbol : plannedResult.query.getSelect().getProjectedSymbols()) {
-		        expressionMap.put(SymbolMap.getExpression(symbol), iter.next());
+		        expressionMap.put(SymbolMap.getExpression(symbol), SymbolMap.getExpression(iter.next()));
 		    }
 			for (int i = 0; i < plannedResult.leftExpressions.size(); i++) {
 				plannedResult.nonEquiJoinCriteria.add(new CompareCriteria(SymbolMap.getExpression((Expression)plannedResult.leftExpressions.get(i)), CompareCriteria.EQ, (Expression)plannedResult.rightExpressions.get(i)));
@@ -732,7 +720,11 @@
 			Criteria mappedCriteria = Criteria.combineCriteria(plannedResult.nonEquiJoinCriteria);
 			ExpressionMappingVisitor.mapExpressions(mappedCriteria, expressionMap);
 			query.setCriteria(Criteria.combineCriteria(query.getCriteria(), mappedCriteria));
-		    query.getFrom().addClause((FromClause) q.getFrom().getClauses().get(0));
+			FromClause clause = q.getFrom().getClauses().get(0);
+			if (plannedResult.makeInd) {
+				clause.setMakeInd(true);
+			}
+		    query.getFrom().addClause(clause);
 		    query.getTemporaryMetadata().putAll(q.getTemporaryMetadata());
 			//transform the query into an inner join 
 		}
@@ -766,83 +758,18 @@
 	 * Converts a group by with expressions into a group by with only element symbols and an inline view
 	 * @param query
 	 * @return
-	 * @throws QueryValidatorException
+	 * @throws TeiidProcessingException 
+	 * @throws TeiidComponentException 
 	 */
-	private Query rewriteGroupBy(Query query) throws TeiidComponentException, TeiidProcessingException{
+	private Query rewriteGroupBy(Query query) throws TeiidComponentException, TeiidProcessingException {
 		if (query.getGroupBy() == null) {
+			rewriteAggs = false;
 			return query;
 		}
 		if (isDistinctWithGroupBy(query)) {
 			query.getSelect().setDistinct(false);
 		}
-        // we check for group by expressions here to create an ANSI SQL plan
-        boolean hasExpression = false;
-        for (final Iterator iterator = query.getGroupBy().getSymbols().iterator(); !hasExpression && iterator.hasNext();) {
-            hasExpression = iterator.next() instanceof ExpressionSymbol;
-        } 
-        if (!hasExpression) {
-        	return query;
-        }
-        Select select = query.getSelect();
-        GroupBy groupBy = query.getGroupBy();
-        query.setGroupBy(null);
-        Criteria having = query.getHaving();
-        query.setHaving(null);
-        OrderBy orderBy = query.getOrderBy();
-        query.setOrderBy(null);
-        Limit limit = query.getLimit();
-        query.setLimit(null);
-        Into into = query.getInto();
-        query.setInto(null);
-        Set<Expression> newSelectColumns = new HashSet<Expression>();
-        for (final Iterator iterator = groupBy.getSymbols().iterator(); iterator.hasNext();) {
-            newSelectColumns.add(SymbolMap.getExpression((SingleElementSymbol)iterator.next()));
-        }
-        Set<AggregateSymbol> aggs = new HashSet<AggregateSymbol>();
-        aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(select, true));
-        if (having != null) {
-            aggs.addAll(AggregateSymbolCollectorVisitor.getAggregates(having, true));
-        }
-        for (AggregateSymbol aggregateSymbol : aggs) {
-            if (aggregateSymbol.getExpression() != null) {
-                Expression expr = aggregateSymbol.getExpression();
-                newSelectColumns.add(SymbolMap.getExpression(expr));
-            }
-        }
-        Select innerSelect = new Select();
-        int index = 0;
-        for (Expression expr : newSelectColumns) {
-            if (expr instanceof SingleElementSymbol) {
-                innerSelect.addSymbol((SingleElementSymbol)expr);
-            } else {
-                innerSelect.addSymbol(new ExpressionSymbol("EXPR" + index++ , expr)); //$NON-NLS-1$
-            }
-        }
-        query.setSelect(innerSelect);
-        Query outerQuery = null;
-        try {
-            outerQuery = QueryRewriter.createInlineViewQuery(new GroupSymbol("X"), query, metadata, query.getSelect().getProjectedSymbols()); //$NON-NLS-1$
-        } catch (TeiidException err) {
-            throw new TeiidRuntimeException(err);
-        }
-        Iterator<SingleElementSymbol> iter = outerQuery.getSelect().getProjectedSymbols().iterator();
-        HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
-        for (SingleElementSymbol symbol : query.getSelect().getProjectedSymbols()) {
-            expressionMap.put(SymbolMap.getExpression(symbol), iter.next());
-        }
-        ExpressionMappingVisitor.mapExpressions(groupBy, expressionMap);
-        outerQuery.setGroupBy(groupBy);
-        ExpressionMappingVisitor.mapExpressions(having, expressionMap);
-        outerQuery.setHaving(having);
-        ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
-        outerQuery.setOrderBy(orderBy);
-        outerQuery.setLimit(limit);
-        ExpressionMappingVisitor.mapExpressions(select, expressionMap);
-        outerQuery.setSelect(select);
-        outerQuery.setInto(into);
-        outerQuery.setOption(query.getOption());
-        query = outerQuery;
-        rewriteExpressions(innerSelect);
+		rewriteExpressions(query.getGroupBy());
 		return query;
 	}
 	
@@ -855,7 +782,7 @@
 		for (SingleElementSymbol selectExpr : query.getSelect().getProjectedSymbols()) {
 			selectExpressions.add(SymbolMap.getExpression(selectExpr));
 		}
-		for (SingleElementSymbol groupByExpr :  (List<SingleElementSymbol>)groupBy.getSymbols()) {
+		for (Expression groupByExpr : groupBy.getSymbols()) {
 			if (!selectExpressions.contains(groupByExpr)) {
 				return false;
 			}
@@ -883,11 +810,11 @@
         try {
             PostOrderNavigator.doVisit(obj, visitor);
         } catch (TeiidRuntimeException err) {
-            if (err.getChild() instanceof TeiidComponentException) {
-                throw (TeiidComponentException)err.getChild();
+            if (err.getCause() instanceof TeiidComponentException) {
+                throw (TeiidComponentException)err.getCause();
             } 
-            if (err.getChild() instanceof TeiidProcessingException) {
-                throw (TeiidProcessingException)err.getChild();
+            if (err.getCause() instanceof TeiidProcessingException) {
+                throw (TeiidProcessingException)err.getCause();
             } 
             throw err;
         }
@@ -910,57 +837,14 @@
         
         LinkedList<OrderByItem> unrelatedItems = new LinkedList<OrderByItem>();
         
-        boolean hasUnrelatedExpression = rewriteOrderBy(queryCommand, orderBy,
-				projectedSymbols, unrelatedItems);
+        rewriteOrderBy(queryCommand, orderBy, projectedSymbols, unrelatedItems);
         
-        if (orderBy.getVariableCount() == 0 || !hasUnrelatedExpression) {
-        	return queryCommand;
-        } 
-        
-        int originalSymbolCount = select.getProjectedSymbols().size();
-
-        //add unrelated to select
-        for (OrderByItem orderByItem : unrelatedItems) {
-            select.addSymbol(orderByItem.getSymbol());				
-		}
-        makeSelectUnique(select, false);
-        
-        Query query = queryCommand.getProjectedQuery();
-        
-        Into into = query.getInto();
-        query.setInto(null);
-        Limit limit = query.getLimit();
-        query.setLimit(null);
-        query.setOrderBy(null);
-        
-        Query top = null;
-        
-        try {
-        	top = createInlineViewQuery(new GroupSymbol("X"), query, metadata, select.getProjectedSymbols()); //$NON-NLS-1$
-			Iterator<SingleElementSymbol> iter = top.getSelect().getProjectedSymbols().iterator();
-		    HashMap<Expression, SingleElementSymbol> expressionMap = new HashMap<Expression, SingleElementSymbol>();
-		    for (SingleElementSymbol symbol : select.getProjectedSymbols()) {
-		    	SingleElementSymbol ses = iter.next();
-		        expressionMap.put(SymbolMap.getExpression(symbol), ses);
-		        expressionMap.put(new ElementSymbol(symbol.getName()), ses);
-		    }
-		    ExpressionMappingVisitor.mapExpressions(orderBy, expressionMap);
-		    //now the order by should only contain element symbols
-		} catch (TeiidException err) {
-            throw new TeiidRuntimeException(err);
-        }
-		List symbols = top.getSelect().getSymbols();
-		top.getSelect().setSymbols(symbols.subList(0, originalSymbolCount));
-		top.setInto(into);
-		top.setLimit(limit);
-		top.setOrderBy(orderBy);
-		return top;
+    	return queryCommand;
     }
 
-	public static boolean rewriteOrderBy(QueryCommand queryCommand,
+	public static void rewriteOrderBy(QueryCommand queryCommand,
 			final OrderBy orderBy, final List projectedSymbols,
 			LinkedList<OrderByItem> unrelatedItems) {
-		boolean hasUnrelatedExpression = false;
 		HashSet<Expression> previousExpressions = new HashSet<Expression>();
         for (int i = 0; i < orderBy.getVariableCount(); i++) {
         	SingleElementSymbol querySymbol = orderBy.getVariable(i);
@@ -977,14 +861,11 @@
                 orderBy.removeOrderByItem(i--);
         	} else if (!isUnrelated) {
         		orderBy.getOrderByItems().get(i).setSymbol((SingleElementSymbol)querySymbol.clone());
-        	} else {
-        		hasUnrelatedExpression = true;
         	}
         }
         if (orderBy.getVariableCount() == 0) {
         	queryCommand.setOrderBy(null);
         } 
-		return hasUnrelatedExpression;
 	}
     
     /**
@@ -1589,26 +1470,29 @@
      */
     private Criteria rewriteCriteria(SubqueryCompareCriteria criteria) throws TeiidComponentException, TeiidProcessingException{
     	
-    	if (criteria.getCommand().getProcessorPlan() == null && criteria.getPredicateQuantifier() != SubqueryCompareCriteria.ALL) {
-    		if (criteria.getOperator() == CompareCriteria.EQ || criteria.getOperator() == CompareCriteria.NE) {
+    	if (criteria.getCommand().getProcessorPlan() == null) {
+    		if ((criteria.getOperator() == CompareCriteria.EQ && criteria.getPredicateQuantifier() != SubqueryCompareCriteria.ALL)
+    				|| (criteria.getOperator() == CompareCriteria.NE && criteria.getPredicateQuantifier() == SubqueryCompareCriteria.ALL)) {
     			SubquerySetCriteria result = new SubquerySetCriteria(criteria.getLeftExpression(), criteria.getCommand());
     			result.setNegated(criteria.getOperator() == CompareCriteria.NE);
     			return rewriteCriteria(result);
     		}
-    		CompareCriteria cc = new CompareCriteria();
-    		cc.setLeftExpression(criteria.getLeftExpression());
-    		Query q = createInlineViewQuery(new GroupSymbol("X"), criteria.getCommand(), metadata, criteria.getCommand().getProjectedSymbols()); //$NON-NLS-1$
-    		SingleElementSymbol ses = q.getProjectedSymbols().get(0);
-    		Expression expr = SymbolMap.getExpression(ses);
-    		q.getSelect().clearSymbols();
-    		AggregateSymbol.Type type = Type.MAX;
-    		if (criteria.getOperator() == CompareCriteria.GT || criteria.getOperator() == CompareCriteria.GE) {
-    			type = Type.MIN;
+    		if (criteria.getPredicateQuantifier() != SubqueryCompareCriteria.ALL && criteria.getOperator() != CompareCriteria.EQ && criteria.getOperator() != CompareCriteria.NE) {
+	    		CompareCriteria cc = new CompareCriteria();
+	    		cc.setLeftExpression(criteria.getLeftExpression());
+	    		Query q = createInlineViewQuery(new GroupSymbol("X"), criteria.getCommand(), metadata, criteria.getCommand().getProjectedSymbols()); //$NON-NLS-1$
+	    		SingleElementSymbol ses = q.getProjectedSymbols().get(0);
+	    		Expression expr = SymbolMap.getExpression(ses);
+	    		q.getSelect().clearSymbols();
+	    		AggregateSymbol.Type type = Type.MAX;
+	    		if (criteria.getOperator() == CompareCriteria.GT || criteria.getOperator() == CompareCriteria.GE) {
+	    			type = Type.MIN;
+	    		}
+	    		q.getSelect().addSymbol(new AggregateSymbol(ses.getName(), type.name(), false, expr));
+	    		cc.setRightExpression(new ScalarSubquery(q));
+				cc.setOperator(criteria.getOperator());
+	    		return rewriteCriteria(cc);
     		}
-    		q.getSelect().addSymbol(new AggregateSymbol(ses.getName(), type.name(), false, expr));
-    		cc.setRightExpression(new ScalarSubquery(q));
-			cc.setOperator(criteria.getOperator());
-    		return rewriteCriteria(cc);
     	}
 
         Expression leftExpr = rewriteExpressionDirect(criteria.getLeftExpression());
@@ -1667,6 +1551,7 @@
     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);
+	private boolean rewriteAggs = true;
 
     /**
      * @param criteria
@@ -2133,24 +2018,34 @@
             Constant constant = (Constant) rightExpr;
             String value = (String) constant.getValue();
 
-            char escape = criteria.getEscapeChar();
-
-            // Check whether escape char is unnecessary and remove it
-            if(escape != MatchCriteria.NULL_ESCAPE_CHAR && value.indexOf(escape) < 0) {
-                criteria.setEscapeChar(MatchCriteria.NULL_ESCAPE_CHAR);
+            if (criteria.getMode() != MatchMode.REGEX) {
+	            char escape = criteria.getEscapeChar();
+	
+	            // Check whether escape char is unnecessary and remove it
+	            if(escape != MatchCriteria.NULL_ESCAPE_CHAR && value.indexOf(escape) < 0) {
+	                criteria.setEscapeChar(MatchCriteria.NULL_ESCAPE_CHAR);
+	            }
+	
+	            // if the value of this string constant is '%', then we know the crit will 
+	            // always be true                    
+	            if ( value.equals( String.valueOf(MatchCriteria.WILDCARD_CHAR)) ) { 
+	                return getSimpliedCriteria(criteria, criteria.getLeftExpression(), !criteria.isNegated(), true);                                        
+	            } 
+	            
+	            if (criteria.getMode() == MatchMode.SIMILAR) {
+	            	//regex is more widely supported
+	            	criteria.setMode(MatchMode.REGEX);
+	            	criteria.setRightExpression(new Constant(Evaluator.SIMILAR_TO_REGEX.getPatternString(value, escape)));
+	            	criteria.setEscapeChar(MatchCriteria.NULL_ESCAPE_CHAR);
+	            } else if(DataTypeManager.DefaultDataClasses.STRING.equals(criteria.getLeftExpression().getType()) 
+	            		&& value.indexOf(escape) < 0 
+	            		&& value.indexOf(MatchCriteria.MATCH_CHAR) < 0 
+	            		&& value.indexOf(MatchCriteria.WILDCARD_CHAR) < 0) {
+	            	// if both left and right expressions are strings, and the LIKE match characters ('*', '_') are not present 
+		            //  in the right expression, rewrite the criteria as EQUALs rather than LIKE
+	            	return rewriteCriteria(new CompareCriteria(criteria.getLeftExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, criteria.getRightExpression()));
+	            }
             }
-
-            // if the value of this string constant is '%', then we know the crit will 
-            // always be true                    
-            if ( value.equals( String.valueOf(MatchCriteria.WILDCARD_CHAR)) ) { 
-                return getSimpliedCriteria(criteria, criteria.getLeftExpression(), !criteria.isNegated(), true);                                        
-            } 
-            
-            // if both left and right expressions are strings, and the LIKE match characters ('*', '_') are not present 
-            //  in the right expression, rewrite the criteria as EQUALs rather than LIKE
-            if(DataTypeManager.DefaultDataClasses.STRING.equals(criteria.getLeftExpression().getType()) && value.indexOf(escape) < 0 && value.indexOf(MatchCriteria.MATCH_CHAR) < 0 && value.indexOf(MatchCriteria.WILDCARD_CHAR) < 0) {
-            	return rewriteCriteria(new CompareCriteria(criteria.getLeftExpression(), criteria.isNegated()?CompareCriteria.NE:CompareCriteria.EQ, criteria.getRightExpression()));
-            }
         }
 
 		return criteria;
@@ -2361,16 +2256,21 @@
     			expression.setAggregateFunction(Type.MAX);
     		}
     	}
-    	if ((expression.getAggregateFunction() == Type.MAX || expression.getAggregateFunction() == Type.MIN)
-				&& EvaluatableVisitor.willBecomeConstant(expression.getExpression())) {
-			try {
-				return new ExpressionSymbol(expression.getName(), ResolverUtil
-						.convertExpression(expression.getExpression(),DataTypeManager.getDataTypeName(expression.getType()), metadata));
-			} catch (QueryResolverException e) {
-				//should not happen, so throw as a runtime
-				throw new TeiidRuntimeException(e);
-			}
-		}
+    	if ((expression.getAggregateFunction() == Type.MAX || expression.getAggregateFunction() == Type.MIN) 
+    			&& rewriteAggs && expression.getExpression() != null && EvaluatableVisitor.willBecomeConstant(expression.getExpression())) {
+    		return expression.getExpression();
+    	}
+    	if (expression.getExpression() != null && expression.getCondition() != null && !expression.respectsNulls()) {
+    		Expression cond = expression.getCondition();
+    		Expression ex = expression.getExpression();
+    		if (!(cond instanceof Criteria)) {
+    			cond = new ExpressionCriteria(cond);
+    		}
+    		SearchedCaseExpression sce = new SearchedCaseExpression(Arrays.asList(cond), Arrays.asList(ex));
+    		sce.setType(ex.getType());
+    		expression.setCondition(null);
+    		expression.setExpression(sce);
+    	}
 		return expression;
 	}
    
@@ -2387,6 +2287,7 @@
     	FUNCTION_MAP.put(FunctionLibrary.PARSETIME.toLowerCase(), 7);
     	FUNCTION_MAP.put(FunctionLibrary.FORMATDATE.toLowerCase(), 8);
     	FUNCTION_MAP.put(FunctionLibrary.FORMATTIME.toLowerCase(), 9);
+    	FUNCTION_MAP.put(SourceSystemFunctions.TRIM.toLowerCase(), 10);
     }
     
 	private Expression rewriteFunction(Function function) throws TeiidComponentException, TeiidProcessingException{
@@ -2513,7 +2414,27 @@
 				function.getArgs()[0] = ResolverUtil.getConversion(function.getArg(0), DataTypeManager.getDataTypeName(function.getArg(0).getType()), DataTypeManager.DefaultDataTypes.TIMESTAMP, false, funcLibrary);
 				break;
 			}
+			case 10: {
+				if (new Constant(" ").equals(function.getArg(1))) { //$NON-NLS-1$
+					String spec = (String)((Constant)function.getArg(0)).getValue();
+					Expression string = function.getArg(2);
+					if (!SQLConstants.Reserved.TRAILING.equalsIgnoreCase(spec)) {
+						function = new Function(SourceSystemFunctions.LTRIM, new Expression[] {string});
+						FunctionDescriptor descriptor = funcLibrary.findFunction(SourceSystemFunctions.LTRIM, new Class[] { DataTypeManager.DefaultDataClasses.STRING });
+						function.setFunctionDescriptor(descriptor);
+						function.setType(DataTypeManager.DefaultDataClasses.STRING);
+						string = function;
+					}
+					if (!SQLConstants.Reserved.LEADING.equalsIgnoreCase(spec)) {
+						function = new Function(SourceSystemFunctions.RTRIM, new Expression[] {string});
+						FunctionDescriptor descriptor = funcLibrary.findFunction(SourceSystemFunctions.RTRIM, new Class[] { DataTypeManager.DefaultDataClasses.STRING });
+						function.setFunctionDescriptor(descriptor);
+						function.setType(DataTypeManager.DefaultDataClasses.STRING);
+					}
+				}
+				break;
 			}
+			}
 		}
 						
 		Expression[] args = function.getArgs();
@@ -2528,17 +2449,44 @@
         }
         function.setArgs(newArgs);
 
-        if( FunctionLibrary.isConvert(function) &&
-            newArgs[1] instanceof Constant) {
-            
-            Class srcType = newArgs[0].getType();
-            String tgtTypeName = (String) ((Constant)newArgs[1]).getValue();
-            Class tgtType = DataTypeManager.getDataTypeClass(tgtTypeName);
+        if( FunctionLibrary.isConvert(function)) {
+            Class<?> srcType = newArgs[0].getType();
+            Class<?> tgtType = function.getType();
 
             if(srcType != null && tgtType != null && srcType.equals(tgtType)) {
-                return newArgs[0];
+                return newArgs[0]; //unnecessary conversion
             }
-
+            
+            if (!(newArgs[0] instanceof Function) || tgtType == DataTypeManager.DefaultDataClasses.OBJECT) {
+            	return function;
+            }
+        	Function nested = (Function) newArgs[0];
+        	if (!FunctionLibrary.isConvert(nested)) {
+        		return function;
+        	}
+    		Class<?> nestedType = nested.getArgs()[0].getType();
+    		
+            Transform t = DataTypeManager.getTransform(nestedType, nested.getType());
+            if (t.isExplicit()) {
+            	//explicit conversions are required
+            	return function;
+            }
+            if (DataTypeManager.getTransform(nestedType, tgtType) == null) {
+            	//no direct conversion exists
+            	return function;
+            }
+    		//can't remove a convert that would alter the lexical form
+    		if (tgtType == DataTypeManager.DefaultDataClasses.STRING &&
+    				(nestedType == DataTypeManager.DefaultDataClasses.BOOLEAN
+    				|| nestedType == DataTypeManager.DefaultDataClasses.DATE
+    				|| nestedType == DataTypeManager.DefaultDataClasses.TIME
+    				|| tgtType == DataTypeManager.DefaultDataClasses.BIG_DECIMAL
+    				|| tgtType == DataTypeManager.DefaultDataClasses.FLOAT
+    				|| (tgtType == DataTypeManager.DefaultDataClasses.DOUBLE && srcType != DataTypeManager.DefaultDataClasses.FLOAT))) {
+    			return function;
+    		}
+        	//nested implicit transform is not needed
+        	return rewriteExpressionDirect(ResolverUtil.getConversion(nested.getArgs()[0], DataTypeManager.getDataTypeName(nestedType), DataTypeManager.getDataTypeName(tgtType), false, funcLibrary));
         }
 
         //convert DECODESTRING function to CASE expression

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageObject.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageObject.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageObject.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,7 +23,7 @@
 package org.teiid.query.sql;
 
 import java.util.ArrayList;
-import java.util.List;
+import java.util.Collection;
 
 /**
  * This is the primary interface for all language objects.  It extends a few 
@@ -47,7 +47,7 @@
     
     public static class Util {
 
-		public static <S extends LanguageObject, T extends S> ArrayList<S> deepClone(List<T> collection, Class<S> type) {
+		public static <S extends LanguageObject, T extends S> ArrayList<S> deepClone(Collection<T> collection, Class<S> type) {
 			if (collection == null) {
 				return null;
 			}


Property changes on: branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageObject.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/main/java/org/teiid/query/sql/LanguageObject.java:3149-3217
/trunk/engine/src/main/java/org/teiid/query/sql/LanguageObject.java:3188-3382

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/LanguageVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -68,9 +68,8 @@
 import org.teiid.query.sql.lang.XMLTable;
 import org.teiid.query.sql.proc.AssignmentStatement;
 import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.BreakStatement;
+import org.teiid.query.sql.proc.BranchingStatement;
 import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.ContinueStatement;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.proc.CriteriaSelector;
 import org.teiid.query.sql.proc.DeclareStatement;
@@ -83,8 +82,6 @@
 import org.teiid.query.sql.proc.WhileStatement;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.CaseExpression;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.DerivedColumn;
@@ -92,11 +89,14 @@
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.QueryString;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.WindowFunction;
+import org.teiid.query.sql.symbol.WindowSpecification;
 import org.teiid.query.sql.symbol.XMLAttributes;
 import org.teiid.query.sql.symbol.XMLElement;
 import org.teiid.query.sql.symbol.XMLForest;
@@ -171,8 +171,7 @@
     // Visitor methods for symbol objects
     public void visit(AggregateSymbol obj) {}
     public void visit(AliasSymbol obj) {}
-    public void visit(AllInGroupSymbol obj) {}
-    public void visit(AllSymbol obj) {}
+    public void visit(MultipleElementSymbol obj) {}
     public void visit(Constant obj) {}
     public void visit(ElementSymbol obj) {}
     public void visit(ExpressionSymbol obj) {}
@@ -194,8 +193,7 @@
     public void visit(IfStatement obj) {}
     public void visit(RaiseErrorStatement obj) {}
     public void visit(TranslateCriteria obj) {}
-    public void visit(BreakStatement obj) {}
-    public void visit(ContinueStatement obj) {}
+    public void visit(BranchingStatement obj) {}
     public void visit(WhileStatement obj) {}
     public void visit(LoopStatement obj) {}
     public void visit(DynamicCommand obj) {}
@@ -223,4 +221,7 @@
 	public void visit(AlterView obj) {}
 	public void visit(AlterProcedure obj) {}
     public void visit(AlterTrigger obj) {}
+
+	public void visit(WindowFunction windowFunction) {}
+	public void visit(WindowSpecification windowSpecification) {}
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ArrayTable.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -59,7 +59,7 @@
 	}
 
 	@Override
-	public ArrayTable clone() {
+	protected ArrayTable cloneDirect() {
 		ArrayTable clone = new ArrayTable();
 		this.copy(clone);
 		clone.setArrayValue((Expression)this.arrayValue.clone());

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/ExistsCriteria.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,9 +43,11 @@
 	public static class SubqueryHint {
 		public static String MJ = "MJ"; //$NON-NLS-1$
 		public static String NOUNNEST = "NO_UNNEST"; //$NON-NLS-1$
+		public static String DJ = "DJ"; //$NON-NLS-1$
 
 		private boolean mergeJoin;
 	    private boolean noUnnest;
+	    private boolean depJoin;
 	    
 	    public void setMergeJoin(boolean semiJoin) {
 			this.mergeJoin = semiJoin;
@@ -63,6 +65,15 @@
 			return noUnnest;
 		}
 	    
+	    public void setDepJoin(boolean depJoin) {
+			this.depJoin = depJoin;
+			this.mergeJoin = true;
+		}
+	    
+	    public boolean isDepJoin() {
+			return depJoin;
+		}
+	    
 		@Override
 		public boolean equals(Object obj) {
 			if (this == obj) {
@@ -72,13 +83,16 @@
 				return false;
 			}
 			SubqueryHint other = (SubqueryHint) obj;
-			return mergeJoin == other.mergeJoin && noUnnest == other.noUnnest;
+			return mergeJoin == other.mergeJoin 
+			&& noUnnest == other.noUnnest 
+			&& depJoin == other.depJoin;
 		}
 		
 		public SubqueryHint clone() {
 			SubqueryHint clone = new SubqueryHint();
 			clone.mergeJoin = this.mergeJoin;
 			clone.noUnnest = this.noUnnest;
+			clone.depJoin = this.depJoin;
 			return clone;
 		}
 		

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/FromClause.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,6 +26,7 @@
 
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.SQLStringVisitor;
 
 
@@ -37,9 +38,13 @@
  * and may contain criteria.
  */
 public abstract class FromClause implements LanguageObject {
+	
+	public static String MAKEIND = "MAKEIND"; //$NON-NLS-1$
+	
     private boolean optional;
     private boolean makeDep;
     private boolean makeNotDep;
+    private boolean makeInd;
 
     public boolean isOptional() {
         return optional;
@@ -49,9 +54,26 @@
         this.optional = optional;
     }
     
+    public boolean isMakeInd() {
+		return makeInd;
+	}
+    
+    public void setMakeInd(boolean makeInd) {
+		this.makeInd = makeInd;
+	}
+    
     public abstract void acceptVisitor(LanguageVisitor visitor);
-    public abstract void collectGroups(Collection groups);
-    public abstract Object clone();
+    public abstract void collectGroups(Collection<GroupSymbol> groups);
+    protected abstract FromClause cloneDirect();
+    
+    public FromClause clone() {
+    	FromClause clone = cloneDirect();
+    	clone.makeDep = makeDep;
+    	clone.makeInd = makeInd;
+    	clone.makeNotDep = makeNotDep;
+    	clone.optional = optional;
+    	return clone;
+    }
 
     public boolean isMakeDep() {
         return this.makeDep;
@@ -70,7 +92,7 @@
     }
     
     public boolean hasHint() {
-        return optional || makeDep || makeNotDep;
+        return optional || makeDep || makeNotDep || makeInd;
     }
     
     public boolean equals(Object obj) {
@@ -86,7 +108,8 @@
 
         return other.isOptional() == this.isOptional()
                && other.isMakeDep() == this.isMakeDep()
-               && other.isMakeNotDep() == this.isMakeNotDep();
+               && other.isMakeNotDep() == this.isMakeNotDep()
+        	   && other.isMakeInd() == this.isMakeInd();
     }
     
     @Override

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/GroupBy.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/GroupBy.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/GroupBy.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,13 +23,10 @@
 package org.teiid.query.sql.lang;
 
 import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
 import java.util.List;
 
 import org.teiid.core.util.EquivalenceUtil;
 import org.teiid.core.util.HashCodeUtil;
-import org.teiid.query.QueryPlugin;
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.symbol.Expression;
@@ -46,7 +43,7 @@
 public class GroupBy implements LanguageObject {
 
     /** The set of expressions for the data elements to be group. */
-    private List symbols;     // List<Expression>
+    private List<Expression> symbols; 
 
     // =========================================================================
     //                         C O N S T R U C T O R S
@@ -56,15 +53,15 @@
      * Constructs a default instance of this class.
      */
     public GroupBy() {
-        symbols = new ArrayList();
+        symbols = new ArrayList<Expression>();
     }
 
     /**
      * Constructs an instance of this class from an ordered set of symbols.
      * @param symbols The ordered list of {@link org.teiid.query.sql.symbol.ElementSymbol}s
      */
-    public GroupBy( List symbols ) {
-        this.symbols = new ArrayList( symbols );
+    public GroupBy( List<? extends Expression> symbols ) {
+        this.symbols = new ArrayList<Expression>( symbols );
     }
 
     // =========================================================================
@@ -83,7 +80,7 @@
      * Returns an ordered list of the symbols in the GROUP BY
      * @return List of {@link org.teiid.query.sql.symbol.ElementSymbol}s
      */
-    public List getSymbols() {
+    public List<Expression> getSymbols() {
         return symbols;
     }
 
@@ -97,19 +94,6 @@
         }
     }
 
-	/**
-     * Replaces the existing set of symbols with a new collection of symbols
-     * @param symbols Collection of {@link org.teiid.query.sql.symbol.ElementSymbol}s
-     * to replace current symbols with
-     */
-    public void replaceSymbols( Collection symbols ) {
-		if(symbols == null) {
-            throw new IllegalArgumentException(QueryPlugin.Util.getString("ERR.015.010.0003")); //$NON-NLS-1$
-		}
-
-		this.symbols = new ArrayList(symbols);
-    }
-
     public void acceptVisitor(LanguageVisitor visitor) {
         visitor.visit(this);
     }
@@ -123,15 +107,7 @@
 	 * @return Deep copy of object
 	 */
 	public Object clone() {
-	    List thisSymbols = getSymbols();
-	    List copySymbols = new ArrayList(thisSymbols.size());
-	    Iterator iter = thisSymbols.iterator();
-	    while(iter.hasNext()) {
-	    	Expression es = (Expression) iter.next();
-	    	copySymbols.add(es.clone());
-	    }
-
-		return new GroupBy(copySymbols);
+		return new GroupBy(LanguageObject.Util.deepClone(this.symbols, Expression.class));
 	}
 
 	/**

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/JoinPredicate.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,6 +30,7 @@
 import org.teiid.core.util.EquivalenceUtil;
 import org.teiid.core.util.HashCodeUtil;
 import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.symbol.GroupSymbol;
 
 
 /**
@@ -165,7 +166,7 @@
      * Collect all GroupSymbols for this from clause.
      * @param groups Groups to add to
      */
-    public void collectGroups(Collection groups) {
+    public void collectGroups(Collection<GroupSymbol> groups) {
         if(this.leftClause != null) { 
             this.leftClause.collectGroups(groups);
         } 
@@ -223,15 +224,15 @@
 	 * Return deep clone for object
 	 * @return Deep clone
 	 */
-	public Object clone() {
+	protected FromClause cloneDirect() {
 	    FromClause copyLeft = null;
 	    if(this.leftClause != null) { 
-	        copyLeft = (FromClause) this.leftClause.clone();
+	        copyLeft = this.leftClause.clone();
 	    }	
 
 	    FromClause copyRight = null;
 	    if(this.rightClause != null) { 
-	        copyRight = (FromClause) this.rightClause.clone();
+	        copyRight = this.rightClause.clone();
 	    }	
 	    
 		List copyCrits = null;
@@ -245,9 +246,6 @@
 		}
 	    	    
         JoinPredicate clonedJoinPredicate = new JoinPredicate(copyLeft, copyRight, this.joinType, copyCrits);
-        clonedJoinPredicate.setOptional(this.isOptional());
-        clonedJoinPredicate.setMakeDep(this.isMakeDep());
-        clonedJoinPredicate.setMakeNotDep(this.isMakeNotDep());
         return clonedJoinPredicate;
 	}
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/MatchCriteria.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/MatchCriteria.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/MatchCriteria.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,10 +23,15 @@
 package org.teiid.query.sql.lang;
 
 import java.util.Arrays;
+import java.util.List;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
 
 import org.teiid.api.exception.query.ExpressionEvaluationException;
 import org.teiid.core.util.EquivalenceUtil;
 import org.teiid.core.util.HashCodeUtil;
+import org.teiid.core.util.LRUCache;
+import org.teiid.language.Like.MatchMode;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.lang.PredicateCriteria.Negatable;
@@ -61,7 +66,8 @@
 	private char escapeChar = NULL_ESCAPE_CHAR;
 	
     /** Negation flag. Indicates whether the criteria expression contains a NOT. */
-    private boolean negated = false;
+    private boolean negated;
+    private MatchMode mode = MatchMode.LIKE;
     
     /**
      * Constructs a default instance of this class.
@@ -200,10 +206,14 @@
 
         MatchCriteria mc = (MatchCriteria)obj;
 
-        if (isNegated() ^ mc.isNegated()) {
+        if (isNegated() != mc.isNegated()) {
             return false;
         }
         
+        if (this.mode != mc.mode) {
+        	return false;
+        }
+        
         return getEscapeChar() == mc.getEscapeChar() &&
         EquivalenceUtil.areEqual(getLeftExpression(), mc.getLeftExpression()) &&
         EquivalenceUtil.areEqual(getRightExpression(), mc.getRightExpression());
@@ -224,18 +234,36 @@
 	    }	
 	    MatchCriteria criteriaCopy = new MatchCriteria(leftCopy, rightCopy, getEscapeChar());
         criteriaCopy.setNegated(isNegated());
+        criteriaCopy.mode = mode;
         return criteriaCopy;
 	}
 	
+    private final static LRUCache<List<?>, Pattern> patternCache = new LRUCache<List<?>, Pattern>(100);
+    
+    public static Pattern getPattern(String newPattern, String originalPattern, int flags) throws ExpressionEvaluationException {
+    	List<?> key = Arrays.asList(newPattern, flags);
+    	Pattern p = patternCache.get(key);
+        if (p == null) {
+            try {	        
+    	        p = Pattern.compile(newPattern, Pattern.DOTALL);
+    	        patternCache.put(key, p);
+    		} catch(PatternSyntaxException e) {
+                throw new ExpressionEvaluationException(e, "ERR.015.006.0014", QueryPlugin.Util.getString("ERR.015.006.0014", new Object[]{originalPattern, e.getMessage()})); //$NON-NLS-1$ //$NON-NLS-2$
+    		}
+        }
+        return p;
+    }
+
 	/**
      * <p>Utility to convert the pattern into a different match syntax</p>
      */
 	public static class PatternTranslator {
-	    
 	    private char[] reserved;
 	    private char newEscape;
-	    private String newWildCard;
-	    private String newSingleMatch;
+	    private char[] toReplace;
+	    private String[] replacements;
+	    private int flags;
+	    private final LRUCache<List<?>, Pattern> cache = new LRUCache<List<?>, Pattern>(100);
 
 	    /**
 	     * @param newWildCard replacement for %
@@ -243,17 +271,29 @@
 	     * @param reserved sorted array of reserved chars in the new match syntax
 	     * @param newEscape escape char in the new syntax
 	     */
-	    public PatternTranslator(String newWildCard, String newSingleMatch, char[] reserved, char newEscape) {
+	    public PatternTranslator(char[] toReplace, String[] replacements, char[] reserved, char newEscape, int flags) {
 	        this.reserved = reserved;
 	        this.newEscape = newEscape;
-	        this.newSingleMatch = newSingleMatch;
-	        this.newWildCard = newWildCard;
+	        this.toReplace = toReplace;
+	        this.replacements = replacements;
+	        this.flags = flags;
 	    }
 	    
-	    public StringBuffer translate(String pattern, char escape) throws ExpressionEvaluationException {
+	    public Pattern translate(String pattern, char escape) throws ExpressionEvaluationException {
+	        List<?> key = Arrays.asList(pattern, escape);
+	        Pattern result = cache.get(key);
+	        if (result == null) {
+		        String newPattern = getPatternString(pattern, escape);
+		        result = getPattern(newPattern, pattern, flags);
+		        cache.put(key, result);
+	        }
+	        return result;
+	    }
+
+		public String getPatternString(String pattern, char escape)
+				throws ExpressionEvaluationException {
+			StringBuffer newPattern = new StringBuffer("^"); //$NON-NLS-1$
 	        
-	        StringBuffer newPattern = new StringBuffer();
-	        
 	        boolean escaped = false;
 	        
 	        for (int i = 0; i < pattern.length(); i++) {
@@ -266,25 +306,21 @@
 	                } else {
 	                    escaped = true;
 	                }
-	            } else if (character == MatchCriteria.WILDCARD_CHAR) {
-	                if (escaped) {
-	                    appendCharacter(newPattern, character);
-	                    escaped = false;
-	                } else {
-	                    newPattern.append(newWildCard);
-	                }
-	            } else if (character == MatchCriteria.MATCH_CHAR) {
-	                if (escaped) {
-	                    appendCharacter(newPattern, character);
-	                    escaped = false;
-	                } else {
-	                    newPattern.append(newSingleMatch);
-	                }
 	            } else {
-	                if (escaped) {
-	                    throw new ExpressionEvaluationException(QueryPlugin.Util.getString("MatchCriteria.invalid_escape", new Object[] {pattern, new Character(escape)})); //$NON-NLS-1$
-	                }
-	                appendCharacter(newPattern, character);
+	            	int index = Arrays.binarySearch(toReplace, character);
+	            	if (index >= 0) {
+		                if (escaped) {
+		                    appendCharacter(newPattern, character);
+		                    escaped = false;
+		                } else {
+		                    newPattern.append(replacements[index]);
+		                }
+	            	} else {
+		                if (escaped) {
+		                    throw new ExpressionEvaluationException(QueryPlugin.Util.getString("MatchCriteria.invalid_escape", new Object[] {pattern, new Character(escape)})); //$NON-NLS-1$
+		                }
+		                appendCharacter(newPattern, character);
+	            	}
 	            }
 	        }
 	        
@@ -292,8 +328,9 @@
 	            throw new ExpressionEvaluationException(QueryPlugin.Util.getString("MatchCriteria.invalid_escape", new Object[] {pattern, new Character(escape)})); //$NON-NLS-1$	
 	        }
 	        
-	        return newPattern;
-	    }
+	        newPattern.append('$');
+			return newPattern.toString();
+		}
 	    
 	    private void appendCharacter(StringBuffer newPattern, char character) {
 	        if (Arrays.binarySearch(this.reserved, character) >= 0) {
@@ -304,4 +341,12 @@
 	    
 	}
 	
+	public MatchMode getMode() {
+		return mode;
+	}
+	
+	public void setMode(MatchMode mode) {
+		this.mode = mode;
+	}
+	
 }  // END CLASS

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/OrderByItem.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/OrderByItem.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/OrderByItem.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -79,7 +79,7 @@
 	 * @return true if the expression does not appear in the select clause
 	 */
 	public boolean isUnrelated() {
-		return expressionPosition != null && expressionPosition == -1;
+		return getExpressionPosition() == -1;
 	}
 
 	@Override

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/Select.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/Select.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/Select.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,17 +24,13 @@
 
 import java.util.ArrayList;
 import java.util.Collection;
-import java.util.Iterator;
 import java.util.List;
 
 import org.teiid.core.util.EquivalenceUtil;
 import org.teiid.core.util.HashCodeUtil;
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.SelectSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
@@ -48,7 +44,7 @@
 public class Select implements LanguageObject {
 
     /** The set of symbols for the data elements to be selected. */
-    private List symbols;     // List<SelectSymbols>
+    private List<SelectSymbol> symbols;
 
     /** Flag for whether duplicate removal should be performed on the results */
     private boolean distinct;
@@ -61,15 +57,15 @@
      * Constructs a default instance of this class.
      */
     public Select() {
-        symbols = new ArrayList();
+        symbols = new ArrayList<SelectSymbol>();
     }
 
     /**
      * Constructs an instance of this class from an ordered set of symbols.
      * @param symbols The ordered list of symbols
      */
-    public Select( List symbols ) {
-        this.symbols = new ArrayList( symbols );
+    public Select( List<? extends SelectSymbol> symbols ) {
+        this.symbols = new ArrayList<SelectSymbol>( symbols );
     }
 
     // =========================================================================
@@ -88,14 +84,14 @@
 	 * @return True if Select * is used
 	 */
     public boolean isStar() {
-		return (symbols.size() == 1 && symbols.get(0) instanceof AllSymbol);
+		return (symbols.size() == 1 && symbols.get(0) instanceof MultipleElementSymbol && ((MultipleElementSymbol)symbols.get(0)).getGroup() == null);
     }
 
     /**
      * Returns an ordered list of the symbols in the select.
      * @param Get list of SelectSymbol in SELECT
      */
-    public List getSymbols() {
+    public List<SelectSymbol> getSymbols() {
         return symbols;
     }
     
@@ -103,8 +99,8 @@
      * Sets an ordered list of the symbols in the select.
      * @param symbols list of SelectSymbol in SELECT
      */
-    public void setSymbols(List symbols) {
-        this.symbols = symbols;
+    public void setSymbols(List<? extends SelectSymbol> symbols) {
+        this.symbols = new ArrayList<SelectSymbol>(symbols);
     }    
 
     /**
@@ -113,7 +109,7 @@
      * @return The variable identifier at the index
      */
     public SelectSymbol getSymbol( int index ) {
-        return (SelectSymbol) symbols.get(index);
+        return symbols.get(index);
     }
 
     /**
@@ -130,9 +126,9 @@
      * Adds a new collection of symbols to the list of symbols.
      * @param symbols Collection of SelectSymbols
      */
-    public void addSymbols( Collection symbols) {
+    public void addSymbols( Collection<? extends SelectSymbol> toAdd) {
     	if(symbols != null) {
-	        this.symbols.addAll(symbols);
+	        this.symbols.addAll(toAdd);
         }
     }
     
@@ -152,38 +148,6 @@
         return symbols.contains(symbol);
     }
 
-    /**
-     * Check is the element symbol is being selected by this
-     * select clause.  This includes checking for select start
-     * and select group.star for the group of this element symbol.
-     * ElementSymbol is assumed to be fully resolved.
-     * @param elementSymbol fully resolved ElementSymbol
-     * @return whether this select will select the element symbol
-     */
-    public boolean isElementBeingSelected(ElementSymbol elementSymbol){
-        boolean isBeingSelected = this.containsSymbol(elementSymbol);
-        if (!isBeingSelected){
-            GroupSymbol g = elementSymbol.getGroupSymbol();
-            String groupDotStarName = g.getName() + ".*"; //$NON-NLS-1$
-            Iterator i = this.getSymbols().iterator();
-            while (i.hasNext()) {
-                Object selectSymbol = i.next();
-                if (selectSymbol instanceof AllSymbol){
-                    isBeingSelected = true;
-                    break;
-                } else if (selectSymbol instanceof AllInGroupSymbol){
-                    AllInGroupSymbol aigSymbol = (AllInGroupSymbol)selectSymbol;
-                    if (aigSymbol.getName().equalsIgnoreCase(groupDotStarName)){
-                        isBeingSelected = true;
-                        break;
-                    }
-                }
-            }
-        }
-        return isBeingSelected;
-    }
-    
-
 	/**
 	 * Set whether select is distinct.
 	 * @param isDistinct True if SELECT is distinct
@@ -212,9 +176,7 @@
 	 */
 	public List<SingleElementSymbol> getProjectedSymbols() { 
 		ArrayList<SingleElementSymbol> projectedSymbols = new ArrayList<SingleElementSymbol>();
-		Iterator iter = symbols.iterator();
-		while(iter.hasNext()) {
-			SelectSymbol symbol = (SelectSymbol) iter.next();
+		for (SelectSymbol symbol : symbols) {
 			if(symbol instanceof SingleElementSymbol) { 
 				projectedSymbols.add((SingleElementSymbol)symbol);
 			} else {
@@ -236,15 +198,7 @@
 	 * @return Deep clone
 	 */
 	public Object clone() {
-	    List thisSymbols = getSymbols();
-	    List copySymbols = new ArrayList(thisSymbols.size());
-	    Iterator iter = thisSymbols.iterator();
-	    while(iter.hasNext()) {
-	    	SelectSymbol ss = (SelectSymbol) iter.next();
-	    	copySymbols.add(ss.clone());    
-	    }
-	    	    
-		Select copy = new Select(copySymbols);
+		Select copy = new Select(LanguageObject.Util.deepClone(this.symbols, SelectSymbol.class));
 		copy.setDistinct( isDistinct() );
 		return copy;
 	}

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/SubqueryFromClause.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -159,16 +159,13 @@
 	 * Get deep clone of object
 	 * @return Deep copy of the object
 	 */
-	public Object clone() {
+	public FromClause cloneDirect() {
         Command commandCopy = null;        
         if(this.command != null) {
             commandCopy = (Command) this.command.clone();
         }
         
-        SubqueryFromClause clause = new SubqueryFromClause((GroupSymbol)this.symbol.clone(), commandCopy);
-        clause.setOptional(this.isOptional());
-        clause.setMakeDep(this.isMakeDep());
-        clause.setMakeNotDep(this.isMakeNotDep());
+        SubqueryFromClause clause = new SubqueryFromClause(this.symbol.clone(), commandCopy);
         clause.setTable(this.isTable());
         return clause;
 	}

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TableFunctionReference.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -83,7 +83,7 @@
 		public ProjectedColumn copyTo(ProjectedColumn copy) {
 			copy.name = this.name;
 			copy.type = this.type;
-			copy.symbol = (ElementSymbol)this.symbol.clone();
+			copy.symbol = this.symbol.clone();
 			return copy;
 		}
 		
@@ -101,14 +101,14 @@
 	}
     
 	public void copy(TableFunctionReference copy) {
-		copy.symbol = (GroupSymbol)this.symbol.clone();
+		copy.symbol = this.symbol.clone();
 		if (correlatedReferences != null) {
 			copy.correlatedReferences = correlatedReferences.clone();
 		}
 	}
 
 	@Override
-	public void collectGroups(Collection groups) {
+	public void collectGroups(Collection<GroupSymbol> groups) {
 		groups.add(getGroupSymbol());
 	}
 	

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/TextTable.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,10 +36,12 @@
 	
 	public static class TextColumn extends ProjectedColumn {
 		private Integer width;
+		private boolean noTrim;
 		
-		public TextColumn(String name, String type, Integer width) {
+		public TextColumn(String name, String type, Integer width, boolean noTrim) {
 			super(name, type);
 			this.width = width;
+			this.noTrim = noTrim;
 		}
 		
 		protected TextColumn() {
@@ -54,6 +56,14 @@
 			this.width = width;
 		}
 		
+		public boolean isNoTrim() {
+			return noTrim;
+		}
+		
+		public void setNoTrim(boolean noTrim) {
+			this.noTrim = noTrim;
+		}
+		
 		@Override
 		public boolean equals(Object obj) {
 			if (obj == this) {
@@ -63,13 +73,15 @@
 				return false;
 			}
 			TextColumn other = (TextColumn)obj;
-			return EquivalenceUtil.areEqual(width, other.width);
+			return EquivalenceUtil.areEqual(width, other.width)
+			&& noTrim == other.noTrim;
 		}
 		
 		@Override
 		public TextColumn clone() {
 			TextColumn clone = new TextColumn();
 			clone.width = this.width;
+			clone.noTrim = this.noTrim;
 			this.copyTo(clone);
 			return clone;
 		}
@@ -82,6 +94,7 @@
     private boolean escape;
     private Integer header;
     private Integer skip;
+    private boolean usingRowDelimiter = true;
     
     private boolean fixedWidth;
     
@@ -148,6 +161,14 @@
     public void setFile(Expression file) {
 		this.file = file;
 	}
+    
+    public boolean isUsingRowDelimiter() {
+		return usingRowDelimiter;
+	}
+    
+    public void setUsingRowDelimiter(boolean usingRowDelimiter) {
+		this.usingRowDelimiter = usingRowDelimiter;
+	}
 
 	@Override
 	public void acceptVisitor(LanguageVisitor visitor) {
@@ -155,7 +176,7 @@
 	}
 
 	@Override
-	public TextTable clone() {
+	protected TextTable cloneDirect() {
 		TextTable clone = new TextTable();
 		this.copy(clone);
 		clone.setDelimiter(this.delimiter);
@@ -168,6 +189,7 @@
 			clone.getColumns().add(column.clone());
 		}
 		clone.fixedWidth = this.fixedWidth;
+		clone.usingRowDelimiter = this.usingRowDelimiter;
 		return clone;
 	}
 
@@ -186,7 +208,8 @@
 			&& EquivalenceUtil.areEqual(escape, other.escape)
 			&& EquivalenceUtil.areEqual(quote, other.quote)
 			&& EquivalenceUtil.areEqual(header, other.header)
-			&& EquivalenceUtil.areEqual(skip, other.skip);
+			&& EquivalenceUtil.areEqual(skip, other.skip)
+			&& usingRowDelimiter == other.usingRowDelimiter;
 	}
 	
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/UnaryFromClause.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -74,7 +74,7 @@
      * Collect all GroupSymbols for this from clause.
      * @param groups Groups to add to
      */
-    public void collectGroups(Collection groups) {
+    public void collectGroups(Collection<GroupSymbol> groups) {
         groups.add(this.group);    
     }
 	
@@ -121,15 +121,12 @@
 	 * Get deep clone of object
 	 * @return Deep copy of the object
 	 */
-	public Object clone() {
+	public FromClause cloneDirect() {
 	    GroupSymbol copyGroup = null;
 	    if(this.group != null) { 
-	        copyGroup = (GroupSymbol) this.group.clone();
+	        copyGroup = this.group.clone();
 	    }
         UnaryFromClause clonedUnaryFromClause = new UnaryFromClause(copyGroup);
-        clonedUnaryFromClause.setOptional(this.isOptional());
-        clonedUnaryFromClause.setMakeDep(this.isMakeDep());
-        clonedUnaryFromClause.setMakeNotDep(this.isMakeNotDep());
         if (this.expandedCommand != null) {
         	clonedUnaryFromClause.setExpandedCommand((Command)this.expandedCommand.clone());
         }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/lang/XMLTable.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,6 @@
 
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.List;
 
 import net.sf.saxon.sxpath.XPathExpression;
@@ -170,7 +169,7 @@
 	}
 
 	@Override
-	public XMLTable clone() {
+	protected XMLTable cloneDirect() {
 		XMLTable clone = new XMLTable();
 		this.copy(clone);
 		for (XMLColumn column : columns) {
@@ -195,11 +194,6 @@
 	}
 
 	@Override
-	public void collectGroups(Collection groups) {
-		groups.add(getGroupSymbol());
-	}
-	
-	@Override
 	public boolean equals(Object obj) {
 		if (obj == this) {
 			return true;

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/navigator/PreOrPostOrderNavigator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -72,9 +72,8 @@
 import org.teiid.query.sql.lang.XMLTable;
 import org.teiid.query.sql.proc.AssignmentStatement;
 import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.BreakStatement;
+import org.teiid.query.sql.proc.BranchingStatement;
 import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.ContinueStatement;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.proc.CriteriaSelector;
 import org.teiid.query.sql.proc.DeclareStatement;
@@ -87,8 +86,6 @@
 import org.teiid.query.sql.proc.WhileStatement;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.CaseExpression;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.DerivedColumn;
@@ -97,11 +94,14 @@
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.QueryString;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.WindowFunction;
+import org.teiid.query.sql.symbol.WindowSpecification;
 import org.teiid.query.sql.symbol.XMLAttributes;
 import org.teiid.query.sql.symbol.XMLElement;
 import org.teiid.query.sql.symbol.XMLForest;
@@ -140,12 +140,12 @@
             visitVisitor(obj);
         }
     }
-
     
     public void visit(AggregateSymbol obj) {
         preVisitVisitor(obj);
         visitNode(obj.getExpression());
         visitNode(obj.getOrderBy());
+        visitNode(obj.getCondition());
         postVisitVisitor(obj);
     }
     public void visit(AliasSymbol obj) {
@@ -153,14 +153,10 @@
         visitNode(obj.getSymbol());
         postVisitVisitor(obj);
     }
-    public void visit(AllInGroupSymbol obj) {
+    public void visit(MultipleElementSymbol obj) {
         preVisitVisitor(obj);
         postVisitVisitor(obj);
     }
-    public void visit(AllSymbol obj) {
-        preVisitVisitor(obj);
-        postVisitVisitor(obj);
-    }
     public void visit(AssignmentStatement obj) {
         preVisitVisitor(obj);
         visitNode(obj.getVariable());
@@ -184,7 +180,7 @@
         visitNodes(obj.getStatements());
         postVisitVisitor(obj);
     }
-    public void visit(BreakStatement obj) {
+    public void visit(BranchingStatement obj) {
         preVisitVisitor(obj);
         postVisitVisitor(obj);
     }
@@ -220,10 +216,6 @@
         preVisitVisitor(obj);
         postVisitVisitor(obj);
     }
-    public void visit(ContinueStatement obj) {
-        preVisitVisitor(obj);
-        postVisitVisitor(obj);
-    }
     public void visit(CreateUpdateProcedureCommand obj) {
         preVisitVisitor(obj);
         visitNode(obj.getBlock());
@@ -700,6 +692,22 @@
         postVisitVisitor(obj);
     }
     
+    @Override
+    public void visit(WindowFunction obj) {
+    	preVisitVisitor(obj);
+        visitNode(obj.getFunction());
+        visitNode(obj.getWindowSpecification());
+        postVisitVisitor(obj);
+    }
+    
+    @Override
+    public void visit(WindowSpecification obj) {
+    	preVisitVisitor(obj);
+    	visitNodes(obj.getPartition());
+        visitNode(obj.getOrderBy());
+        postVisitVisitor(obj);
+    }
+    
     public static void doVisit(LanguageObject object, LanguageVisitor visitor, boolean order) {
     	doVisit(object, visitor, order, false);
     }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Block.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Block.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Block.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,10 +26,11 @@
 import java.util.List;
 
 import org.teiid.core.util.EquivalenceUtil;
-import org.teiid.query.sql.LanguageObject;
+import org.teiid.core.util.StringUtil;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.ProcedureReservedWords;
 import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.proc.Statement.Labeled;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.visitor.SQLStringVisitor;
 
@@ -38,10 +39,12 @@
  * <p> This class represents a group of <code>Statement</code> objects. The
  * statements are stored on this object in the order in which they are added.</p>
  */
-public class Block implements LanguageObject {
+public class Block extends Statement implements Labeled {
 
 	// list of statements on this block
 	private List<Statement> statements;
+	private boolean atomic;
+	private String label;
 
 	/**
 	 * Constructor for Block.
@@ -58,6 +61,14 @@
 		this();
 		statements.add(statement);
 	}
+	
+	public String getLabel() {
+		return label;
+	}
+	
+	public void setLabel(String label) {
+		this.label = label;
+	}
 
 	/**
 	 * Get all the statements contained on this block.
@@ -112,9 +123,11 @@
 	 */
 	public Block clone() {		
 		Block copy = new Block();
+		copy.setAtomic(atomic);
 		for (Statement statement : statements) {
 			copy.addStatement((Statement)statement.clone());
 		}
+		copy.setLabel(label);
 		return copy;
 	}
 	
@@ -134,9 +147,13 @@
     	if(!(obj instanceof Block)) {
     		return false;
 		}
-
+    	
+    	Block other = (Block)obj;
+    	
 		// Compare the statements on the block
-        return EquivalenceUtil.areEqual(getStatements(), ((Block)obj).getStatements());
+        return this.atomic == other.atomic 
+        && StringUtil.equalsIgnoreCase(label, other.label)
+        && EquivalenceUtil.areEqual(getStatements(), other.getStatements());
     }    
 
     /**
@@ -157,5 +174,18 @@
     public String toString() {
     	return SQLStringVisitor.getSQLString(this);
     }
+    
+    public boolean isAtomic() {
+		return atomic;
+	}
+    
+    public void setAtomic(boolean atomic) {
+		this.atomic = atomic;
+	}
+    
+    @Override
+    public int getType() {
+    	return Statement.TYPE_COMPOUND;
+    }
 
 }// END CLASS

Copied: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BranchingStatement.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/sql/proc/BranchingStatement.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BranchingStatement.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BranchingStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,136 @@
+/*
+ * 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 org.teiid.query.sql.proc;
+
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.core.util.StringUtil;
+import org.teiid.query.sql.LanguageVisitor;
+
+/**
+ * <p> This class represents a break statement in the storedprocedure language.
+ * It extends the <code>Statement</code> that could part of a block.</p>
+ */
+public class BranchingStatement extends Statement {
+	
+	public enum BranchingMode {
+		/**
+		 * Teiid specific - only allowed to target loops
+		 */
+		BREAK,
+		/**
+		 * Teiid specific - only allowed to target loops
+		 */
+		CONTINUE,
+		/**
+		 * ANSI - allowed to leave any block 
+		 */
+		LEAVE
+	}
+	
+	private String label;
+	private BranchingMode mode;
+	
+	public BranchingStatement() {
+		this(BranchingMode.BREAK);
+	}
+	
+	public BranchingStatement(BranchingMode mode) {
+		this.mode = mode;
+	}
+	
+	public String getLabel() {
+		return label;
+	}
+	
+	public void setLabel(String label) {
+		this.label = label;
+	}
+	
+	public void setMode(BranchingMode mode) {
+		this.mode = mode;
+	}
+	
+	public BranchingMode getMode() {
+		return mode;
+	}
+	
+    /**
+     * Return the type for this statement, this is one of the types
+     * defined on the statement object.
+     */
+    public int getType() {
+    	switch (mode) {
+    	case BREAK:
+    		return Statement.TYPE_BREAK;
+    	case CONTINUE:
+    		return Statement.TYPE_CONTINUE;
+    	case LEAVE:
+    		return Statement.TYPE_LEAVE;
+    	}
+    	throw new AssertionError();
+    }       
+
+    // =========================================================================
+    //                  P R O C E S S I N G     M E T H O D S
+    // =========================================================================
+    
+    public void acceptVisitor(LanguageVisitor visitor) {
+        visitor.visit(this);
+    }
+    
+    /**
+     * Deep clone statement to produce a new identical statement.
+     * @return Deep clone 
+     */
+    public BranchingStatement clone() {     
+        BranchingStatement clone = new BranchingStatement();
+        clone.mode = mode;
+        clone.label = label;
+        return clone;
+    }
+    
+    /**
+     * Compare two BreakStatements for equality.
+     * @param obj Other object
+     * @return True if equal
+     */
+    public boolean equals(Object obj) {
+        // Quick same object test
+        if(this == obj) {
+            return true;
+        }
+        if (!(obj instanceof BranchingStatement)) {
+        	return false;
+        }
+        BranchingStatement other = (BranchingStatement)obj;
+        return StringUtil.equalsIgnoreCase(label, other.label) 
+        && mode == other.mode;
+    } 
+    
+    public int hashCode() {
+        return HashCodeUtil.hashCode(mode.hashCode());
+    }
+      
+}

Deleted: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BreakStatement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BreakStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/BreakStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -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 org.teiid.query.sql.proc;
-
-import org.teiid.query.sql.LanguageVisitor;
-
-/**
- * <p> This class represents a break statement in the storedprocedure language.
- * It extends the <code>Statement</code> that could part of a block.</p>
- */
-public class BreakStatement extends Statement {
-    
-    /**
-     * Return the type for this statement, this is one of the types
-     * defined on the statement object.
-     */
-    public int getType() {
-        return Statement.TYPE_BREAK;
-    }       
-
-    // =========================================================================
-    //                  P R O C E S S I N G     M E T H O D S
-    // =========================================================================
-    
-    public void acceptVisitor(LanguageVisitor visitor) {
-        visitor.visit(this);
-    }
-    
-    /**
-     * Deep clone statement to produce a new identical statement.
-     * @return Deep clone 
-     */
-    public Object clone() {     
-        return new BreakStatement();
-    }
-    
-    /**
-     * Compare two BreakStatements for equality.
-     * @param obj Other object
-     * @return True if equal
-     */
-    public boolean equals(Object obj) {
-        // Quick same object test
-        if(this == obj) {
-            return true;
-        }
-
-        return obj instanceof BreakStatement;
-    } 
-    
-    public int hashCode() {
-        //the break statement are always equal
-        return 0;
-    }
-      
-}

Deleted: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/ContinueStatement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/ContinueStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/ContinueStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,84 +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 org.teiid.query.sql.proc;
-
-import org.teiid.query.sql.LanguageVisitor;
-import org.teiid.query.sql.visitor.SQLStringVisitor;
-
-/**
- * <p> This class represents a continue statement in the storedprocedure language.
- * It extends the <code>Statement</code> that could part of a block.</p>
- */
-public class ContinueStatement extends Statement {
-    
-    /**
-     * Return the type for this statement, this is one of the types
-     * defined on the statement object.
-     */
-    public int getType() {
-        return Statement.TYPE_CONTINUE;
-    }       
-
-    // =========================================================================
-    //                  P R O C E S S I N G     M E T H O D S
-    // =========================================================================
-    
-    public void acceptVisitor(LanguageVisitor visitor) {
-        visitor.visit(this);
-    }
-    
-    /**
-     * Deep clone statement to produce a new identical statement.
-     * @return Deep clone 
-     */
-    public Object clone() {     
-        return new ContinueStatement();
-    }
-    
-    /**
-     * Compare two ContinueStatements for equality.
-     * @param obj Other object
-     * @return True if equal
-     */
-    public boolean equals(Object obj) {
-        // Quick same object test
-        if(this == obj) {
-            return true;
-        }
-
-        // Quick fail tests     
-        if(!(obj instanceof ContinueStatement)) {
-            return false;
-        }
-
-        return true;
-    } 
-      
-    public int hashCode() {
-        //the continue statements are always equal
-        return 0;
-    }
-      
-}

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/IfStatement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/IfStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/IfStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -151,11 +151,11 @@
 	 * @return Deep clone 
 	 */
 	public Object clone() {
-		Block otherIf = (Block)this.ifBlock.clone();
+		Block otherIf = this.ifBlock.clone();
 		Criteria otherCrit = (Criteria) this.condition.clone();		
 		Block otherElse = null;
 		if(this.hasElseBlock()) {
-			otherElse = (Block) this.elseBlock.clone();	
+			otherElse = this.elseBlock.clone();	
 		}
 
 		return new IfStatement(otherCrit, otherIf, otherElse);

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/LoopStatement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/LoopStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/LoopStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,10 +26,12 @@
 
 import org.teiid.core.util.EquivalenceUtil;
 import org.teiid.core.util.HashCodeUtil;
+import org.teiid.core.util.StringUtil;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.SubqueryContainer;
+import org.teiid.query.sql.proc.Statement.Labeled;
 
 
 /**
@@ -39,10 +41,11 @@
  * a block, a select statement and a cursor. 
  * determines which block should be executed..</p>
  */
-public class LoopStatement extends Statement implements SubqueryContainer {
+public class LoopStatement extends Statement implements SubqueryContainer, Labeled {
     private String cursorName;
     private Block loopBlock;
     private Command query;
+    private String label;
     
     public LoopStatement(Block block, Command query, String cursorName){
         this.loopBlock = block;
@@ -50,6 +53,14 @@
         this.cursorName = cursorName;
     }    
     
+    public String getLabel() {
+		return label;
+	}
+    
+    public void setLabel(String label) {
+		this.label = label;
+	}
+    
     /**
      * @return
      */
@@ -121,10 +132,12 @@
      * @return Deep clone 
      */
     public Object clone() {
-        Block otherBlock = (Block)this.loopBlock.clone();    
+        Block otherBlock = this.loopBlock.clone();    
         Query otherQuery = (Query)this.query.clone();
 
-        return new LoopStatement(otherBlock, otherQuery, this.cursorName);
+        LoopStatement ls = new LoopStatement(otherBlock, otherQuery, this.cursorName);
+        ls.setLabel(label);
+        return ls;
     }
     
     /**
@@ -152,7 +165,8 @@
             // Compare the if block
             EquivalenceUtil.areEqual(loopBlock, other.loopBlock) &&
             // Compare the else block
-            EquivalenceUtil.areEqual(cursorName, other.cursorName);
+            EquivalenceUtil.areEqual(cursorName, other.cursorName)
+            && StringUtil.equalsIgnoreCase(this.label, other.label);
     } 
 
     /**

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Statement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Statement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/Statement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,7 +22,7 @@
 
 package org.teiid.query.sql.proc;
 
-import org.teiid.query.sql.*;
+import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.visitor.SQLStringVisitor;
 
 /**
@@ -31,6 +31,11 @@
  * <code>IfStatement</code>, <code>AssignmentStatement</code> etc.</p>
  */
 public abstract class Statement implements LanguageObject {
+	
+	public interface Labeled {
+		String getLabel();
+		void setLabel(String label);
+	}
 
 	/** 
 	 * Represents an unknown type of statement 
@@ -84,6 +89,10 @@
     
     public static final int TYPE_UPDATE = 10;
     
+    public static final int TYPE_COMPOUND = 11;
+    
+    public static final int TYPE_LEAVE = 12;
+    
 	/**
 	 * Return type of statement to make it easier to build switch statements by statement type.
 	 * @return Type from TYPE constants

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/TriggerAction.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/TriggerAction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/TriggerAction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,7 +36,7 @@
 	private Block block;
 	
 	public TriggerAction(Block b) {
-		this.block = b;
+		this.setBlock(b);
 	}
 	
 	public Block getBlock() {
@@ -44,6 +44,7 @@
 	}
 	
 	public void setBlock(Block block) {
+		block.setAtomic(true);
 		this.block = block;
 	}
 	

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/proc/WhileStatement.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/proc/WhileStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/proc/WhileStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,8 +26,10 @@
 
 import org.teiid.core.util.EquivalenceUtil;
 import org.teiid.core.util.HashCodeUtil;
+import org.teiid.core.util.StringUtil;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.lang.Criteria;
+import org.teiid.query.sql.proc.Statement.Labeled;
 
 
 /**
@@ -36,16 +38,16 @@
  * a block and a criteria that
  * determines when to exit the while loop.</p>
  */
-public class WhileStatement extends Statement {
+public class WhileStatement extends Statement implements Labeled {
 
     private Block whileBlock;
-    
+    private String label;
     // criteria on the if block
     private Criteria condition;
 
     /**
      * Constructor for IfStatement.
-     * @param criteria The criteria determining which bleck should be executed
+     * @param criteria The criteria determining which block should be executed
      * @param ifBlock The IF <code>Block</code> object.
      * @param ifBlock The ELSE <code>Block</code> object.
      */
@@ -53,6 +55,14 @@
         this.whileBlock = block;
         this.condition = criteria;
     }
+    
+    public void setLabel(String label) {
+		this.label = label;
+	}
+    
+    public String getLabel() {
+		return label;
+	}
 
     /**
      * Get the condition that determines which block needs to be executed.
@@ -106,10 +116,12 @@
      * @return Deep clone 
      */
     public Object clone() {
-        Block otherBlock = (Block)this.whileBlock.clone();
+        Block otherBlock = this.whileBlock.clone();
         Criteria otherCrit = (Criteria) this.condition.clone();     
 
-        return new WhileStatement(otherCrit, otherBlock);
+        WhileStatement ws = new WhileStatement(otherCrit, otherBlock);
+        ws.setLabel(label);
+        return ws;
     }
     
     /**
@@ -135,7 +147,8 @@
             // Compare the condition
             EquivalenceUtil.areEqual(getCondition(), other.getCondition()) &&
             // Compare the if block
-            EquivalenceUtil.areEqual(whileBlock, other.whileBlock);
+            EquivalenceUtil.areEqual(whileBlock, other.whileBlock)
+            && StringUtil.equalsIgnoreCase(this.label, other.label);
     } 
 
     /**

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AggregateSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,14 +34,7 @@
 
 
 /**
- * <p>An aggregate symbol represents an aggregate function in the SELECT or HAVING clauses.  It
- * extends ExpressionSymbol as they have many things in common.  The aggregate symbol is
- * typically something like <code>SUM(stock.quantity * 2)</code>.  There are five supported
- * aggregate functions: COUNT, SUM, AVG, MIN, and MAX.  Aggregate functions contain an expression -
- * this data is managed by the super class, ExpressionSymbol.  Aggregate functions may also
- * specify a DISTINCT flag to indicate that duplicates should be ignored.  The DISTINCT flag
- * may be set for all five aggregate functions but is ignored for the computation of MIN and MAX.
- * One special use of an aggregate symbol is for the symbol <code>COUNT(*)</code>.  The * expression
+ * <p>An aggregate symbol represents an aggregate function. The * expression
  * is encoded by setting the expression to null.  This may ONLY be used with the COUNT function.</p>
  *
  * <p>The type of an aggregate symbol depends on the function and the type of the underlying
@@ -69,12 +62,17 @@
 		STDDEV_POP,
 		STDDEV_SAMP,
 		VAR_POP,
-		VAR_SAMP;
+		VAR_SAMP,
+		RANK,
+		DENSE_RANK,
+		ROW_NUMBER;
 	}
 
 	private Type aggregate;
 	private boolean distinct;
 	private OrderBy orderBy;
+	private Expression condition;
+	private boolean isWindowed;
 
 	private static final Class<Integer> COUNT_TYPE = DataTypeManager.DefaultDataClasses.INTEGER;
 	private static final Map<Class<?>, Class<?>> SUM_TYPES;
@@ -165,24 +163,41 @@
 	 * @return Type of the symbol
 	 */
 	public Class<?> getType() {
-		if(this.aggregate == Type.COUNT) {
+		switch (this.aggregate) {
+		case COUNT:
 			return COUNT_TYPE;
-		} else if(this.aggregate == Type.SUM ) {
+		case SUM:
 			Class<?> expressionType = this.getExpression().getType();
 			return SUM_TYPES.get(expressionType);
-        } else if (this.aggregate == Type.AVG) {
-            Class<?> expressionType = this.getExpression().getType();
+		case AVG:
+            expressionType = this.getExpression().getType();
             return AVG_TYPES.get(expressionType);
-		} else if (isBoolean()) {
+		case ARRAY_AGG:
+			return DataTypeManager.DefaultDataClasses.OBJECT;
+		case TEXTAGG:
+			return DataTypeManager.DefaultDataClasses.BLOB;
+		}
+		if (isBoolean()) {
 			return DataTypeManager.DefaultDataClasses.BOOLEAN;
-		} else if (isEnhancedNumeric()) {
+		}
+		if (isEnhancedNumeric()) {
 			return DataTypeManager.DefaultDataClasses.DOUBLE;
-		} else if (this.aggregate == Type.ARRAY_AGG) {
-			return DataTypeManager.DefaultDataClasses.OBJECT;
-		} else {
-			return this.getExpression().getType();
 		}
+		if (isAnalytical()) {
+			return DataTypeManager.DefaultDataClasses.INTEGER;
+		}
+		return this.getExpression().getType();
 	}
+	
+	public boolean isAnalytical() {
+		switch (this.aggregate) {
+		case RANK:
+		case ROW_NUMBER:
+		case DENSE_RANK:
+			return true;
+		}
+		return false;
+	}
 
 	public boolean isBoolean() {
 		return this.aggregate == Type.EVERY 
@@ -222,6 +237,10 @@
 		if (orderBy != null) {
 			copy.setOrderBy(orderBy.clone());
 		}
+		if (condition != null) {
+			copy.setCondition((Expression) condition.clone());
+		}
+		copy.isWindowed = this.isWindowed;
 		return copy;
 	}
     
@@ -245,7 +264,9 @@
         
         return this.aggregate.equals(other.aggregate)
                && this.distinct == other.distinct
+               && this.isWindowed == other.isWindowed
                && EquivalenceUtil.areEqual(this.getExpression(), other.getExpression())
+               && EquivalenceUtil.areEqual(this.condition, other.condition)
         	   && EquivalenceUtil.areEqual(this.getOrderBy(), other.getOrderBy());
     }
     
@@ -254,17 +275,23 @@
     		return false;
     	}
     	switch (getAggregateFunction()) {
-		case COUNT:
-		case AVG:
-		case STDDEV_POP:
-		case STDDEV_SAMP:
-		case VAR_POP:
-		case VAR_SAMP:
-		case SUM:
-			return true;
+		case MAX:
+		case MIN:
+		case ANY:
+		case SOME:
+		case EVERY:
+			return false;
 		}
-		return false;
+		return true;
     }
+    
+    public Expression getCondition() {
+		return condition;
+	}
+    
+    public void setCondition(Expression condition) {
+		this.condition = condition;
+	}
 
 	public static boolean areAggregatesCardinalityDependent(Collection<AggregateSymbol> aggs) {
 		for (AggregateSymbol aggregateSymbol : aggs) {
@@ -274,5 +301,33 @@
 		}
 		return false;
 	}
+	
+	public boolean respectsNulls() {
+		switch (this.aggregate) {
+		case TEXTAGG:
+		case ARRAY_AGG:
+			return true;
+		}
+		return false;
+	}
+	
+	public boolean canStage() {
+		switch (this.aggregate) {
+		case TEXTAGG:
+		case ARRAY_AGG:
+			return false;
+		case XMLAGG:
+			return orderBy == null;
+		}
+		return true;
+	}
+	
+	public boolean isWindowed() {
+		return isWindowed;
+	}
+	
+	public void setWindowed(boolean isWindowed) {
+		this.isWindowed = isWindowed;
+	}
 
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AliasSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AliasSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AliasSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -82,7 +82,7 @@
 	 * Get the type of the symbol
 	 * @return Type of the symbol
 	 */
-	public Class getType() {
+	public Class<?> getType() {
 		return this.symbol.getType();
 	}
 

Deleted: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllInGroupSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllInGroupSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllInGroupSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,72 +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 org.teiid.query.sql.symbol;
-
-import java.util.List;
-
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-
-/**
- * <p>This is a subclass of Symbol representing <group>.*, which contains all of
- * the elements from a single group in the query.  The name of this symbol is "group.*",
- * when resolved it contains a single Group Symbols and a set of Element Symbols</p>
- */
-public class AllInGroupSymbol extends MultipleElementSymbol {
-
-    /**
-     * Constructor used for cloning 
-     * @param name
-     * @param canonicalName
-     * @since 4.3
-     */
-    protected AllInGroupSymbol(String name, String canonicalName) {
-        super(name, canonicalName);
-    }
-    
-    /**
-     * Default constructor
-     */
-    public AllInGroupSymbol(String name) {
-        super(name);
-    }
-    
-    public void acceptVisitor(LanguageVisitor visitor) {
-        visitor.visit(this);
-    }
-
-	/**
-	 * Return a deep copy of this object
-	 * @return Deep copy of this object
-	 */
-	public Object clone() {
-		AllInGroupSymbol copy = new AllInGroupSymbol(getName(), getCanonical());
-		
-		List<ElementSymbol> elements = getElementSymbols();
-		if(elements != null && elements.size() > 0) {
-			copy.setElementSymbols(LanguageObject.Util.deepClone(elements, ElementSymbol.class));				
-		}	
-
-		return copy;
-	}
-}

Deleted: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/AllSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,75 +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 org.teiid.query.sql.symbol;
-
-import java.util.List;
-
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.LanguageVisitor;
-
-/**
- * <p>This is a subclass of Symbol representing *, which contains all of
- * the elements from all groups in the query.  The name of this symbol is always "*",
- * when resolved it contains a set of Element Symbols referred to by the AllSymbol</p>
- */
-public class AllSymbol extends MultipleElementSymbol {
-
-    private static final String ALL_SYMBOL_NAME = "*"; //$NON-NLS-1$
-
-    /**
-     * Constructor used for cloning 
-     * @param name
-     * @param canonicalName
-     * @since 4.3
-     */
-    protected AllSymbol(String name, String canonicalName) {
-        super(name, canonicalName);
-    }
-    
-    /**
-     * Default constructor
-     */
-    public AllSymbol(){
-        this(ALL_SYMBOL_NAME, ALL_SYMBOL_NAME);
-    }
-
-    public void acceptVisitor(LanguageVisitor visitor) {
-        visitor.visit(this);
-    }
-
-	/**
-	 * Return a deep copy of this object
-	 * @return Deep copy of this object
-	 */
-	public Object clone() {
-		AllSymbol copy = new AllSymbol(ALL_SYMBOL_NAME, ALL_SYMBOL_NAME);
-
-		List<ElementSymbol> elements = getElementSymbols();
-		if(elements != null && elements.size() > 0) {
-			copy.setElementSymbols(LanguageObject.Util.deepClone(elements, ElementSymbol.class));				
-		}	
-
-		return copy;
-	}
-	
-}

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/DerivedColumn.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/DerivedColumn.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/DerivedColumn.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,7 +24,6 @@
 
 import org.teiid.core.util.EquivalenceUtil;
 import org.teiid.core.util.HashCodeUtil;
-import org.teiid.query.function.source.XMLSystemFunctions;
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.visitor.SQLStringVisitor;

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ElementSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ElementSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ElementSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -46,7 +46,8 @@
     private GroupSymbol groupSymbol;
     private Object metadataID;
 	private Class<?> type;
-    private boolean isExternalReference = false;
+    private boolean isExternalReference;
+    private boolean isAggregate;
         
     private DisplayMode displayMode = DisplayMode.OUTPUT_NAME;
 	
@@ -262,7 +263,16 @@
 		copy.setIsExternalReference(isExternalReference());
 		copy.outputName = this.outputName;
 		copy.setDisplayMode(this.getDisplayMode());
+		copy.isAggregate = isAggregate;
 		return copy;
 	}
 	
+	public boolean isAggregate() {
+		return isAggregate;
+	}
+	
+	public void setAggregate(boolean isAggregate) {
+		this.isAggregate = isAggregate;
+	}
+	
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ExpressionSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ExpressionSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/ExpressionSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,7 +34,6 @@
  */
 public class ExpressionSymbol extends SingleElementSymbol {
 	private Expression expression;
-	private boolean derivedExpression;
 
     /**
      * Constructor used for cloning 
@@ -101,19 +100,9 @@
 			clonedExpr = (Expression) getExpression().clone();		
 	    }
 	    ExpressionSymbol copy = new ExpressionSymbol(getName(), getCanonical(), clonedExpr);
-	    copy.setDerivedExpression(this.derivedExpression);
 	    return copy;
 	}
 
-    public boolean isDerivedExpression() {
-        return this.derivedExpression;
-    }
-
-    public void setDerivedExpression(boolean derivedExpression) {
-        this.derivedExpression = derivedExpression;
-    }
-    
-    
     /** 
      * @see org.teiid.query.sql.symbol.Symbol#hashCode()
      */

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/MultipleElementSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/MultipleElementSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/MultipleElementSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,22 +22,23 @@
 
 package org.teiid.query.sql.symbol;
 
-import java.util.*;
+import java.util.LinkedList;
+import java.util.List;
 
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.visitor.SQLStringVisitor;
+
 /**
  * <p>This is a subclass of Symbol representing multiple output columns.</p>
  */
-public abstract class MultipleElementSymbol extends SelectSymbol {
+public class MultipleElementSymbol implements SelectSymbol {
     private List<ElementSymbol> elementSymbols;
+    private GroupSymbol group;
 
-    /**
-     * Passthrough constructor used for cloning 
-     * @param name
-     * @param canonicalName
-     * @since 4.3
-     */
-    protected MultipleElementSymbol(String name, String canonicalName) {
-        super(name, canonicalName);
+    public MultipleElementSymbol() {
     }
     
     /**
@@ -45,7 +46,7 @@
      * @param name Name of the symbol
      */
     public MultipleElementSymbol(String name){
-        super(name);
+        this.group = new GroupSymbol(name);
     }
 
     /**
@@ -83,5 +84,60 @@
     public boolean isResolved() {
         return(elementSymbols != null);
     }
+    
+    public void acceptVisitor(LanguageVisitor visitor) {
+        visitor.visit(this);
+    }
 
+	/**
+	 * Return a deep copy of this object
+	 * @return Deep copy of this object
+	 */
+	public Object clone() {
+		MultipleElementSymbol copy = new MultipleElementSymbol();
+		if (group != null) {
+			copy.group = group.clone();
+		}
+
+		List<ElementSymbol> elements = getElementSymbols();
+		if(elements != null && elements.size() > 0) {
+			copy.setElementSymbols(LanguageObject.Util.deepClone(elements, ElementSymbol.class));				
+		}	
+
+		return copy;
+	}
+	
+	/**
+	 * @return null if selecting all groups, otherwise the specific group
+	 */
+	public GroupSymbol getGroup() {
+		return group;
+	}
+	
+	public void setGroup(GroupSymbol group) {
+		this.group = group;
+	}
+	
+	@Override
+	public String toString() {
+		return SQLStringVisitor.getSQLString(this);
+	}
+	
+	@Override
+	public int hashCode() {
+		return HashCodeUtil.hashCode(0, group);
+	}
+	
+	@Override
+	public boolean equals(Object obj) {
+		if (obj == this) {
+			return true;
+		}
+		if (!(obj instanceof MultipleElementSymbol)) {
+			return false;
+		}
+		MultipleElementSymbol other = (MultipleElementSymbol)obj;
+		return EquivalenceUtil.areEqual(this.group, other.group);
+	}
+
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/QueryString.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/QueryString.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/QueryString.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,7 +30,7 @@
 import org.teiid.query.sql.visitor.SQLStringVisitor;
 
 /**
- * Represents XMLATTRIBUTES name value pairs
+ * Represents query string name value pairs
  */
 public class QueryString implements Expression {
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/Reference.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/Reference.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/Reference.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -191,12 +191,4 @@
         return this.positional;
     }
     
-    /**
-     * Should never be called - used for an xml hack
-     * @param expression
-     */
-    public void setExpression(ElementSymbol expression) {
-		this.expression = expression;
-	}
-
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SelectSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SelectSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SelectSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,29 +22,14 @@
 
 package org.teiid.query.sql.symbol;
 
+import org.teiid.query.sql.LanguageObject;
+
 /** 
  * This is the server's representation of a metadata symbol that can be used
  * in a SELECT statement.  It exists as a typing mechanism and to provide a single
  * additional method to get an ordered list of elements from each symbol.
  */
-public abstract class SelectSymbol extends Symbol {
+public interface SelectSymbol extends LanguageObject {
+	
 
-    /**
-     * Passthrough constructor used for cloning 
-     * @param name
-     * @param canonicalName
-     * @since 4.3
-     */
-    protected SelectSymbol(String name, String canonicalName) {
-        super(name, canonicalName);
-    }
-    
-	/**
-	 * Construct a symbol with a name
-	 * @param name Name of symbol
-	 */
-	public SelectSymbol(String name) {
-		super(name);
-	}
-				
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SingleElementSymbol.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SingleElementSymbol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/SingleElementSymbol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,7 +27,7 @@
 /**
  * <p>This is a subclass of Symbol representing a single output column.</p>
  */
-public abstract class SingleElementSymbol extends SelectSymbol implements Expression {
+public abstract class SingleElementSymbol extends Symbol implements Expression, SelectSymbol {
 
 	/**
      * Character used to delimit name components in a symbol

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/TextLine.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/TextLine.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/TextLine.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -88,7 +88,7 @@
 	
 	@Override
 	public Class<?> getType() {
-		return DataTypeManager.DefaultDataClasses.BLOB;
+		return DataTypeManager.DefaultDataClasses.STRING;
 	}
 
 	@Override

Copied: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowFunction.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/sql/symbol/WindowFunction.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowFunction.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,106 @@
+/*
+ * 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 org.teiid.query.sql.symbol;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.visitor.SQLStringVisitor;
+
+public class WindowFunction extends SingleElementSymbol {
+	
+	private AggregateSymbol function;
+	private WindowSpecification windowSpecification;
+	
+	public WindowFunction(String name) {
+		super(name);
+	}
+	
+	protected WindowFunction(String name, String canonical) {
+		super(name, canonical);
+	}
+	
+	public AggregateSymbol getFunction() {
+		return function;
+	}
+	
+	public void setFunction(AggregateSymbol expression) {
+		this.function = expression;
+		this.function.setWindowed(true);
+	}
+	
+	public WindowSpecification getWindowSpecification() {
+		return windowSpecification;
+	}
+	
+	public void setWindowSpecification(WindowSpecification windowSpecification) {
+		this.windowSpecification = windowSpecification;
+	}
+	
+	@Override
+	public Class<?> getType() {
+		return function.getType();
+	}
+
+	@Override
+	public boolean isResolved() {
+		return function.isResolved();
+	}
+
+	@Override
+	public void acceptVisitor(LanguageVisitor visitor) {
+		visitor.visit(this);
+	}
+	
+	@Override
+	public int hashCode() {
+		return HashCodeUtil.hashCode(function.hashCode(), windowSpecification);
+	}
+	
+	@Override
+	public boolean equals(Object obj) {
+		if (obj == this) {
+			return true;
+		}
+		if (!(obj instanceof WindowFunction)) {
+			return false;
+		}
+		WindowFunction other = (WindowFunction)obj;
+		return EquivalenceUtil.areEqual(this.function, other.function) &&
+		EquivalenceUtil.areEqual(this.windowSpecification, other.windowSpecification);
+	}
+	
+	@Override
+	public WindowFunction clone() {
+		WindowFunction clone = new WindowFunction(this.getName(), this.getCanonical());
+		clone.setFunction((AggregateSymbol) this.function.clone());
+		clone.setWindowSpecification(this.windowSpecification.clone());
+		return clone;
+	}
+	
+	@Override
+	public String toString() {
+		return SQLStringVisitor.getSQLString(this);
+	}
+	
+}

Copied: branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowSpecification.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/sql/symbol/WindowSpecification.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowSpecification.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/symbol/WindowSpecification.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,99 @@
+/*
+ * 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 org.teiid.query.sql.symbol;
+
+import java.util.List;
+
+import org.teiid.core.util.EquivalenceUtil;
+import org.teiid.core.util.HashCodeUtil;
+import org.teiid.query.sql.LanguageObject;
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.OrderBy;
+import org.teiid.query.sql.visitor.SQLStringVisitor;
+
+public class WindowSpecification implements LanguageObject {
+	
+	private List<Expression> partition;
+	private OrderBy orderBy;
+	
+	public WindowSpecification() {
+		
+	}
+	
+	public List<Expression> getPartition() {
+		return partition;
+	}
+	
+	public void setPartition(List<Expression> grouping) {
+		this.partition = grouping;
+	}
+	
+	public OrderBy getOrderBy() {
+		return orderBy;
+	}
+	
+	public void setOrderBy(OrderBy orderBy) {
+		this.orderBy = orderBy;
+	}
+
+	@Override
+	public void acceptVisitor(LanguageVisitor visitor) {
+		visitor.visit(this);
+	}
+	
+	@Override
+	public int hashCode() {
+		return HashCodeUtil.hashCode(0, partition, orderBy);
+	}
+	
+	@Override
+	public boolean equals(Object obj) {
+		if (obj == this) {
+			return true;
+		}
+		if (!(obj instanceof WindowSpecification)) {
+			return false;
+		}
+		WindowSpecification other = (WindowSpecification)obj;
+		return EquivalenceUtil.areEqual(this.partition, other.partition) &&
+		EquivalenceUtil.areEqual(this.orderBy, other.orderBy);
+	}
+	
+	@Override
+	public WindowSpecification clone() {
+		WindowSpecification clone = new WindowSpecification();
+		if (this.partition != null) {
+			clone.setPartition(LanguageObject.Util.deepClone(this.partition, Expression.class));
+		}
+		if (this.orderBy != null) {
+			clone.setOrderBy(this.orderBy.clone());
+		}
+		return clone;
+	}
+	
+	@Override
+	public String toString() {
+		return SQLStringVisitor.getSQLString(this);
+	}
+	
+}

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/util/ValueIteratorSource.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -50,5 +50,9 @@
     ValueIterator getValueIterator(Expression valueExpression) throws TeiidComponentException;
     
     Set<Object> getCachedSet(Expression valueExpression) throws TeiidComponentException, TeiidProcessingException;
-    
+
+	void setUnused(boolean unused);
+
+	boolean isUnused();
+
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AbstractSymbolMappingVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AbstractSymbolMappingVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AbstractSymbolMappingVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,11 +33,10 @@
 import org.teiid.query.sql.lang.UnaryFromClause;
 import org.teiid.query.sql.lang.Update;
 import org.teiid.query.sql.proc.CriteriaSelector;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Symbol;
 
 
@@ -124,70 +123,28 @@
 	 * Swap each ElementSymbol referenced by AllInGroupSymbol
 	 * @param obj Object to remap
 	 */
-    public void visit(AllInGroupSymbol obj) {   
-        // Discover new group name during course of mapping
-        String newGroupName = null;
-                     
-		List oldSymbols = obj.getElementSymbols();
+    public void visit(MultipleElementSymbol obj) {   
+		List<ElementSymbol> oldSymbols = obj.getElementSymbols();
 		if(oldSymbols != null && oldSymbols.size() > 0) {
-			List newSymbols = new ArrayList(oldSymbols.size());
+			List<ElementSymbol> newSymbols = new ArrayList<ElementSymbol>(oldSymbols.size());
 			
-			Iterator iter = oldSymbols.iterator();
+			Iterator<ElementSymbol> iter = oldSymbols.iterator();
 			while(iter.hasNext()) {
-				ElementSymbol es = (ElementSymbol) iter.next();    
+				ElementSymbol es = iter.next();    
 				ElementSymbol mappedSymbol = getMappedElement(es);
-				
-				// Save group name on first valid mapped element
-				if(newGroupName == null && mappedSymbol != null) { 
-				    GroupSymbol newGroup = mappedSymbol.getGroupSymbol();
-				    if(newGroup != null) { 
-					    newGroupName = newGroup.getName();
-				    }
-				}
-				
 				newSymbols.add( mappedSymbol );
 			}
 			obj.setElementSymbols(newSymbols);
 		} 	
-
-		// If haven't discovered group name yet (if, for instance, stuff isn't resolved),
-		// then fake up a group symbol, map it, and use the name of the mapped group symbol
-		if(newGroupName == null) {
-			String symbolName = obj.getName();
-			String oldGroupName = symbolName.substring(0, symbolName.length()-2);	// cut .* off
-			
-			GroupSymbol fakeSymbol = new GroupSymbol(oldGroupName);
-			GroupSymbol mappedSymbol = getMappedGroup(fakeSymbol);
-			
-			newGroupName = mappedSymbol.getName();
+		
+		if (obj.getGroup() == null) {
+			return;
 		}
 		
-		// Finally, swap name of group, which should be the name of the group
-		// for all of the element symbols
-		obj.setShortName(newGroupName + ".*"); //$NON-NLS-1$
-			
+		obj.setGroup(getMappedGroup(obj.getGroup()));
     }
 
 	/**
-	 * Swap each ElementSymbol referenced by AllSymbol
-	 * @param obj Object to remap
-	 */
-    public void visit(AllSymbol obj) {
-		List oldSymbols = obj.getElementSymbols();
-		if(oldSymbols != null && oldSymbols.size() > 0) {
-			List newSymbols = new ArrayList(oldSymbols.size());
-			
-			Iterator iter = oldSymbols.iterator();
-			while(iter.hasNext()) {
-				ElementSymbol es = (ElementSymbol) iter.next();    
-				newSymbols.add( getMappedElement(es) );
-			}
-
-			obj.setElementSymbols(newSymbols);
-		}		
-    }
-    
-	/**
 	 * Swap group in unary from clause.
 	 * @param obj Object to remap
 	 */

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AggregateSymbolCollectorVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AggregateSymbolCollectorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/AggregateSymbolCollectorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,23 +25,28 @@
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.HashSet;
+import java.util.LinkedHashSet;
 
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.navigator.PreOrPostOrderNavigator;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.ExpressionSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.Expression;
+import org.teiid.query.sql.symbol.WindowFunction;
 
 
 public class AggregateSymbolCollectorVisitor extends LanguageVisitor {
     
     public static class AggregateStopNavigator extends PreOrPostOrderNavigator {
-        
-        public AggregateStopNavigator(LanguageVisitor visitor) {
-            super(visitor, PreOrPostOrderNavigator.POST_ORDER, false);
+    	
+    	private Collection<? extends Expression> groupingCols;
+    	private Collection<? super Expression> groupingColsUsed;
+    	
+        public AggregateStopNavigator(LanguageVisitor visitor, Collection<? super Expression> groupingColsUsed, Collection<? extends Expression> groupingCols) {
+            super(visitor, PreOrPostOrderNavigator.PRE_ORDER, false);
+            this.groupingCols = groupingCols;
+            this.groupingColsUsed = groupingColsUsed;
         }
         
         public void visit(AggregateSymbol obj) {
@@ -50,52 +55,56 @@
             postVisitVisitor(obj);
         }
         
-        /** 
-         * @see org.teiid.query.sql.navigator.PreOrPostOrderNavigator#visit(org.teiid.query.sql.symbol.ExpressionSymbol)
-         */
         @Override
-        public void visit(ExpressionSymbol obj) {
-            if (obj.isDerivedExpression()) {
-                preVisitVisitor(obj);
-                postVisitVisitor(obj);
-            } else {
-                super.visit(obj);
-            }
+        protected void visitNode(LanguageObject obj) {
+        	if (groupingCols != null && obj instanceof Expression && groupingCols.contains(obj)) {
+        		if (groupingColsUsed != null) {
+        			groupingColsUsed.add((Expression)obj);
+        		}
+        		return;
+        	}
+        	super.visitNode(obj);
         }
-         
+        
     }
 
-    private Collection<AggregateSymbol> aggregates;
-    private Collection<SingleElementSymbol> groupingSymbols;
+    private Collection<? super AggregateSymbol> aggregates;
+    private Collection<? super ElementSymbol> otherElements;
+    private Collection<? super WindowFunction> windowFunctions;
     
-	public AggregateSymbolCollectorVisitor(Collection<AggregateSymbol> aggregates, Collection<SingleElementSymbol> elements) { 
+	public AggregateSymbolCollectorVisitor(Collection<? super AggregateSymbol> aggregates, Collection<? super ElementSymbol> elements) { 
         this.aggregates = aggregates;
-        this.groupingSymbols = elements;
+        this.otherElements = elements;
 	}	
     
     public void visit(AggregateSymbol obj) {
-        if (aggregates != null) {
+        if (aggregates != null && !obj.isWindowed()) {
             this.aggregates.add(obj);
         }
     }
     
-    public void visit(ExpressionSymbol obj) {
-        if (this.groupingSymbols != null && obj.isDerivedExpression()) {
-            this.groupingSymbols.add(obj);     
-        }
+    public void visit(WindowFunction windowFunction) {
+    	if (this.windowFunctions != null) {
+    		this.windowFunctions.add(windowFunction);
+    	}
     }
-
+    
     public void visit(ElementSymbol obj) {
-        if (this.groupingSymbols != null) {
-            this.groupingSymbols.add(obj);  
+        if (this.otherElements != null && !obj.isExternalReference()) {
+            this.otherElements.add(obj);  
         }
     }
 
-    public static final void getAggregates(LanguageObject obj, Collection<SingleElementSymbol> aggregates, Collection<SingleElementSymbol> elements) {
-        AggregateSymbolCollectorVisitor visitor = new AggregateSymbolCollectorVisitor(new ArrayList<AggregateSymbol>(), elements);
-        AggregateStopNavigator asn = new AggregateStopNavigator(visitor);
-        obj.acceptVisitor(asn);
-        aggregates.addAll(visitor.aggregates);
+    public static final void getAggregates(LanguageObject obj, 
+    		Collection<? super AggregateSymbol> aggregates, 
+    		Collection<? super ElementSymbol> otherElements, 
+    		Collection<? super Expression> groupingColsUsed, 
+    		Collection<? super WindowFunction> windowFunctions, 
+    		Collection<? extends Expression> groupingCols) {
+        AggregateSymbolCollectorVisitor visitor = new AggregateSymbolCollectorVisitor(aggregates, otherElements);
+        visitor.windowFunctions = windowFunctions;
+        AggregateStopNavigator asn = new AggregateStopNavigator(visitor, groupingColsUsed, groupingCols);
+        asn.visitNode(obj);
     }
 
     public static final Collection<AggregateSymbol> getAggregates(LanguageObject obj, boolean removeDuplicates) {
@@ -104,12 +113,12 @@
     	}
         Collection<AggregateSymbol> aggregates = null;
         if (removeDuplicates) {
-            aggregates = new HashSet<AggregateSymbol>();
+            aggregates = new LinkedHashSet<AggregateSymbol>();
         } else {
             aggregates = new ArrayList<AggregateSymbol>();    
         }
         AggregateSymbolCollectorVisitor visitor = new AggregateSymbolCollectorVisitor(aggregates, null);
-        AggregateStopNavigator asn = new AggregateStopNavigator(visitor);
+        AggregateStopNavigator asn = new AggregateStopNavigator(visitor, null, null);
         obj.acceptVisitor(asn);
         return aggregates;
     }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ElementCollectorVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ElementCollectorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ElementCollectorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,9 +32,8 @@
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.navigator.DeepPreOrderNavigator;
 import org.teiid.query.sql.navigator.PreOrderNavigator;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 
 
 /**
@@ -49,7 +48,8 @@
  */
 public class ElementCollectorVisitor extends LanguageVisitor {
 
-    private Collection<ElementSymbol> elements;
+    private Collection<? super ElementSymbol> elements;
+    private boolean aggsOnly;
 
     /**
      * Construct a new visitor with the specified collection, which should
@@ -57,7 +57,7 @@
      * @param elements Collection to use for elements
      * @throws IllegalArgumentException If elements is null
      */
-	public ElementCollectorVisitor(Collection<ElementSymbol> elements) {
+	public ElementCollectorVisitor(Collection<? super ElementSymbol> elements) {
         if(elements == null) {
             throw new IllegalArgumentException(QueryPlugin.Util.getString("ERR.015.010.0021")); //$NON-NLS-1$
         }
@@ -65,21 +65,14 @@
     }
 
     /**
-     * Get the elements collected by the visitor.  This should best be called
-     * after the visitor has been run on the language object tree.
-     * @return Collection of {@link org.teiid.query.sql.symbol.ElementSymbol}
-     */
-    public Collection<ElementSymbol> getElements() {
-        return this.elements;
-    }
-
-    /**
      * 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) {
-        this.elements.add(obj);
+    	if (!aggsOnly || obj.isAggregate()) {
+            this.elements.add(obj);
+    	}
     }
 
     /**
@@ -87,29 +80,18 @@
      * called directly.
      * @param obj Language object
      */
-    public void visit(AllInGroupSymbol obj) {
+    public void visit(MultipleElementSymbol obj) {
         if(obj.getElementSymbols() != null) {
 	        this.elements.addAll(obj.getElementSymbols());
         }
     }
 
     /**
-     * Visit a language object and collect symbols.  This method should <b>NOT</b> be
-     * called directly.
-     * @param obj Language object
-     */
-    public void visit(AllSymbol obj) {
-        if(obj.getElementSymbols() != null) {
-	        this.elements.addAll(obj.getElementSymbols());
-        }
-    }
-
-    /**
      * Helper to quickly get the elements from obj in the elements collection
      * @param obj Language object
      * @param elements Collection to collect elements in
      */
-    public static final void getElements(LanguageObject obj, Collection<ElementSymbol> elements) {
+    public static final void getElements(LanguageObject obj, Collection<? super ElementSymbol> elements) {
     	if(obj == null) {
     		return;
     	}
@@ -150,6 +132,10 @@
      * @return Collection of {@link org.teiid.query.sql.symbol.ElementSymbol}
      */
     public static final Collection<ElementSymbol> getElements(LanguageObject obj, boolean removeDuplicates, boolean useDeepIteration) {
+    	return getElements(obj, removeDuplicates, useDeepIteration, false);
+    }
+    
+    public static final Collection<ElementSymbol> getElements(LanguageObject obj, boolean removeDuplicates, boolean useDeepIteration, boolean aggsOnly) {
         if(obj == null) {
             return Collections.emptyList();
         }
@@ -159,16 +145,20 @@
         } else {
             elements = new ArrayList<ElementSymbol>();
         }
-        ElementCollectorVisitor visitor = null;
+        ElementCollectorVisitor visitor = new ElementCollectorVisitor(elements);
+        visitor.aggsOnly = aggsOnly;
         if (useDeepIteration){
-            visitor = new ElementCollectorVisitor(elements);
             DeepPreOrderNavigator.doVisit(obj, visitor);
         } else {
-            visitor = new ElementCollectorVisitor(elements);
             PreOrderNavigator.doVisit(obj, visitor);
         }
         
         return elements;
     }
+    
+    public static final Collection<ElementSymbol> getAggregates(LanguageObject obj, boolean removeDuplicates) {
+    	return getElements(obj, removeDuplicates, false, true);
+    }
 
+
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ExpressionMappingVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ExpressionMappingVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/ExpressionMappingVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,6 +24,7 @@
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
@@ -52,6 +53,7 @@
 import org.teiid.query.sql.lang.SubquerySetCriteria;
 import org.teiid.query.sql.lang.XMLTable;
 import org.teiid.query.sql.lang.XMLTable.XMLColumn;
+import org.teiid.query.sql.navigator.PreOrPostOrderNavigator;
 import org.teiid.query.sql.navigator.PreOrderNavigator;
 import org.teiid.query.sql.proc.AssignmentStatement;
 import org.teiid.query.sql.symbol.AggregateSymbol;
@@ -65,6 +67,7 @@
 import org.teiid.query.sql.symbol.QueryString;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
+import org.teiid.query.sql.symbol.WindowSpecification;
 import org.teiid.query.sql.symbol.XMLElement;
 import org.teiid.query.sql.symbol.XMLParse;
 import org.teiid.query.sql.symbol.XMLSerialize;
@@ -78,6 +81,7 @@
 
     private Map symbolMap;
     private boolean clone = true;
+    private boolean elementSymbolsOnly;
 
     /**
      * Constructor for ExpressionMappingVisitor.
@@ -251,7 +255,7 @@
 
     public void visit(SearchedCaseExpression obj) {
         int whenCount = obj.getWhenCount();
-        ArrayList thens = new ArrayList(whenCount);
+        ArrayList<Expression> thens = new ArrayList<Expression>(whenCount);
         for (int i = 0; i < whenCount; i++) {
             thens.add(replaceExpression(obj.getThenExpression(i)));
         }
@@ -299,6 +303,9 @@
     }    
     
     public Expression replaceExpression(Expression element) {
+    	if (elementSymbolsOnly && !(element instanceof ElementSymbol)) {
+    		return element;
+    	}
         Expression mapped = (Expression) this.symbolMap.get(element);
         if(mapped != null) {
         	if (clone) {
@@ -310,17 +317,20 @@
     }
     
     public void visit(StoredProcedure obj) {
-    	for (Iterator paramIter = obj.getInputParameters().iterator(); paramIter.hasNext();) {
-			SPParameter param = (SPParameter) paramIter.next();
+    	for (Iterator<SPParameter> paramIter = obj.getInputParameters().iterator(); paramIter.hasNext();) {
+			SPParameter param = paramIter.next();
             Expression expr = param.getExpression();
             param.setExpression(replaceExpression(expr));
         }
     }
     
     public void visit(AggregateSymbol obj) {
-    	if (obj.getExpression() != null) { //account for count(*) - TODO: clean this up
+    	if (obj.getExpression() != null) {
     		obj.setExpression(replaceExpression(obj.getExpression()));
     	}
+    	if (obj.getCondition() != null) { 
+    		obj.setCondition(replaceExpression(obj.getCondition()));
+    	}
     }
     
     /**
@@ -328,7 +338,11 @@
      * @param obj Object to remap
      */
     public void visit(GroupBy obj) {        
-        replaceSymbols(obj.getSymbols(), false);
+    	List<Expression> symbols = obj.getSymbols();
+		for (int i = 0; i < symbols.size(); i++) {
+            Expression symbol = symbols.get(i);
+            symbols.set(i, replaceExpression(symbol));
+        }
     }
     
     @Override
@@ -371,21 +385,47 @@
      * @param obj Language object
      * @param exprMap Expression map, Expression to Expression
      */
-    public static void mapExpressions(LanguageObject obj, Map exprMap) {
+    public static void mapExpressions(LanguageObject obj, Map<? extends Expression, ? extends Expression> exprMap) {
         if(obj == null || exprMap == null || exprMap.isEmpty()) { 
             return;
         }
-        final Set reverseSet = new HashSet(exprMap.values());
         final ExpressionMappingVisitor visitor = new ExpressionMappingVisitor(exprMap);
-        PreOrderNavigator pon = new PreOrderNavigator(visitor) {
-        	@Override
-        	protected void visitNode(LanguageObject obj) {
-        		if (!(obj instanceof Expression) || !reverseSet.contains(obj)) {
-            		super.visitNode(obj);
-        		}
+        visitor.elementSymbolsOnly = true;
+        boolean preOrder = true;
+        boolean useReverseMapping = true;
+        for (Map.Entry<? extends Expression, ? extends Expression> entry : exprMap.entrySet()) {
+        	if (!(entry.getKey() instanceof ElementSymbol)) {
+        		visitor.elementSymbolsOnly = false;
+        		break;
         	}
-        };
-        obj.acceptVisitor(pon);
+		}
+        if (!visitor.elementSymbolsOnly) {
+        	for (Map.Entry<? extends Expression, ? extends Expression> entry : exprMap.entrySet()) {
+            	if (!(entry.getValue() instanceof ElementSymbol)) {
+            		useReverseMapping = !Collections.disjoint(GroupsUsedByElementsVisitor.getGroups(exprMap.keySet()),
+                    		GroupsUsedByElementsVisitor.getGroups(exprMap.values()));
+            		break;
+            	}
+    		}
+        } else {
+        	preOrder = false;
+        	useReverseMapping = false;
+        }
+        
+        if (useReverseMapping) {
+	        final Set<Expression> reverseSet = new HashSet<Expression>(exprMap.values());
+	        PreOrderNavigator pon = new PreOrderNavigator(visitor) {
+	        	@Override
+	        	protected void visitNode(LanguageObject obj) {
+	        		if (!(obj instanceof Expression) || !reverseSet.contains(obj)) {
+	            		super.visitNode(obj);
+	        		}
+	        	}
+	        };
+	        obj.acceptVisitor(pon);
+        } else {
+        	PreOrPostOrderNavigator.doVisit(obj, visitor, preOrder, false);
+        }
     }
     
     protected void setVariableValues(Map variableValues) {
@@ -421,4 +461,15 @@
     	}
     }
     
+    @Override
+    public void visit(WindowSpecification windowSpecification) {
+    	if (windowSpecification.getPartition() == null) {
+    		return;
+    	}
+    	List<Expression> partition = windowSpecification.getPartition();
+		for (int i = 0; i < partition.size(); i++) {
+    		partition.set(i, replaceExpression(partition.get(i)));
+    	}
+    }
+    
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/GroupsUsedByElementsVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/GroupsUsedByElementsVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/GroupsUsedByElementsVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -42,7 +42,9 @@
         Collection<ElementSymbol> elements = ElementCollectorVisitor.getElements(obj, true);
 
         for (ElementSymbol elementSymbol : elements) {
-            groups.add(elementSymbol.getGroupSymbol());            
+        	if (elementSymbol.getGroupSymbol() != null) {
+        		groups.add(elementSymbol.getGroupSymbol());  
+        	}
         }
     }
 

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/PredicateCollectorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -45,14 +45,14 @@
  */
 public class PredicateCollectorVisitor extends LanguageVisitor {
 
-    private Collection predicates;
+    private Collection<Criteria> predicates;
 
     /**
      * Construct a new visitor with the default collection type, which is a
      * {@link java.util.ArrayList}.
      */
     public PredicateCollectorVisitor() {
-        this.predicates = new ArrayList();
+        this.predicates = new ArrayList<Criteria>();
     }
 
     /**
@@ -136,7 +136,7 @@
      * Get a collection of predicates discovered while visiting.
      * @return Collection of {@link org.teiid.query.sql.lang.PredicateCriteria} subclasses.
      */
-    public Collection getPredicates() {
+    public Collection<Criteria> getPredicates() {
         return this.predicates;
     }
 
@@ -144,7 +144,7 @@
      * Helper to quickly get the predicates from obj
      * @param obj Language object
      */
-    public static final Collection getPredicates(LanguageObject obj) {
+    public static final Collection<Criteria> getPredicates(LanguageObject obj) {
         PredicateCollectorVisitor visitor = new PredicateCollectorVisitor();
         if(obj != null) {
             PreOrderNavigator.doVisit(obj, visitor);

Modified: branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/sql/visitor/SQLStringVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -93,9 +93,8 @@
 import org.teiid.query.sql.lang.XMLTable.XMLColumn;
 import org.teiid.query.sql.proc.AssignmentStatement;
 import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.BreakStatement;
+import org.teiid.query.sql.proc.BranchingStatement;
 import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.ContinueStatement;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.proc.CriteriaSelector;
 import org.teiid.query.sql.proc.DeclareStatement;
@@ -107,10 +106,9 @@
 import org.teiid.query.sql.proc.TranslateCriteria;
 import org.teiid.query.sql.proc.TriggerAction;
 import org.teiid.query.sql.proc.WhileStatement;
+import org.teiid.query.sql.proc.Statement.Labeled;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.CaseExpression;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.DerivedColumn;
@@ -119,6 +117,7 @@
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.QueryString;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
@@ -126,6 +125,8 @@
 import org.teiid.query.sql.symbol.SelectSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.WindowFunction;
+import org.teiid.query.sql.symbol.WindowSpecification;
 import org.teiid.query.sql.symbol.XMLAttributes;
 import org.teiid.query.sql.symbol.XMLElement;
 import org.teiid.query.sql.symbol.XMLForest;
@@ -133,6 +134,7 @@
 import org.teiid.query.sql.symbol.XMLParse;
 import org.teiid.query.sql.symbol.XMLQuery;
 import org.teiid.query.sql.symbol.XMLSerialize;
+import org.teiid.query.sql.symbol.AggregateSymbol.Type;
 import org.teiid.query.sql.symbol.XMLNamespaces.NamespaceItem;
 import org.teiid.translator.SourceSystemFunctions;
 
@@ -447,7 +449,7 @@
     }
 
     public void visit( JoinPredicate obj ) {
-        addOptionComment(obj);
+        addHintComment(obj);
 
         if (obj.hasHint()) {
             append("(");//$NON-NLS-1$
@@ -506,29 +508,31 @@
         if (obj.hasHint()) {
             append(")"); //$NON-NLS-1$
         }
-        addFromClasueDepOptions(obj);
     }
 
-    private void addFromClasueDepOptions( FromClause obj ) {
-        if (obj.isMakeDep()) {
+    private void addHintComment( FromClause obj ) {
+    	if (obj.hasHint()) {
+    		append(BEGIN_HINT);
             append(SPACE);
-            append(Option.MAKEDEP);
-        }
-        if (obj.isMakeNotDep()) {
-            append(SPACE);
-            append(Option.MAKENOTDEP);
-        }
-    }
-
-    private void addOptionComment( FromClause obj ) {
-        if (obj.isOptional()) {
-            append(BEGIN_HINT);
-            append(SPACE);
-            append(Option.OPTIONAL);
-            append(SPACE);
+            if (obj.isOptional()) {
+                append(Option.OPTIONAL);
+                append(SPACE);
+            }
+            if (obj.isMakeDep()) {
+                append(Option.MAKEDEP);
+                append(SPACE);
+            }
+            if (obj.isMakeNotDep()) {
+                append(Option.MAKENOTDEP);
+                append(SPACE);
+            }
+            if (obj.isMakeInd()) {
+                append(FromClause.MAKEIND);
+                append(SPACE);
+            }
             append(END_HINT);
             append(SPACE);
-        }
+    	}
     }
 
     public void visit( JoinType obj ) {
@@ -565,7 +569,19 @@
             append(NOT);
             append(SPACE);
         }
-        append(LIKE);
+        switch (obj.getMode()) {
+        case SIMILAR:
+        	append(SIMILAR);
+        	append(SPACE);
+        	append(TO);
+        	break;
+        case LIKE:
+        	append(LIKE);
+        	break;
+        case REGEX:
+        	append(LIKE_REGEX);
+        	break;
+        }
         append(SPACE);
 
         visitNode(obj.getRightExpression());
@@ -574,7 +590,7 @@
             append(SPACE);
             append(ESCAPE);
             append(" '"); //$NON-NLS-1$
-            append("" + obj.getEscapeChar()); //$NON-NLS-1$
+            append(String.valueOf(obj.getEscapeChar()));
             append("'"); //$NON-NLS-1$
         }
     }
@@ -589,16 +605,16 @@
     public void visit( Option obj ) {
         append(OPTION);
 
-        Collection groups = obj.getDependentGroups();
+        Collection<String> groups = obj.getDependentGroups();
         if (groups != null && groups.size() > 0) {
             append(" "); //$NON-NLS-1$
             append(MAKEDEP);
             append(" "); //$NON-NLS-1$
 
-            Iterator iter = groups.iterator();
+            Iterator<String> iter = groups.iterator();
 
             while (iter.hasNext()) {
-                outputDisplayName((String)iter.next());
+                outputDisplayName(iter.next());
 
                 if (iter.hasNext()) {
                     append(", ");//$NON-NLS-1$
@@ -1046,7 +1062,7 @@
     }
 
     public void visit( SubqueryFromClause obj ) {
-        addOptionComment(obj);
+        addHintComment(obj);
         if (obj.isTable()) {
             append(TABLE);
         }
@@ -1055,7 +1071,6 @@
         append(")");//$NON-NLS-1$
         append(" AS ");//$NON-NLS-1$
         append(obj.getOutputName());
-        addFromClasueDepOptions(obj);
     }
 
     public void visit( SubquerySetCriteria obj ) {
@@ -1076,9 +1091,8 @@
     }
 
     public void visit( UnaryFromClause obj ) {
-        addOptionComment(obj);
+        addHintComment(obj);
         visitNode(obj.getGroup());
-        addFromClasueDepOptions(obj);
     }
 
     public void visit( Update obj ) {
@@ -1123,7 +1137,9 @@
         }
 
         if (obj.getExpression() == null) {
-            append(Tokens.ALL_COLS);
+        	if (obj.getAggregateFunction() == Type.COUNT) {
+        		append(Tokens.ALL_COLS);
+        	}
         } else {
             visitNode(obj.getExpression());
         }
@@ -1133,6 +1149,16 @@
             visitNode(obj.getOrderBy());
         }
         append(")"); //$NON-NLS-1$
+        
+        if (obj.getCondition() != null) {
+        	append(SPACE);
+        	append(FILTER);
+        	append(Tokens.LPAREN);
+        	append(WHERE);
+        	append(SPACE);
+        	append(obj.getCondition());
+        	append(Tokens.RPAREN);
+        }
     }
 
     public void visit( AliasSymbol obj ) {
@@ -1143,14 +1169,16 @@
         append(escapeSinglePart(obj.getOutputName()));
     }
 
-    public void visit( AllInGroupSymbol obj ) {
-        append(obj.getName());
+    public void visit( MultipleElementSymbol obj ) {
+    	if (obj.getGroup() == null) {
+    		append(Tokens.ALL_COLS);
+    	} else {
+    		visitNode(obj.getGroup());
+    		append(Tokens.DOT);
+    		append(Tokens.ALL_COLS);
+    	}
     }
 
-    public void visit( AllSymbol obj ) {
-        append(obj.getName());
-    }
-
     public void visit( Constant obj ) {
         Class<?> type = obj.getType();
         String[] constantParts = null;
@@ -1288,6 +1316,20 @@
             outputDisplayName((String)((Constant)args[0]).getValue());
             registerNodes(args, 1);
             append(")"); //$NON-NLS-1$
+        } else if (name.equalsIgnoreCase(SourceSystemFunctions.TRIM)) {
+        	append(name);
+        	append(SQLConstants.Tokens.LPAREN);
+        	String value = (String)((Constant)args[0]).getValue();
+        	if (!value.equalsIgnoreCase(BOTH)) {
+	        	append(((Constant)args[0]).getValue());
+	            append(" "); //$NON-NLS-1$
+        	}
+            append(args[1]);
+            append(" "); //$NON-NLS-1$
+            append(FROM);
+            append(" "); //$NON-NLS-1$
+            append(args[2]);
+            append(")"); //$NON-NLS-1$
         } else {
             append(name);
             append("("); //$NON-NLS-1$
@@ -1340,21 +1382,35 @@
     // ############ Visitor methods for storedprocedure language objects ####################
 
     public void visit( Block obj ) {
-        List statements = obj.getStatements();
+    	addLabel(obj);
+        List<Statement> statements = obj.getStatements();
         // Add first clause
         append(BEGIN);
+        if (obj.isAtomic()) {
+        	append(SPACE);
+        	append(ATOMIC);
+        }
         append("\n"); //$NON-NLS-1$
-        Iterator stmtIter = statements.iterator();
+        Iterator<Statement> stmtIter = statements.iterator();
         while (stmtIter.hasNext()) {
             // Add each statement
             addTabs(1);
-            visitNode((Statement)stmtIter.next());
+            visitNode(stmtIter.next());
             append("\n"); //$NON-NLS-1$
         }
         addTabs(0);
         append(END);
     }
 
+	private void addLabel(Labeled obj) {
+		if (obj.getLabel() != null) {
+    		outputDisplayName(obj.getLabel());
+    		append(SPACE);
+    		append(Tokens.COLON);
+    		append(SPACE);
+    	}
+	}
+
     protected void addTabs( int level ) {
     }
 
@@ -1515,17 +1571,27 @@
         append(";"); //$NON-NLS-1$
     }
 
-    public void visit( BreakStatement obj ) {
-        append(BREAK);
+    public void visit( BranchingStatement obj ) {
+    	switch (obj.getMode()) {
+    	case CONTINUE:
+    		append(CONTINUE);
+    		break;
+    	case BREAK:
+    		append(BREAK);
+    		break;
+    	case LEAVE:
+    		append(LEAVE);
+    		break;
+    	}
+    	if (obj.getLabel() != null) {
+    		append(SPACE);
+    		outputDisplayName(obj.getLabel());
+    	}
         append(";"); //$NON-NLS-1$
     }
 
-    public void visit( ContinueStatement obj ) {
-        append(CONTINUE);
-        append(";"); //$NON-NLS-1$
-    }
-
     public void visit( LoopStatement obj ) {
+    	addLabel(obj);
         append(LOOP);
         append(" "); //$NON-NLS-1$
         append(ON);
@@ -1541,6 +1607,7 @@
     }
 
     public void visit( WhileStatement obj ) {
+    	addLabel(obj);
         append(WHILE);
         append("("); //$NON-NLS-1$
         visitNode(obj.getCondition());
@@ -1569,6 +1636,13 @@
             append(SubqueryHint.NOUNNEST);
             append(SPACE);
             append(END_HINT);
+    	} else if (hint.isDepJoin()) {
+    		append(SPACE);
+        	append(BEGIN_HINT);
+            append(SPACE);
+            append(SubqueryHint.DJ);
+            append(SPACE);
+            append(END_HINT);
         } else if (hint.isMergeJoin()) {
             append(SPACE);
         	append(BEGIN_HINT);
@@ -1699,6 +1773,14 @@
     }
 
     public void visit( Limit obj ) {
+    	if (obj.getRowLimit() == null) {
+    		append(OFFSET);
+    		append(SPACE);
+            visitNode(obj.getOffset());
+            append(SPACE);
+            append(ROWS);
+    		return;
+    	}
         append(LIMIT);
         if (obj.getOffset() != null) {
             append(SPACE);
@@ -1711,6 +1793,7 @@
 
     @Override
     public void visit( TextTable obj ) {
+        addHintComment(obj);
         append("TEXTTABLE("); //$NON-NLS-1$
         visitNode(obj.getFile());
         append(SPACE);
@@ -1728,10 +1811,24 @@
                 append(SPACE);
                 append(col.getWidth());
             }
+            if (col.isNoTrim()) {
+            	append(SPACE);
+                append(NO);
+                append(SPACE);
+                append(NonReserved.TRIM);
+            }
             if (cols.hasNext()) {
                 append(","); //$NON-NLS-1$
             }
         }
+        if (!obj.isUsingRowDelimiter()) {
+        	append(SPACE);
+            append(NO);
+        	append(SPACE);
+            append(ROW);
+        	append(SPACE);
+            append(NonReserved.DELIMITER);
+        }
         if (obj.getDelimiter() != null) {
             append(SPACE);
             append(NonReserved.DELIMITER);
@@ -1771,6 +1868,7 @@
 
     @Override
     public void visit( XMLTable obj ) {
+        addHintComment(obj);
         append("XMLTABLE("); //$NON-NLS-1$
         if (obj.getNamespaces() != null) {
             visitNode(obj.getNamespaces());
@@ -1936,6 +2034,7 @@
     
     @Override
     public void visit(ArrayTable obj) {
+        addHintComment(obj);
     	append("ARRAYTABLE("); //$NON-NLS-1$
         visitNode(obj.getArrayValue());
         append(SPACE);
@@ -2016,6 +2115,36 @@
         addTabs(0);
     	append(alterView.getDefinition());
     }
+    
+    @Override
+    public void visit(WindowFunction windowFunction) {
+    	append(windowFunction.getFunction());
+    	append(SPACE);
+    	append(OVER);
+    	append(SPACE);
+    	append(windowFunction.getWindowSpecification());
+    }
+    
+    @Override
+    public void visit(WindowSpecification windowSpecification) {
+    	append(Tokens.LPAREN);
+    	boolean needsSpace = false;
+    	if (windowSpecification.getPartition() != null) {
+    		append(PARTITION);
+    		append(SPACE);
+    		append(BY);
+    		append(SPACE);
+    		registerNodes(windowSpecification.getPartition(), 0);
+    		needsSpace = true;
+    	}
+    	if (windowSpecification.getOrderBy() != null) {
+    		if (needsSpace) {
+    			append(SPACE);
+    		}
+    		append(windowSpecification.getOrderBy());
+    	}
+    	append(Tokens.RPAREN);	
+    }
 
     public static String escapeSinglePart( String part ) {
         if (isReservedWord(part)) {

Copied: branches/as7/engine/src/main/java/org/teiid/query/tempdata/AlterTempTable.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/tempdata/AlterTempTable.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/tempdata/AlterTempTable.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/tempdata/AlterTempTable.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,78 @@
+package org.teiid.query.tempdata;
+
+import java.util.List;
+
+import org.teiid.query.sql.LanguageVisitor;
+import org.teiid.query.sql.lang.Command;
+import org.teiid.query.sql.symbol.ElementSymbol;
+import org.teiid.query.sql.symbol.SingleElementSymbol;
+
+/*
+ * 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.
+ */
+
+public class AlterTempTable extends Command {
+	
+	private String tempTable;
+	private List<ElementSymbol> indexColumns;
+	
+	public AlterTempTable(String tempTable) {
+		this.tempTable = tempTable;
+	}
+	
+	public String getTempTable() {
+		return tempTable;
+	}
+	
+	public List<ElementSymbol> getIndexColumns() {
+		return indexColumns;
+	}
+	
+	public void setIndexColumns(List<ElementSymbol> indexColumns) {
+		this.indexColumns = indexColumns;
+	}
+	
+	@Override
+	public boolean areResultsCachable() {
+		return false;
+	}
+
+	@Override
+	public Object clone() {
+		return this;
+	}
+
+	@Override
+	public List<SingleElementSymbol> getProjectedSymbols() {
+		return Command.getUpdateCommandSymbol();
+	}
+
+	@Override
+	public int getType() {
+		return Command.TYPE_UNKNOWN;
+	}
+
+	@Override
+	public void acceptVisitor(LanguageVisitor visitor) {
+		
+	}
+
+}

Modified: branches/as7/engine/src/main/java/org/teiid/query/tempdata/IndexInfo.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/tempdata/IndexInfo.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/tempdata/IndexInfo.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,6 +23,7 @@
 package org.teiid.query.tempdata;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.LinkedList;
@@ -32,8 +33,10 @@
 import org.teiid.common.buffer.TupleBrowser;
 import org.teiid.common.buffer.TupleSource;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.language.Like.MatchMode;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
+import org.teiid.query.eval.Evaluator;
 import org.teiid.query.processor.CollectionTupleSource;
 import org.teiid.query.processor.relational.RelationalNode;
 import org.teiid.query.sql.lang.CompareCriteria;
@@ -126,22 +129,45 @@
 						Constant value = (Constant)matchCriteria.getRightExpression();
 						String pattern = (String)value.getValue();
 						boolean escaped = false;
+						char escapeChar = matchCriteria.getEscapeChar();
+						if (matchCriteria.getMode() == MatchMode.REGEX) {
+							escapeChar = '\\';
+						}
 						StringBuilder prefix = new StringBuilder();
-						for (int j = 0; i < pattern.length(); j++) {
+						
+			            if (pattern.length() > 0 && matchCriteria.getMode() == MatchMode.REGEX && pattern.charAt(0) != '^') {
+			            	//make the assumption that we require an anchor
+			            	continue;
+			            }
+
+						for (int j = matchCriteria.getMode() == MatchMode.REGEX?1:0; i < pattern.length(); j++) {
 				            char character = pattern.charAt(j);
 				            
-				            if (character == matchCriteria.getEscapeChar() && character != MatchCriteria.NULL_ESCAPE_CHAR) {
+				            if (character == escapeChar && character != MatchCriteria.NULL_ESCAPE_CHAR) {
 				                if (escaped) {
 				                    prefix.append(character);
 				                    escaped = false;
 				                } else {
 				                    escaped = true;
 				                }
-				            } else if (character == MatchCriteria.WILDCARD_CHAR || character == MatchCriteria.MATCH_CHAR) {
-				            	break;
+				                continue;
+				            }
+				            if (!escaped) {
+				            	if (matchCriteria.getMode() == MatchMode.LIKE) {
+					            	if (character == MatchCriteria.WILDCARD_CHAR || character == MatchCriteria.MATCH_CHAR) {
+						            	break;
+					            	}
+				            	} else {
+				            		int index = Arrays.binarySearch(Evaluator.REGEX_RESERVED, character);
+				            		if (index >= 0 && pattern.length() > 0) {
+				            			getRegexPrefix(pattern, escapeChar, prefix, j, character);
+				            			break;
+				            		}
+				            	}
 				            } else {
-				            	prefix.append(character);
+					            escaped = false;
 				            }
+				            prefix.append(character);
 						}
 						if (prefix.length() > 0) {
 							this.addCondition(i, new Constant(prefix.toString()), CompareCriteria.GE);
@@ -158,6 +184,32 @@
 			}
 		}
 	}
+
+	private void getRegexPrefix(String pattern, char escapeChar,
+			StringBuilder prefix, int j, char character) {
+		boolean escaped = false;
+		//check the rest of the expression for |
+		int level = 0;
+		for (int k = j; k < pattern.length(); k++) {
+			character = pattern.charAt(k);
+		    if (character == escapeChar && character != MatchCriteria.NULL_ESCAPE_CHAR) {
+		        escaped = !escaped;
+		    } else if (!escaped) {
+		    	if (character == '(') {
+		    		level++;
+		    	} else if (character == ')') {
+		    		level--;
+		    	} else if (character == '|' && level == 0) {
+		    		prefix.setLength(0); //TODO: turn this into an IN condition
+		    		return;
+		    	}
+		    }
+		}
+
+		if (character == '{' || character == '?' || character == '*') {
+			prefix.setLength(prefix.length() - 1); 
+		}
+	}
 	
 	void addCondition(int i, Constant value, int comparisionMode) {
 		switch (comparisionMode) {

Modified: branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableDataManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -206,7 +206,7 @@
         		return null;
         	}
         	final String groupKey = group.getNonCorrelationName().toUpperCase();
-            final TempTable table = contextStore.getOrCreateTempTable(groupKey, command, bufferManager, false);
+            final TempTable table = contextStore.getOrCreateTempTable(groupKey, command, bufferManager, true);
         	if (command instanceof Insert) {
         		Insert insert = (Insert)command;
         		TupleSource ts = insert.getTupleSource();
@@ -249,6 +249,15 @@
     		contextStore.removeTempTableByName(tempTableName);
             return CollectionTupleSource.createUpdateCountTupleSource(0);
     	}
+    	if (command instanceof AlterTempTable) {
+    		AlterTempTable att = (AlterTempTable)command;
+    		TempTable tt = contextStore.getOrCreateTempTable(att.getTempTable().toUpperCase(), command, bufferManager, true);
+    		tt.setUpdatable(false);
+    		if (att.getIndexColumns() != null) {
+    			tt.addIndex(att.getIndexColumns(), false);
+    		}
+    		return CollectionTupleSource.createUpdateCountTupleSource(0);
+    	}
         return null;
     }
 
@@ -309,15 +318,27 @@
 		QueryMetadataInterface metadata = context.getMetadata();
 		TempTableStore globalStore = context.getGlobalTableStore();
 		if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEW)) {
-			Object groupID = validateMatView(metadata, proc);
+			Object groupID = validateMatView(metadata, (String)((Constant)proc.getParameter(1).getExpression()).getValue());
 			Object matTableId = context.getGlobalTableStore().getGlobalTempTableMetadataId(groupID, metadata);
 			String matViewName = metadata.getFullName(groupID);
 			String matTableName = metadata.getFullName(matTableId);
 			LogManager.logDetail(LogConstants.CTX_MATVIEWS, "processing refreshmatview for", matViewName); //$NON-NLS-1$
 			MatTableInfo info = globalStore.getMatTableInfo(matTableName);
-			boolean invalidate = Boolean.TRUE.equals(((Constant)proc.getParameter(1).getExpression()).getValue());
+			Long loadTime = null;
+			boolean useCache = false;
+			if (this.distributedCache != null) {
+				MatTableKey key = new MatTableKey();
+				key.name = matTableName;
+				key.vdb = new VDBKey(context.getVdbName(),context.getVdbVersion());
+				MatTableEntry entry = this.tables.get(key);
+				useCache = (entry != null && entry.valid && entry.lastUpdate > info.getUpdateTime());
+				if (useCache) {
+					loadTime = entry.lastUpdate;
+				}
+			}			
+			boolean invalidate = Boolean.TRUE.equals(((Constant)proc.getParameter(2).getExpression()).getValue());
 			if (invalidate) {
-				touchTable(context, matTableName, false);
+				touchTable(context, matTableName, false, System.currentTimeMillis());
 			}
 			MatState oldState = info.setState(MatState.NEEDS_LOADING, invalidate?Boolean.FALSE:null, null);
 			if (oldState == MatState.LOADING) {
@@ -325,10 +346,10 @@
 			}
 			GroupSymbol matTable = new GroupSymbol(matTableName);
 			matTable.setMetadataID(matTableId);
-			int rowCount = loadGlobalTable(context, matTable, matTableName, globalStore, info, null);
+			int rowCount = loadGlobalTable(context, matTable, matTableName, matViewName, globalStore, info, invalidate?null:loadTime, !invalidate && useCache);
 			return CollectionTupleSource.createUpdateCountTupleSource(rowCount);
 		} else if (StringUtil.endsWithIgnoreCase(proc.getProcedureCallableName(), REFRESHMATVIEWROW)) {
-			Object groupID = validateMatView(metadata, proc);
+			Object groupID = validateMatView(metadata, (String)((Constant)proc.getParameter(1).getExpression()).getValue());
 			Object pk = metadata.getPrimaryKey(groupID);
 			String matViewName = metadata.getFullName(groupID);
 			if (pk == null) {
@@ -363,6 +384,7 @@
 			}
 			List<?> result = updateMatViewRow(globalStore, matTableName, tuple, delete);
 			if (result != null && eventDistributor != null) {
+				result = new ArrayList<Object>(result); //ensure the list is serializable
 				this.eventDistributor.updateMatViewRow(context.getVdbName(), context.getVdbVersion(), metadata.getName(metadata.getModelID(groupID)), metadata.getName(groupID), tuple, delete);
 			}
 			return CollectionTupleSource.createUpdateCountTupleSource(result != null ? 1 : 0);
@@ -376,15 +398,36 @@
 		TempTable tempTable = globalStore.getOrCreateTempTable(matTableName, new Query(), bufferManager, false);
 		return tempTable.updateTuple(tuple, delete);
 	}
+	
+	public void refreshMatView(String vdbName, int vdbVersion, String viewName, 
+			QueryMetadataInterface metadata, TempTableStore globalStore) 
+			throws QueryProcessingException, TeiidComponentException, TeiidProcessingException {
+			
+		Object groupID = validateMatView(metadata, viewName);
+		Object matTableId = globalStore.getGlobalTempTableMetadataId(groupID, metadata);
+		String matViewName = metadata.getFullName(groupID);
+		String matTableName = metadata.getFullName(matTableId);
+		LogManager.logDetail(LogConstants.CTX_MATVIEWS, "processing refreshmatview for", matViewName); //$NON-NLS-1$
+		MatTableInfo info = globalStore.getMatTableInfo(matTableName);
 
-	private Object validateMatView(QueryMetadataInterface metadata,
-			StoredProcedure proc) throws TeiidComponentException,
+		MatState oldState = info.setState(MatState.NEEDS_LOADING, Boolean.FALSE, null);
+		if (oldState == MatState.LOADING) {
+			return;
+		}
+		GroupSymbol matTable = new GroupSymbol(matTableName);
+		matTable.setMetadataID(matTableId);
+		CommandContext context = new CommandContext(new Object(), "internal", "internal", vdbName, vdbVersion); //$NON-NLS-1$ //$NON-NLS-2$
+		context.setMetadata(metadata);
+		context.setGlobalTableStore(globalStore);
+		loadGlobalTable(context, matTable, matTableName, matViewName, globalStore, info, null, true);		
+	}	
+
+	private Object validateMatView(QueryMetadataInterface metadata,	String viewName) throws TeiidComponentException,
 			TeiidProcessingException {
-		String name = (String)((Constant)proc.getParameter(1).getExpression()).getValue();
 		try {
-			Object groupID = metadata.getGroupID(name);
+			Object groupID = metadata.getGroupID(viewName);
 			if (!metadata.hasMaterialization(groupID) || metadata.getMaterialization(groupID) != null) {
-				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.not_implicit_matview", name)); //$NON-NLS-1$
+				throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableDataManager.not_implicit_matview", viewName)); //$NON-NLS-1$
 			}
 			return groupID;
 		} catch (QueryMetadataException e) {
@@ -401,8 +444,13 @@
 		if (!group.isTempGroupSymbol()) {
 			return null;
 		}
+		String viewName = null;
 		final String tableName = group.getNonCorrelationName().toUpperCase();
 		boolean remapColumns = !tableName.equalsIgnoreCase(group.getName());
+		TempMetadataID groupID = (TempMetadataID)group.getMetadataID();
+		if (groupID.getOriginalMetadataID() != null) {
+			viewName = context.getMetadata().getFullName(groupID.getOriginalMetadataID());
+		}		
 		TempTable table = null;
 		if (group.isGlobalTable()) {
 			final TempTableStore globalStore = context.getGlobalTableStore();
@@ -414,11 +462,13 @@
 				key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
 				
 				MatTableEntry entry = this.tables.get(key);
-				boolean firstload = !info.isValid();
+				boolean notValid = !info.isValid();
 				if (entry != null && entry.lastUpdate > info.getUpdateTime() 
-						&& info.getState() != MatState.LOADING) {
-					//remote load
-					info.setState(MatState.NEEDS_LOADING, firstload?false:entry.valid, null);
+						&& info.getState() != MatState.LOADING
+						//TODO: use extension metadata or a config parameter to make this skew configurable
+						&& !(!notValid && entry.valid && info.getState() == MatState.LOADED && entry.lastUpdate < info.getUpdateTime() + 30000)) {
+					//trigger a remote load due to the cache being more up to date than the local copy
+					info.setState(MatState.NEEDS_LOADING, notValid?false:entry.valid, null);
 					loadTime = entry.lastUpdate;
 				}
 			}
@@ -426,9 +476,9 @@
 			if (load) {
 				if (!info.isValid()) {
 					//blocking load
-					loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
+					loadGlobalTable(context, group, tableName, viewName, globalStore, info, loadTime, true);
 				} else {
-					loadAsynch(context, group, tableName, globalStore, info, loadTime);
+					loadAsynch(context, group, tableName, viewName, globalStore, info, loadTime);
 				}
 			} 
 			table = globalStore.getOrCreateTempTable(tableName, query, bufferManager, false);
@@ -461,13 +511,13 @@
 	}
 
 	private void loadAsynch(final CommandContext context,
-			final GroupSymbol group, final String tableName,
+			final GroupSymbol group, final String tableName, final String viewName,
 			final TempTableStore globalStore, final MatTableInfo info,
 			final Long loadTime) {
 		Callable<Integer> toCall = new Callable<Integer>() {
 			@Override
 			public Integer call() throws Exception {
-				return loadGlobalTable(context, group, tableName, globalStore, info, loadTime);
+				return loadGlobalTable(context, group, tableName, viewName, globalStore, info, loadTime, true);
 			}
 		};
 		FutureTask<Integer> task = new FutureTask<Integer>(toCall);
@@ -475,8 +525,8 @@
 	}
 
 	private int loadGlobalTable(CommandContext context,
-			GroupSymbol group, final String tableName,
-			TempTableStore globalStore, MatTableInfo info, Long loadTime)
+			GroupSymbol group, final String tableName, final String viewName,
+			TempTableStore globalStore, MatTableInfo info, Long loadTime, boolean useCache)
 			throws TeiidComponentException, TeiidProcessingException {
 		LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loading", tableName)); //$NON-NLS-1$
 		QueryMetadataInterface metadata = context.getMetadata();
@@ -503,16 +553,20 @@
 			}
 		}
 		int rowCount = -1;
+		boolean viewFetched = false;
 		try {
 			String fullName = metadata.getFullName(group.getMetadataID());
 			TupleSource ts = null;
 			CacheID cid = null;
 			if (distributedCache != null) {
-				cid = new CacheID(new ParseInfo(), fullName, context.getVdbName(), 
+				cid = new CacheID(new ParseInfo(), viewName, context.getVdbName(), 
 						context.getVdbVersion(), context.getConnectionID(), context.getUserName());
-				CachedResults cr = this.distributedCache.get(cid);
-				if (cr != null) {
-					ts = cr.getResults().createIndexedTupleSource();
+				if (useCache) {
+					CachedResults cr = this.distributedCache.get(cid);
+					if (cr != null) {
+						ts = cr.getResults().createIndexedTupleSource();
+						LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.cache_load", tableName)); //$NON-NLS-1$
+					}
 				}
 			}
 			
@@ -531,9 +585,10 @@
 					BatchCollector bc = qp.createBatchCollector();
 					TupleBuffer tb = bc.collectTuples();
 					cr.setResults(tb, qp.getProcessorPlan());
-					touchTable(context, fullName, true);
+					touchTable(context, fullName, true, info.getUpdateTime());
 					this.distributedCache.put(cid, Determinism.VDB_DETERMINISTIC, cr, info.getTtl());
 					ts = tb.createIndexedTupleSource();
+					viewFetched = true;
 				} else {
 					ts = new BatchCollector.BatchProducerTupleSource(qp);
 				}
@@ -565,18 +620,22 @@
 			} else {
 				globalStore.swapTempTable(tableName, table);
 				info.setState(MatState.LOADED, true, loadTime);
+				if (viewFetched & viewName != null && this.eventDistributor != null) {
+					this.eventDistributor.refreshMatView(context.getVdbName(), context.getVdbVersion(), viewName);
+				}
 				LogManager.logInfo(LogConstants.CTX_MATVIEWS, QueryPlugin.Util.getString("TempTableDataManager.loaded", tableName, rowCount)); //$NON-NLS-1$
 			}
 		}
 		return rowCount;
 	}
 
-	private void touchTable(CommandContext context, String fullName, boolean valid) {
+	private void touchTable(CommandContext context, String fullName, boolean valid, long loadtime) {
 		MatTableKey key = new MatTableKey();
 		key.name = fullName;
 		key.vdb = new VDBKey(context.getVdbName(), context.getVdbVersion());
 		MatTableEntry matTableEntry = new MatTableEntry();
 		matTableEntry.valid = valid;
+		matTableEntry.lastUpdate = loadtime;
 		tables.put(key, matTableEntry, null);
 	}
 
@@ -639,5 +698,4 @@
 	public MetadataRepository getMetadataRepository() {
 		return this.processorDataManager.getMetadataRepository();
 	}
-
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableStore.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableStore.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/tempdata/TempTableStore.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -37,6 +37,8 @@
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.language.SQLConstants;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataID;
@@ -96,6 +98,7 @@
 		
 		public synchronized MatState setState(MatState state, Boolean valid, Long timestamp) {
 			MatState oldState = this.state;
+			LogManager.logDetail(LogConstants.CTX_MATVIEWS, this, "setting matState to", state, valid, timestamp, "old values", oldState, this.valid); //$NON-NLS-1$ //$NON-NLS-2$
 			if (valid != null) {
 				this.valid = valid;
 			}
@@ -214,16 +217,10 @@
     }
     
     TempTable getOrCreateTempTable(String tempTableID, Command command, BufferManager buffer, boolean delegate) throws QueryProcessingException{
-    	TempTable tsID = groupToTupleSourceID.get(tempTableID);
-        if(tsID != null) {
-            return tsID;
-        }
-        if(delegate && this.parentTempTableStore != null){
-    		tsID = this.parentTempTableStore.groupToTupleSourceID.get(tempTableID);
-    	    if(tsID != null) {
-    	        return tsID;
-    	    }
-        }
+    	TempTable tempTable = getTempTable(tempTableID, command, buffer, delegate);
+    	if (tempTable != null) {
+    		return tempTable;
+    	}
         //allow implicit temp group definition
         List<ElementSymbol> columns = null;
         if (command instanceof Insert) {
@@ -236,11 +233,25 @@
         if (columns == null) {
         	throw new QueryProcessingException(QueryPlugin.Util.getString("TempTableStore.table_doesnt_exist_error", tempTableID)); //$NON-NLS-1$
         }
+        LogManager.logDetail(LogConstants.CTX_DQP, "Creating temporary table", tempTableID); //$NON-NLS-1$
         Create create = new Create();
         create.setTable(new GroupSymbol(tempTableID));
         create.setElementSymbolsAsColumns(columns);
         return addTempTable(tempTableID, create, buffer, true);       
     }
+
+	private TempTable getTempTable(String tempTableID, Command command,
+			BufferManager buffer, boolean delegate)
+			throws QueryProcessingException {
+		TempTable tsID = groupToTupleSourceID.get(tempTableID);
+        if(tsID != null) {
+            return tsID;
+        }
+        if(delegate && this.parentTempTableStore != null){
+    		return this.parentTempTableStore.getTempTable(tempTableID, command, buffer, delegate);
+        }
+        return null;
+	}
     
     public Set<String> getAllTempTables() {
         return new HashSet<String>(this.groupToTupleSourceID.keySet());
@@ -261,6 +272,7 @@
 					id = tempMetadataStore.addTempGroup(matTableName, ResolverUtil.resolveElementsInGroup(group, metadata), false, true);
 					id.setQueryNode(metadata.getVirtualPlan(viewId));
 					id.setCardinality(metadata.getCardinality(viewId));
+					id.setOriginalMetadataID(viewId);
 					
 					Object pk = metadata.getPrimaryKey(viewId);
 					if (pk != null) {

Modified: branches/as7/engine/src/main/java/org/teiid/query/util/CommandContext.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/util/CommandContext.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/util/CommandContext.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,6 +26,7 @@
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.LinkedList;
+import java.util.Map;
 import java.util.Properties;
 import java.util.Random;
 import java.util.Set;
@@ -33,13 +34,20 @@
 
 import javax.security.auth.Subject;
 
+import org.teiid.adminapi.DataPolicy;
+import org.teiid.adminapi.Session;
+import org.teiid.adminapi.VDB;
 import org.teiid.api.exception.query.QueryProcessingException;
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.util.ArgCheck;
+import org.teiid.dqp.internal.process.DQPWorkContext;
 import org.teiid.dqp.internal.process.PreparedPlan;
 import org.teiid.dqp.internal.process.SessionAwareCache;
 import org.teiid.dqp.internal.process.SessionAwareCache.CacheID;
+import org.teiid.dqp.message.RequestID;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
 import org.teiid.metadata.FunctionMethod.Determinism;
 import org.teiid.query.QueryPlugin;
 import org.teiid.query.eval.SecurityFunctionEvaluator;
@@ -117,6 +125,14 @@
 	    private int userRequestSourceConcurrency;
 	    private Subject subject;
 	    private HashSet<Object> dataObjects;
+
+		private Session session;
+
+		private RequestID requestId;
+		
+		private DQPWorkContext dqpWorkContext;
+		private TransactionContext transactionContext;
+		private TransactionService transactionService;
 	}
 	
 	private GlobalState globalState = new GlobalState();
@@ -422,13 +438,12 @@
 	}
 	
 	public Set<String> getGroups() {
+		if (globalState.groups == null) {
+			globalState.groups = new HashSet<String>();
+		}
 		return globalState.groups;
 	}
 	
-	public void setGroups(Set<String> groups) {
-		this.globalState.groups = groups;
-	}
-	
 	public long getTimeSliceEnd() {
 		return globalState.timeSliceEnd;
 	}
@@ -567,4 +582,56 @@
 		this.dataObjects = dataObjectsAccessed;
 	}
 	
+	@Override
+	public Session getSession() {
+		return this.globalState.session;
+	}
+	
+	public void setSession(Session session) {
+		this.globalState.session = session;
+	}
+	
+	@Override
+	public String getRequestId() {
+		return this.globalState.requestId != null ? this.globalState.requestId.toString() : null;
+	}
+	
+	public void setRequestId(RequestID requestId) {
+		this.globalState.requestId = requestId;
+	}
+	
+	public void setDQPWorkContext(DQPWorkContext workContext) {
+		this.globalState.dqpWorkContext = workContext;
+	}
+	
+	@Override
+	public Map<String, DataPolicy> getAllowedDataPolicies() {
+		return this.globalState.dqpWorkContext.getAllowedDataPolicies();
+	}
+	
+	@Override
+	public VDB getVdb() {
+		return this.globalState.dqpWorkContext.getVDB();
+	}
+	
+	public DQPWorkContext getDQPWorkContext() {
+		return this.globalState.dqpWorkContext;
+	}
+	
+	public TransactionContext getTransactionContext() {
+		return globalState.transactionContext;
+	}
+	
+	public void setTransactionContext(TransactionContext transactionContext) {
+		globalState.transactionContext = transactionContext;
+	}
+	
+	public TransactionService getTransactionServer() {
+		return globalState.transactionService;
+	}
+	
+	public void setTransactionService(TransactionService transactionService) {
+		globalState.transactionService = transactionService;
+	}
+	
 }

Modified: branches/as7/engine/src/main/java/org/teiid/query/validator/AbstractValidationVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/validator/AbstractValidationVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/validator/AbstractValidationVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,6 +26,7 @@
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
+import java.util.Stack;
 
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.core.TeiidComponentException;
@@ -50,6 +51,7 @@
     private QueryMetadataInterface metadata;
     
     protected Command currentCommand;
+    protected Stack<LanguageObject> stack = new Stack<LanguageObject>();
     
     public AbstractValidationVisitor() {
         this.report = new ValidatorReport();
@@ -69,6 +71,7 @@
      */
     public void reset() {
         this.currentCommand = null;
+        this.stack.clear();
     }
     
     // ######################### Store results info #########################

Deleted: branches/as7/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/validator/AggregateValidationVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,157 +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 org.teiid.query.validator;
-
-import java.util.Collection;
-import java.util.Set;
-
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.QueryPlugin;
-import org.teiid.query.sql.LanguageObject;
-import org.teiid.query.sql.navigator.PreOrderNavigator;
-import org.teiid.query.sql.symbol.AggregateSymbol;
-import org.teiid.query.sql.symbol.CaseExpression;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.ExpressionSymbol;
-import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
-import org.teiid.query.sql.symbol.AggregateSymbol.Type;
-import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-
-/** 
- * Validate that all ElementSymbol and ExpressionSymbols used in the HAVING 
- * and SELECT clauses are based on symbols used in the GROUP BY clause.
- * @since 4.2
- */
-public class AggregateValidationVisitor extends AbstractValidationVisitor {
-    
-    private boolean validateBelow = true;
-
-    // Symbols from GROUP BY - may be null if no group symbols
-    private Set<Expression> groupExpressions;
-    
-    public AggregateValidationVisitor(Set<Expression> groupExpressions) {
-        this.groupExpressions = groupExpressions;
-    }
-    
-    public void visit(AggregateSymbol obj) {
-        Expression aggExp = obj.getExpression();
-
-        // Check for any nested aggregates (which are not allowed)
-        if(aggExp != null) {
-            Collection<AggregateSymbol> nestedAggs = AggregateSymbolCollectorVisitor.getAggregates(aggExp, true);
-            if(nestedAggs.size() > 0) {
-                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0039", nestedAggs), nestedAggs); //$NON-NLS-1$
-            }
-        }
-        
-        // Verify data type of aggregate expression
-        Type aggregateFunction = obj.getAggregateFunction();
-        if((aggregateFunction == Type.SUM || aggregateFunction == Type.AVG) && obj.getType() == null) {
-            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0041", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
-        } else if (obj.getType() != DataTypeManager.DefaultDataClasses.NULL) {
-        	if (aggregateFunction == Type.XMLAGG && aggExp.getType() != DataTypeManager.DefaultDataClasses.XML) {
-        		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_xml", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
-        	} else if (obj.isBoolean() && aggExp.getType() != DataTypeManager.DefaultDataClasses.BOOLEAN) {
-        		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_boolean", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
-        	}
-        }
-        if((obj.isDistinct() || aggregateFunction == Type.MIN || aggregateFunction == Type.MAX) && DataTypeManager.isNonComparable(DataTypeManager.getDataTypeName(aggExp.getType()))) {
-    		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_comparable", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
-        }
-        if(obj.isEnhancedNumeric()) {
-        	if (!Number.class.isAssignableFrom(aggExp.getType())) {
-        		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0041", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
-        	}
-        	if (obj.isDistinct()) {
-        		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.invalid_distinct", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
-        	}
-        }
-        validateBelow = false;
-    }
-    
-    public void visit(ElementSymbol obj) {
-        validateExpression(obj);
-    }
-    
-    public void visit(ExpressionSymbol obj) {
-        validateExpression(obj);
-    }
-    
-    public void visit(CaseExpression obj) {
-        validateExpression(obj);
-    }
-    
-    public void visit(SearchedCaseExpression obj) {
-        validateExpression(obj);
-    }
-    
-    public void visit(Function obj) {
-        validateExpression(obj);
-    }
-    
-    private void validateExpression(Expression symbol) {
-        if (ElementCollectorVisitor.getElements(symbol, false).isEmpty()) {
-            validateBelow = false;
-            return;
-        }
-        
-        if(groupExpressions == null) {
-            if (symbol instanceof ElementSymbol && !((ElementSymbol)symbol).isExternalReference()) {
-                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0037", symbol), symbol); //$NON-NLS-1$
-            }
-        } else if(! groupExpressions.contains(symbol)) {
-            if (symbol instanceof ElementSymbol && !((ElementSymbol)symbol).isExternalReference()) {
-                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0038", symbol), symbol); //$NON-NLS-1$
-            }
-        } else {
-            validateBelow = false;
-        }
-    }
-    
-    public static void validate(LanguageObject obj, final AggregateValidationVisitor visitor) {
-    	visitor.validateBelow = true;
-        PreOrderNavigator nav = new PreOrderNavigator(visitor) {
-            private boolean validateBelow;
-
-            protected void visitNode(LanguageObject obj) {
-                if (validateBelow) {
-                    super.visitNode(obj);
-                }
-            }
-            
-            protected void preVisitVisitor(LanguageObject obj) {
-                super.preVisitVisitor(obj);
-                this.validateBelow = visitor.validateBelow;
-            }
-            
-            protected void postVisitVisitor(LanguageObject obj) {
-                this.validateBelow = true;
-            }
-        };
-        obj.acceptVisitor(nav);
-    }
-    
-}

Modified: branches/as7/engine/src/main/java/org/teiid/query/validator/UpdateValidator.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/validator/UpdateValidator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/validator/UpdateValidator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -404,7 +404,7 @@
             	String groupName = es.getGroupSymbol().getCanonicalName();
         		UpdateMapping info = updateInfo.updatableGroups.get(groupName);
         		if (es.getGroupSymbol().getDefinition() != null) {
-            		ElementSymbol clone = (ElementSymbol)es.clone();
+            		ElementSymbol clone = es.clone();
             		clone.setOutputName(null);
             		clone.getGroupSymbol().setName(clone.getGroupSymbol().getNonCorrelationName());
             		clone.getGroupSymbol().setDefinition(null);

Modified: branches/as7/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/validator/ValidationVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,6 +27,7 @@
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Iterator;
+import java.util.LinkedHashSet;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
@@ -102,6 +103,8 @@
 import org.teiid.query.sql.lang.XMLTable.XMLColumn;
 import org.teiid.query.sql.navigator.PreOrderNavigator;
 import org.teiid.query.sql.proc.AssignmentStatement;
+import org.teiid.query.sql.proc.Block;
+import org.teiid.query.sql.proc.BranchingStatement;
 import org.teiid.query.sql.proc.CommandStatement;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.proc.CriteriaSelector;
@@ -109,12 +112,14 @@
 import org.teiid.query.sql.proc.HasCriteria;
 import org.teiid.query.sql.proc.LoopStatement;
 import org.teiid.query.sql.proc.TranslateCriteria;
+import org.teiid.query.sql.proc.WhileStatement;
+import org.teiid.query.sql.proc.BranchingStatement.BranchingMode;
+import org.teiid.query.sql.proc.Statement.Labeled;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.DerivedColumn;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.QueryString;
@@ -122,6 +127,7 @@
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.WindowFunction;
 import org.teiid.query.sql.symbol.XMLAttributes;
 import org.teiid.query.sql.symbol.XMLElement;
 import org.teiid.query.sql.symbol.XMLForest;
@@ -129,7 +135,6 @@
 import org.teiid.query.sql.symbol.XMLParse;
 import org.teiid.query.sql.symbol.XMLQuery;
 import org.teiid.query.sql.symbol.AggregateSymbol.Type;
-import org.teiid.query.sql.util.SymbolMap;
 import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
 import org.teiid.query.sql.visitor.EvaluatableVisitor;
@@ -165,6 +170,8 @@
 	// State during validation
     private boolean isXML = false;	// only used for Query commands
     
+    private boolean inQuery;
+    
     // update procedure being validated
     private CreateUpdateProcedureCommand updateProc;
     
@@ -175,6 +182,7 @@
     public void reset() {
         super.reset();
         this.isXML = false;
+        this.inQuery = false;
     }
 
     // ############### Visitor methods for language objects ##################
@@ -208,18 +216,12 @@
 
     public void visit(GroupBy obj) {
     	// Get list of all group by IDs
-        List groupBySymbols = obj.getSymbols();
+        List<Expression> groupBySymbols = obj.getSymbols();
         validateSortable(groupBySymbols);
-		Iterator symbolIter = groupBySymbols.iterator();
-		while(symbolIter.hasNext()) {
-            SingleElementSymbol symbol = (SingleElementSymbol)symbolIter.next();
-            if(symbol instanceof ExpressionSymbol) {
-                ExpressionSymbol exprSymbol = (ExpressionSymbol) symbol;
-                Expression expr = exprSymbol.getExpression();
-                if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(expr).isEmpty() || expr instanceof Constant || expr instanceof Reference) {
-                	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.groupby_subquery", expr), expr); //$NON-NLS-1$
-                }
-            }                
+        for (Expression expr : groupBySymbols) {
+            if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(expr).isEmpty() || expr instanceof Constant || expr instanceof Reference) {
+            	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.groupby_subquery", expr), expr); //$NON-NLS-1$
+            }
 		}
     }
     
@@ -271,6 +273,7 @@
         	this.isXML = true;
 	        validateXMLQuery(obj);
         } else {
+        	this.inQuery = true;
             validateAggregates(obj);
 
             //if it is select with no from, should not have ScalarSubQuery
@@ -666,15 +669,13 @@
      * and ORDER BY.
      * @param symbols List of SingleElementSymbol
      */
-    protected void validateSortable(List symbols) {
-        Iterator iter = symbols.iterator();
-        while(iter.hasNext()) {
-            SingleElementSymbol symbol = (SingleElementSymbol) iter.next();
-            validateSortable(symbol);
+    protected void validateSortable(List<? extends Expression> symbols) {
+    	for (Expression expression : symbols) {
+            validateSortable(expression);
         }
     }
 
-	private void validateSortable(SingleElementSymbol symbol) {
+	private void validateSortable(Expression symbol) {
 		if (isNonComparable(symbol)) {
 		    handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0026", symbol), symbol); //$NON-NLS-1$
 		}
@@ -759,48 +760,60 @@
         Select select = query.getSelect();
         GroupBy groupBy = query.getGroupBy();
         Criteria having = query.getHaving();
-        if(groupBy != null || having != null || !AggregateSymbolCollectorVisitor.getAggregates(select, false).isEmpty()) {
-            Set<Expression> groupSymbols = null;
-            if(groupBy != null) {
-                groupSymbols = new HashSet<Expression>();
-                for (final Iterator iterator = groupBy.getSymbols().iterator(); iterator.hasNext();) {
-                    final SingleElementSymbol element = (SingleElementSymbol)iterator.next();
-                    groupSymbols.add(SymbolMap.getExpression(element));
-                }
-            }
-            
-            // Validate HAVING, if it exists
-            AggregateValidationVisitor visitor = new AggregateValidationVisitor(groupSymbols);
-            if(having != null) {
-                AggregateValidationVisitor.validate(having, visitor);
-            }
-            
-            // Validate SELECT
-            List<SingleElementSymbol> projectedSymbols = select.getProjectedSymbols();
-            for (SingleElementSymbol symbol : projectedSymbols) {
-                AggregateValidationVisitor.validate(symbol, visitor);                                            
-            }
-            
-            // Move items to this report
-            ValidatorReport report = visitor.getReport();
-            Collection items = report.getItems();
-            super.getReport().addItems(items);        
+        validateNoAggsInClause(groupBy);
+        validateNoAggsInClause(query.getCriteria());
+        if (query.getFrom() == null) {
+        	validateNoAggsInClause(select);
+        	validateNoAggsInClause(query.getOrderBy());
+        } else {
+        	validateNoAggsInClause(query.getFrom());
         }
+        
+        Set<Expression> groupSymbols = null;
+        boolean hasAgg = false;
+        if (groupBy != null) {
+            groupSymbols = new HashSet<Expression>(groupBy.getSymbols());
+            hasAgg = true;
+        }
+        LinkedHashSet<Expression> invalid = new LinkedHashSet<Expression>();
+        LinkedHashSet<Expression> invalidWindowFunctions = new LinkedHashSet<Expression>();
+        LinkedList<AggregateSymbol> aggs = new LinkedList<AggregateSymbol>();
+        if (having != null) {
+        	AggregateSymbolCollectorVisitor.getAggregates(having, aggs, invalid, null, invalidWindowFunctions, groupSymbols);
+        	hasAgg = true;
+        }
+        for (SingleElementSymbol symbol : select.getProjectedSymbols()) {
+        	AggregateSymbolCollectorVisitor.getAggregates(symbol, aggs, invalid, null, null, groupSymbols);                                            
+        }
+        if ((!aggs.isEmpty() || hasAgg) && !invalid.isEmpty()) {
+    		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0037", invalid), invalid); //$NON-NLS-1$
+        }
+        if (!invalidWindowFunctions.isEmpty()) {
+        	handleValidationError(QueryPlugin.Util.getString("SQLParser.window_only_top_level", invalidWindowFunctions), invalidWindowFunctions); //$NON-NLS-1$
+        }
     }
+
+	private void validateNoAggsInClause(LanguageObject clause) {
+		if (clause == null) {
+        	return;
+        }
+		LinkedHashSet<Expression> aggs = new LinkedHashSet<Expression>();
+		AggregateSymbolCollectorVisitor.getAggregates(clause, aggs, null, null, aggs, null);
+		if (!aggs.isEmpty()) {
+			handleValidationError(QueryPlugin.Util.getString("SQLParser.Aggregate_only_top_level", aggs), aggs); //$NON-NLS-1$
+		}
+	}
     
     protected void validateInsert(Insert obj) {
-        Collection vars = obj.getVariables();
-        Iterator varIter = vars.iterator();
+        Collection<ElementSymbol> vars = obj.getVariables();
+        Iterator<ElementSymbol> varIter = vars.iterator();
         Collection values = obj.getValues();
         Iterator valIter = values.iterator();
         GroupSymbol insertGroup = obj.getGroup();
 
-
         try {
             // Validate that all elements in variable list are updatable
-            Iterator elementIter = vars.iterator();
-            while(elementIter.hasNext()) {
-                ElementSymbol insertElem = (ElementSymbol) elementIter.next();
+        	for (ElementSymbol insertElem : vars) {
                 if(! getMetadata().elementSupports(insertElem.getMetadataID(), SupportConstants.Element.UPDATE)) {
                     handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0052", insertElem), insertElem); //$NON-NLS-1$
                 }
@@ -825,7 +838,7 @@
             // if any of the value present in the insert are null
             while(valIter.hasNext() && varIter.hasNext()) {
                 Expression nextValue = (Expression) valIter.next();
-                ElementSymbol nextVar = (ElementSymbol) varIter.next();
+                ElementSymbol nextVar = varIter.next();
 
                 if (!(nextValue instanceof Constant) && getMetadata().isMultiSourceElement(nextVar.getMetadataID())) {
                 	handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.multisource_constant", nextVar), nextVar); //$NON-NLS-1$
@@ -1203,7 +1216,70 @@
     }
     
     @Override
+    public void visit(WindowFunction windowFunction) {
+    	AggregateSymbol.Type type = windowFunction.getFunction().getAggregateFunction();
+    	switch (type) {
+    	case RANK:
+    	case DENSE_RANK:
+    	case ROW_NUMBER:
+    		if (windowFunction.getWindowSpecification().getOrderBy() == null) {
+    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.ranking_requires_order_by", windowFunction), windowFunction); //$NON-NLS-1$
+    		}
+    		break;
+    	case TEXTAGG:
+    	case ARRAY_AGG:
+    		if (windowFunction.getWindowSpecification().getOrderBy() != null) {
+    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.window_order_by", windowFunction), windowFunction); //$NON-NLS-1$
+            }
+    		break;
+    	}
+    	validateNoSubqueriesOrOuterReferences(windowFunction);
+        if (windowFunction.getFunction().getOrderBy() != null || windowFunction.getFunction().isDistinct()) {
+        	handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0042", new Object[] {windowFunction.getFunction(), windowFunction}), windowFunction); //$NON-NLS-1$
+        }
+        if (windowFunction.getWindowSpecification().getPartition() != null) {
+        	validateSortable(windowFunction.getWindowSpecification().getPartition());
+        }
+    }
+    
+    @Override
     public void visit(AggregateSymbol obj) {
+    	if (!inQuery) {
+    		handleValidationError(QueryPlugin.Util.getString("SQLParser.Aggregate_only_top_level", obj), obj); //$NON-NLS-1$
+    		return;
+    	}
+    	if (obj.getCondition() != null) {
+    		Expression condition = obj.getCondition();
+    		validateNoSubqueriesOrOuterReferences(condition);
+    	}
+        Expression aggExp = obj.getExpression();
+
+        validateNoNestedAggs(aggExp);
+        validateNoNestedAggs(obj.getOrderBy());
+        validateNoNestedAggs(obj.getCondition());
+        
+        // Verify data type of aggregate expression
+        Type aggregateFunction = obj.getAggregateFunction();
+        if((aggregateFunction == Type.SUM || aggregateFunction == Type.AVG) && obj.getType() == null) {
+            handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0041", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
+        } else if (obj.getType() != DataTypeManager.DefaultDataClasses.NULL) {
+        	if (aggregateFunction == Type.XMLAGG && aggExp.getType() != DataTypeManager.DefaultDataClasses.XML) {
+        		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_xml", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
+        	} else if (obj.isBoolean() && aggExp.getType() != DataTypeManager.DefaultDataClasses.BOOLEAN) {
+        		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_boolean", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
+        	}
+        }
+        if((obj.isDistinct() || aggregateFunction == Type.MIN || aggregateFunction == Type.MAX) && DataTypeManager.isNonComparable(DataTypeManager.getDataTypeName(aggExp.getType()))) {
+    		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.non_comparable", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
+        }
+        if(obj.isEnhancedNumeric()) {
+        	if (!Number.class.isAssignableFrom(aggExp.getType())) {
+        		handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0041", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
+        	}
+        	if (obj.isDistinct()) {
+        		handleValidationError(QueryPlugin.Util.getString("AggregateValidationVisitor.invalid_distinct", new Object[] {aggregateFunction, obj}), obj); //$NON-NLS-1$
+        	}
+        }
     	if (obj.getAggregateFunction() != Type.TEXTAGG) {
     		return;
     	}
@@ -1223,7 +1299,29 @@
     		}
     	}
     }
+
+	private void validateNoSubqueriesOrOuterReferences(Expression expr) {
+		if (!ValueIteratorProviderCollectorVisitor.getValueIteratorProviders(expr).isEmpty()) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.filter_subquery", expr), expr); //$NON-NLS-1$
+		}
+		for (ElementSymbol es : ElementCollectorVisitor.getElements(expr, false)) {
+			if (es.isExternalReference()) {
+				handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.filter_subquery", es), es); //$NON-NLS-1$
+			}
+		}
+	}
     
+	private void validateNoNestedAggs(LanguageObject aggExp) {
+		// Check for any nested aggregates (which are not allowed)
+        if(aggExp != null) {
+        	HashSet<Expression> nestedAggs = new LinkedHashSet<Expression>();
+            AggregateSymbolCollectorVisitor.getAggregates(aggExp, nestedAggs, null, null, nestedAggs, null);
+            if(!nestedAggs.isEmpty()) {
+                handleValidationError(QueryPlugin.Util.getString("ERR.015.012.0039", nestedAggs), nestedAggs); //$NON-NLS-1$
+            }
+        }
+	}
+    
 	private String[] validateQName(LanguageObject obj, String name) {
 		try {
 			return Name11Checker.getInstance().getQNameParts(name);
@@ -1376,6 +1474,9 @@
         	if (obj.getHeader() != null && obj.getHeader() < 0) {
 	    		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.text_table_negative"), obj); //$NON-NLS-1$
 	    	}
+        	if (!obj.isUsingRowDelimiter()) {
+        		handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.fixed_option"), obj); //$NON-NLS-1$
+        	}
     		delimiter = obj.getDelimiter();
     		quote = obj.getQuote();
 			validateTextOptions(obj, delimiter, quote);
@@ -1465,7 +1566,47 @@
 		}
     }
     
+    public void visit(Block obj) {
+    	if (obj.getLabel() == null) {
+    		return;
+    	}
+		for (LanguageObject lo : stack) {
+			if (lo instanceof Labeled) {
+				Labeled labeled = (Labeled)lo;
+	    		if (obj.getLabel().equalsIgnoreCase(labeled.getLabel())) {
+	    			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.duplicate_block_label", obj.getLabel()), obj); //$NON-NLS-1$
+	    		}
+			}
+		}
+    }
+    
     @Override
+    public void visit(BranchingStatement obj) {
+		boolean matchedLabel = false;
+		boolean inLoop = false;
+		for (LanguageObject lo : stack) {
+			if (lo instanceof LoopStatement || lo instanceof WhileStatement) {
+				inLoop = true;
+				if (obj.getLabel() == null) {
+					break;
+				}
+				matchedLabel |= obj.getLabel().equalsIgnoreCase(((Labeled)lo).getLabel());
+			} else if (obj.getLabel() != null && lo instanceof Block && obj.getLabel().equalsIgnoreCase(((Block)lo).getLabel())) {
+				matchedLabel = true;
+				if (obj.getMode() != BranchingMode.LEAVE) {
+					handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.invalid_label", obj.getLabel()), obj); //$NON-NLS-1$
+				}
+			}
+		}
+		if (obj.getMode() != BranchingMode.LEAVE && !inLoop) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.no_loop"), obj); //$NON-NLS-1$
+		}
+		if (obj.getLabel() != null && !matchedLabel) {
+			handleValidationError(QueryPlugin.Util.getString("ValidationVisitor.unknown_block_label", obj.getLabel()), obj); //$NON-NLS-1$
+		}
+    }
+    
+    @Override
     public void visit(AlterTrigger obj) {
     	validateGroupSupportsUpdate(obj.getTarget());
 		try {

Modified: branches/as7/engine/src/main/java/org/teiid/query/validator/Validator.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/validator/Validator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/validator/Validator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -72,7 +72,7 @@
         setTempMetadata(metadata, visitor, object);
         
         PreOrderNavigator nav = new PreOrderNavigator(visitor) {
-            
+        	
         	protected void visitNode(LanguageObject obj) {
         		QueryMetadataInterface previous = visitor.getMetadata();
         		setTempMetadata(metadata, visitor, obj);
@@ -80,6 +80,17 @@
         		visitor.setMetadata(previous);
         	}
         	
+        	@Override
+        	protected void preVisitVisitor(LanguageObject obj) {
+        		super.preVisitVisitor(obj);
+        		visitor.stack.add(obj);
+        	}
+        	
+        	@Override
+        	protected void postVisitVisitor(LanguageObject obj) {
+        		visitor.stack.pop();
+        	}
+        	
         };
         object.acceptVisitor(nav);        	
         

Copied: branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/DocumentWrapper.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/xquery/saxon/DocumentWrapper.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/DocumentWrapper.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/DocumentWrapper.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,279 @@
+package org.teiid.query.xquery.saxon;
+
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+
+import net.sf.saxon.Configuration;
+import net.sf.saxon.om.DocumentInfo;
+import net.sf.saxon.om.NamePool;
+import net.sf.saxon.om.NodeInfo;
+import net.sf.saxon.type.Type;
+import nu.xom.Attribute;
+import nu.xom.Document;
+import nu.xom.Element;
+import nu.xom.Node;
+
+/**
+ * The root node of an XPath tree. (Or equivalently, the tree itself).
+ * <P>
+ * This class is used not only for a document, but also for the root
+ * of a document-less tree fragment.
+ * 
+ * @author Michael H. Kay
+ * @author Wolfgang Hoschek (ported net.sf.saxon.jdom to XOM)
+ * @author Steve Hawkins (Ported to Saxon 9.1 for Teiid)
+ */
+
+public class DocumentWrapper extends NodeWrapper implements DocumentInfo {
+
+	protected Configuration config;
+
+	protected String baseURI;
+
+	protected int documentNumber;
+
+    private HashMap idIndex;
+
+	/**
+	 * Create a Saxon wrapper for a XOM root node
+	 * 
+	 * @param root
+	 *            The XOM root node
+	 * @param baseURI
+	 *            The base URI for all the nodes in the tree
+	 * @param config
+	 *            The configuration which defines the name pool used for all
+	 *            names in this tree
+	 */
+	public DocumentWrapper(Node root, String baseURI, Configuration config) {
+		super(root, null, 0);
+		if (root.getParent() != null) 
+			throw new IllegalArgumentException("root node must not have a parent node");
+		this.baseURI = baseURI;
+		this.docWrapper = this;
+		setConfiguration(config);
+	}
+	
+	/**
+	 * Wrap a node in the XOM document.
+	 * 
+	 * @param node
+	 *            The node to be wrapped. This must be a node in the same
+	 *            document (the system does not check for this).
+	 * @return the wrapping NodeInfo object
+	 */
+
+	public NodeInfo wrap(Node node) {
+		if (node == this.node) {
+            return this;
+        }
+		return makeWrapper(node, this);
+	}
+
+	/**
+	 * Set the configuration, which defines the name pool used for all names in
+	 * this document. This is always called after a new document has been
+	 * created. The implementation must register the name pool with the
+	 * document, so that it can be retrieved using getNamePool(). It must also
+	 * call NamePool.allocateDocumentNumber(), and return the relevant document
+	 * number when getDocumentNumber() is subsequently called.
+	 * 
+	 * @param config
+	 *            The configuration to be used
+	 */
+
+	public void setConfiguration(Configuration config) {
+		this.config = config;
+		this.documentNumber = allocateDocumentNumber(config);
+	}
+	
+    /**
+	 * Get the configuration previously set using setConfiguration
+	 */
+
+	public Configuration getConfiguration() {
+		return config;
+	}
+
+	/**
+	 * Get the name pool used for the names in this document
+	 * 
+	 * @return the name pool in which all the names used in this document are
+	 *         registered
+	 */
+
+	public NamePool getNamePool() {
+		return config.getNamePool();
+	}
+
+	/**
+	 * Get the unique document number for this document (the number is unique
+	 * for all documents within a NamePool)
+	 * 
+	 * @return the unique number identifying this document within the name pool
+	 */
+
+	public long getDocumentNumber() {
+		return documentNumber;
+	}
+
+    /**
+	 * Get the element with a given ID, if any
+	 * 
+	 * @param id
+	 *            the required ID value
+	 * @param getParent
+	 *            true if running the element-with-id() function rather than the id()
+	 *            function; the difference is that in the case of an element of type xs:ID,
+	 *            the parent of the element should be returned, not the element itself.
+	 * @return the element with the given ID, or null if there is no such ID
+	 *         present (or if the parser has not notified attributes as being of
+	 *         type ID).
+	 */
+
+	public NodeInfo selectID(String id, boolean getParent) {
+		if (idIndex == null) {
+			Element elem;
+			switch (nodeKind) {
+				case Type.DOCUMENT : 
+					elem = ((Document) node).getRootElement();
+					break;
+				case Type.ELEMENT : 
+					elem = (Element) node;
+					break;
+				default: 
+					return null;
+			}
+			idIndex = new HashMap(50);
+			buildIDIndex(elem);
+		}
+
+		NodeInfo result = (NodeInfo) idIndex.get(id);
+
+		if (result != null && getParent && result.isId() && result.getStringValue().equals(id)) {
+            result = result.getParent();
+        }
+
+		return result ;
+	}
+	
+	
+	private void buildIDIndex(Element elem) {
+		// walk the tree in reverse document order, to satisfy the XPath 1.0 rule
+		// that says if an ID appears twice, the first one wins
+		for (int i=elem.getChildCount(); --i >= 0 ; ) {
+			Node child = elem.getChild(i);
+			if (child instanceof Element) {
+				buildIDIndex((Element)child);
+			}
+		}
+		for (int i=elem.getAttributeCount(); --i >= 0 ; ) {
+			Attribute att = elem.getAttribute(i);
+			if (att.getType() == Attribute.Type.ID) {
+				idIndex.put(att.getValue(), wrap(elem));
+			}
+		}
+	}
+
+    /**
+	 * Get the unparsed entity with a given name
+	 * 
+	 * @param name
+	 *            the name of the entity
+	 * @return null: XOM does not provide access to unparsed entities
+	 * @return if the entity exists, return an array of two Strings, the first
+	 *         holding the system ID of the entity, the second holding the
+	 *         public ID if there is one, or null if not. If the entity does not
+	 *         exist, return null.
+	 */
+
+	public String[] getUnparsedEntity(String name) {
+		return null;
+	}
+
+	private static final Method saxon85Method = findAllocateDocumentNumberMethod85();
+
+	// work-around for incompatibility introduced in saxon-8.5.1
+	private int allocateDocumentNumber(Configuration config) {
+		if (saxon85Method == null) {
+			try { // saxon >= 8.5.1
+				return allocateDocumentNumber851(config);
+			} catch (Throwable t) {
+				throw new RuntimeException(t);
+			}
+		}
+		
+		// saxon < 8.5.1
+		try { 
+			// return config.getNamePool().allocateDocumentNumber(this);
+			Object result = saxon85Method.invoke(config.getNamePool(), new Object[] {this});
+			return ((Integer) result).intValue();
+		} catch (Throwable t) {
+			throw new RuntimeException(t);
+		}
+		
+	}
+
+	// saxon >= 8.5.1
+	private int allocateDocumentNumber851(Configuration config) {
+		return config.getDocumentNumberAllocator().allocateDocumentNumber();
+	}
+	
+	private static Method findAllocateDocumentNumberMethod85() {
+		try {
+			return NamePool.class.getMethod("allocateDocumentNumber", new Class[] {NodeInfo.class});
+		} catch (Throwable t) {
+			return null;
+		}
+	}
+
+	@Override
+	public Iterator getUnparsedEntityNames() {
+		return Collections.EMPTY_LIST.iterator();
+	}
+
+	@Override
+	public int getColumnNumber() {
+		return -1;
+	}
+
+	@Override
+	public boolean isId() {
+		return false;
+	}
+
+	@Override
+	public boolean isIdref() {
+		return false;
+	}
+
+	@Override
+	public boolean isNilled() {
+		return false;
+	}
+
+}
+
+//
+// The contents of this file are subject to the Mozilla Public License Version
+// 1.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the
+// License at http://www.mozilla.org/MPL/
+//
+// Software distributed under the License is distributed on an "AS IS" basis,
+// WITHOUT WARRANTY OF ANY KIND, either express or implied.
+// See the License for the specific language governing rights and limitations
+// under the License.
+//
+// The Original Code is: all this file.
+//
+// The Initial Developer of the Original Code is Michael Kay
+//
+// Portions created by (your name) are Copyright (C) (your legal entity). All
+// Rights Reserved.
+//
+// Contributor(s): none.
+//

Copied: branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/NodeWrapper.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/xquery/saxon/NodeWrapper.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/NodeWrapper.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/NodeWrapper.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,1395 @@
+package org.teiid.query.xquery.saxon;
+
+import net.sf.saxon.Configuration;
+import net.sf.saxon.event.Receiver;
+import net.sf.saxon.om.Axis;
+import net.sf.saxon.om.AxisIterator;
+import net.sf.saxon.om.AxisIteratorImpl;
+import net.sf.saxon.om.DocumentInfo;
+import net.sf.saxon.om.EmptyIterator;
+import net.sf.saxon.om.FastStringBuffer;
+import net.sf.saxon.om.Item;
+import net.sf.saxon.om.NamePool;
+import net.sf.saxon.om.NamespaceIterator;
+import net.sf.saxon.om.Navigator;
+import net.sf.saxon.om.NodeInfo;
+import net.sf.saxon.om.SequenceIterator;
+import net.sf.saxon.om.SiblingCountingNode;
+import net.sf.saxon.om.SingleNodeIterator;
+import net.sf.saxon.om.SingletonIterator;
+import net.sf.saxon.om.StandardNames;
+import net.sf.saxon.om.VirtualNode;
+import net.sf.saxon.pattern.AnyNodeTest;
+import net.sf.saxon.pattern.NameTest;
+import net.sf.saxon.pattern.NodeKindTest;
+import net.sf.saxon.pattern.NodeTest;
+import net.sf.saxon.trans.XPathException;
+import net.sf.saxon.type.Type;
+import net.sf.saxon.value.AtomicValue;
+import net.sf.saxon.value.StringValue;
+import net.sf.saxon.value.UntypedAtomicValue;
+import net.sf.saxon.value.Value;
+import nu.xom.Attribute;
+import nu.xom.Comment;
+import nu.xom.DocType;
+import nu.xom.Document;
+import nu.xom.Element;
+import nu.xom.Node;
+import nu.xom.ParentNode;
+import nu.xom.ProcessingInstruction;
+import nu.xom.Text;
+
+/**
+ * A node in the XML parse tree representing an XML element, character content,
+ * or attribute.
+ * <P>
+ * This is the implementation of the NodeInfo interface used as a wrapper for
+ * XOM nodes.
+ *
+ * @author Michael H. Kay
+ * @author Wolfgang Hoschek (ported net.sf.saxon.jdom to XOM)
+ * @author Steve Hawkins (Ported to Saxon 9.1 for Teiid and fixed a bug with the buffer usage in getDeclaredNamespaces)
+ */
+
+public class NodeWrapper implements NodeInfo, VirtualNode, SiblingCountingNode {
+
+	protected Node node;
+
+	protected short nodeKind;
+
+	private NodeWrapper parent; // null means unknown
+
+	protected DocumentWrapper docWrapper;
+
+	protected int index; // -1 means unknown
+
+	/**
+	 * This constructor is protected: nodes should be created using the wrap
+	 * factory method on the DocumentWrapper class
+	 *
+	 * @param node
+	 *            The XOM node to be wrapped
+	 * @param parent
+	 *            The NodeWrapper that wraps the parent of this node
+	 * @param index
+	 *            Position of this node among its siblings
+	 */
+	protected NodeWrapper(Node node, NodeWrapper parent, int index) {
+		short kind;
+		if (node instanceof Element) {
+			kind = Type.ELEMENT;
+		} else if (node instanceof Text) {
+			kind = Type.TEXT;
+		} else if (node instanceof Attribute) {
+			kind = Type.ATTRIBUTE;
+		} else if (node instanceof Comment) {
+			kind = Type.COMMENT;
+		} else if (node instanceof ProcessingInstruction) {
+			kind = Type.PROCESSING_INSTRUCTION;
+		} else if (node instanceof Document) {
+			kind = Type.DOCUMENT;
+		} else {
+			throwIllegalNode(node); // moved out of fast path to enable better inlining
+			return; // keep compiler happy
+		}
+		this.nodeKind = kind;
+		this.node = node;
+		this.parent = parent;
+		this.index = index;
+	}
+
+	/**
+	 * Factory method to wrap a XOM node with a wrapper that implements the
+	 * Saxon NodeInfo interface.
+	 *
+	 * @param node
+	 *            The XOM node
+	 * @param docWrapper
+	 *            The wrapper for the Document containing this node
+	 * @return The new wrapper for the supplied node
+	 */
+	protected final NodeWrapper makeWrapper(Node node, DocumentWrapper docWrapper) {
+		return makeWrapper(node, docWrapper, null, -1);
+	}
+
+	/**
+	 * Factory method to wrap a XOM node with a wrapper that implements the
+	 * Saxon NodeInfo interface.
+	 *
+	 * @param node
+	 *            The XOM node
+	 * @param docWrapper
+	 *            The wrapper for the Document containing this node
+	 * @param parent
+	 *            The wrapper for the parent of the XOM node
+	 * @param index
+	 *            The position of this node relative to its siblings
+	 * @return The new wrapper for the supplied node
+	 */
+
+	protected final NodeWrapper makeWrapper(Node node, DocumentWrapper docWrapper,
+			NodeWrapper parent, int index) {
+
+		if (node == docWrapper.node) return docWrapper;
+		NodeWrapper wrapper = new NodeWrapper(node, parent, index);
+		wrapper.docWrapper = docWrapper;
+		return wrapper;
+	}
+
+	private static void throwIllegalNode(Node node) {
+		String str = node == null ?
+				"NULL" :
+				node.getClass() + " instance " + node.toString();
+		throw new IllegalArgumentException("Bad node type in XOM! " + str);
+	}
+
+    /**
+     * Get the configuration
+     */
+
+    public Configuration getConfiguration() {
+        return docWrapper.getConfiguration();
+    }
+
+	/**
+	 * Get the underlying XOM node, to implement the VirtualNode interface
+	 */
+
+	public Object getUnderlyingNode() {
+		return node;
+	}
+
+	/**
+	 * Get the real XOM node, to implement the VirtualNode interface
+	 */
+
+	public Object getRealNode() {
+		return node;
+	}
+
+	/**
+	 * Get the name pool for this node
+	 *
+	 * @return the NamePool
+	 */
+
+	public NamePool getNamePool() {
+		return docWrapper.getNamePool();
+	}
+
+	/**
+	 * Return the type of node.
+	 *
+	 * @return one of the values Node.ELEMENT, Node.TEXT, Node.ATTRIBUTE, etc.
+	 */
+
+	public int getNodeKind() {
+		return nodeKind;
+	}
+
+	/**
+	 * Get the typed value of the item
+	 */
+
+	public SequenceIterator getTypedValue() {
+		return SingletonIterator.makeIterator((AtomicValue)atomize());
+	}
+
+    /**
+	 * Get the typed value. The result of this method will always be consistent
+	 * with the method {@link net.sf.saxon.om.Item#getTypedValue()}. However,
+	 * this method is often more convenient and may be more efficient,
+	 * especially in the common case where the value is expected to be a
+	 * singleton.
+	 *
+	 * @return the typed value. If requireSingleton is set to true, the result
+	 *         will always be an AtomicValue. In other cases it may be a Value
+	 *         representing a sequence whose items are atomic values.
+	 * @since 8.5
+	 */
+
+	public Value atomize() {
+		switch (getNodeKind()) {
+			case Type.COMMENT:
+			case Type.PROCESSING_INSTRUCTION:
+				return new StringValue(getStringValueCS());
+			default:
+				return new UntypedAtomicValue(getStringValueCS());
+		}
+	}
+
+    /**
+	 * Get the type annotation of this node, if any. Returns -1 for kinds of
+	 * nodes that have no annotation, and for elements annotated as untyped, and
+	 * attributes annotated as untypedAtomic.
+	 *
+	 * @return the type annotation of the node.
+	 * @see net.sf.saxon.type.Type
+	 */
+
+	public int getTypeAnnotation() {
+        if (getNodeKind() == Type.ATTRIBUTE) {
+            return StandardNames.XS_UNTYPED_ATOMIC;
+        }
+        return StandardNames.XS_UNTYPED;
+	}
+
+	/**
+	 * Determine whether this is the same node as another node. <br />
+	 * Note: a.isSameNode(b) if and only if generateId(a)==generateId(b)
+	 *
+	 * @return true if this Node object and the supplied Node object represent
+	 *         the same node in the tree.
+	 */
+
+	public boolean isSameNodeInfo(NodeInfo other) {
+		if (other instanceof NodeWrapper) {
+			return node == ((NodeWrapper) other).node; // In XOM equality means identity
+		}
+		return false;
+	}
+
+    /**
+     * The equals() method compares nodes for identity. It is defined to give the same result
+     * as isSameNodeInfo().
+     *
+     * @param other the node to be compared with this node
+     * @return true if this NodeInfo object and the supplied NodeInfo object represent
+     *         the same node in the tree.
+     * @since 8.7 Previously, the effect of the equals() method was not defined. Callers
+     *        should therefore be aware that third party implementations of the NodeInfo interface may
+     *        not implement the correct semantics. It is safer to use isSameNodeInfo() for this reason.
+     *        The equals() method has been defined because it is useful in contexts such as a Java Set or HashMap.
+     */
+
+    public boolean equals(Object other) {
+        if (other instanceof NodeInfo) {
+            return isSameNodeInfo((NodeInfo)other);
+        } else {
+            return false;
+        }
+    }
+
+     /**
+      * The hashCode() method obeys the contract for hashCode(): that is, if two objects are equal
+      * (represent the same node) then they must have the same hashCode()
+      * @since 8.7 Previously, the effect of the equals() and hashCode() methods was not defined. Callers
+      * should therefore be aware that third party implementations of the NodeInfo interface may
+      * not implement the correct semantics.
+      */
+
+     public int hashCode() {
+         return node.hashCode();
+     }
+
+	/**
+	 * Get the System ID for the node.
+	 *
+	 * @return the System Identifier of the entity in the source document
+	 *         containing the node, or null if not known. Note this is not the
+	 *         same as the base URI: the base URI can be modified by xml:base,
+	 *         but the system ID cannot.
+	 */
+
+	public String getSystemId() {
+		return docWrapper.baseURI;
+	}
+
+	public void setSystemId(String uri) {
+		docWrapper.baseURI = uri;
+	}
+
+	/**
+	 * Get the Base URI for the node, that is, the URI used for resolving a
+	 * relative URI contained in the node.
+	 */
+
+	public String getBaseURI() {
+		return node.getBaseURI();
+	}
+
+	/**
+	 * Get line number
+	 *
+	 * @return the line number of the node in its original source document; or
+	 *         -1 if not available
+	 */
+
+	public int getLineNumber() {
+		return -1;
+	}
+
+	/**
+	 * Determine the relative position of this node and another node, in
+	 * document order. The other node will always be in the same document.
+	 *
+	 * @param other
+	 *            The other node, whose position is to be compared with this
+	 *            node
+	 * @return -1 if this node precedes the other node, +1 if it follows the
+	 *         other node, or 0 if they are the same node. (In this case,
+	 *         isSameNode() will always return true, and the two nodes will
+	 *         produce the same result for generateId())
+	 */
+
+	public int compareOrder(NodeInfo other) {
+		if (other instanceof NodeWrapper) {
+			return compareOrderFast(node,((NodeWrapper) other).node);
+//		}
+//		if (other instanceof SiblingCountingNode) {
+//			return Navigator.compareOrder(this, (SiblingCountingNode) other);
+		} else {
+			// it must be a namespace node
+			return -other.compareOrder(this);
+		}
+	}
+
+    private static int compareOrderFast(Node first, Node second) {
+		/*
+		 * Unfortunately we do not have a sequence number for each node at hand;
+		 * this would allow to turn the comparison into a simple sequence number
+		 * subtraction. Walking the entire tree and batch-generating sequence
+		 * numbers on the fly is no good option either. However, this rewritten
+		 * implementation turns out to be more than fast enough.
+		 */
+
+		// assert first != null && second != null
+    		// assert first and second MUST NOT be namespace nodes
+		if (first == second) return 0;
+
+		ParentNode firstParent = first.getParent();
+		ParentNode secondParent = second.getParent();
+		if (firstParent == null) {
+			if (secondParent != null) return -1; // first node is the root
+			// both nodes are parentless, use arbitrary but fixed order:
+			return first.hashCode() - second.hashCode();
+		}
+
+		if (secondParent == null) return +1; // second node is the root
+
+		// do they have the same parent (common case)?
+		if (firstParent == secondParent) {
+			int i1 = firstParent.indexOf(first);
+			int i2 = firstParent.indexOf(second);
+
+			// note that attributes and namespaces are not children
+			// of their own parent (i = -1).
+			// attribute (if any) comes before child
+			if (i1 != -1) return (i2 != -1) ? i1 - i2 : +1;
+			if (i2 != -1) return -1;
+
+			// assert: i1 == -1 && i2 == -1
+			// i.e. both nodes are attributes
+			Element elem = (Element) firstParent;
+			for (int i = elem.getAttributeCount(); --i >= 0;) {
+				Attribute attr = elem.getAttribute(i);
+				if (attr == second) return -1;
+				if (attr == first) return +1;
+			}
+			throw new IllegalStateException("should be unreachable");
+		}
+
+		// find the depths of both nodes in the tree
+		int depth1 = 0;
+		int depth2 = 0;
+		Node p1 = first;
+		Node p2 = second;
+		while (p1 != null) {
+			depth1++;
+			p1 = p1.getParent();
+			if (p1 == second) return +1;
+		}
+		while (p2 != null) {
+			depth2++;
+			p2 = p2.getParent();
+			if (p2 == first) return -1;
+		}
+
+		// move up one branch of the tree so we have two nodes on the same level
+		p1 = first;
+		while (depth1 > depth2) {
+			p1 = p1.getParent();
+			depth1--;
+		}
+		p2 = second;
+		while (depth2 > depth1) {
+			p2 = p2.getParent();
+			depth2--;
+		}
+
+		// now move up both branches in sync until we find a common parent
+		while (true) {
+			firstParent = p1.getParent();
+			secondParent = p2.getParent();
+			if (firstParent == null || secondParent == null) {
+				// both nodes are documentless, use arbitrary but fixed order
+				// based on their root elements
+				return p1.hashCode() - p2.hashCode();
+				// throw new NullPointerException("XOM tree compare - internal error");
+			}
+			if (firstParent == secondParent) {
+				return firstParent.indexOf(p1) - firstParent.indexOf(p2);
+			}
+			p1 = firstParent;
+			p2 = secondParent;
+		}
+	}
+
+	/**
+	 * Return the string value of the node. The interpretation of this depends
+	 * on the type of node. For an element it is the accumulated character
+	 * content of the element, including descendant elements.
+	 *
+	 * @return the string value of the node
+	 */
+
+	public String getStringValue() {
+        return node.getValue();
+	}
+
+    /**
+     * Get the value of the item as a CharSequence. This is in some cases more efficient than
+     * the version of the method that returns a String.
+     */
+
+    public CharSequence getStringValueCS() {
+        return node.getValue();
+    }
+
+	/**
+	 * Get name code. The name code is a coded form of the node name: two nodes
+	 * with the same name code have the same namespace URI, the same local name,
+	 * and the same prefix. By masking the name code with &0xfffff, you get a
+	 * fingerprint: two nodes with the same fingerprint have the same local name
+	 * and namespace URI.
+	 *
+	 * @see net.sf.saxon.om.NamePool#allocate allocate
+	 */
+
+	public int getNameCode() {
+		switch (nodeKind) {
+		case Type.ELEMENT:
+		case Type.ATTRIBUTE:
+		case Type.PROCESSING_INSTRUCTION:
+			return docWrapper.getNamePool().allocate(getPrefix(), getURI(),
+					getLocalPart());
+		default:
+			return -1;
+		}
+	}
+
+	/**
+	 * Get fingerprint. The fingerprint is a coded form of the expanded name of
+	 * the node: two nodes with the same name code have the same namespace URI
+	 * and the same local name. A fingerprint of -1 should be returned for a
+	 * node with no name.
+	 */
+
+	public int getFingerprint() {
+		int nc = getNameCode();
+		if (nc == -1) return -1;
+		return nc & 0xfffff;
+	}
+
+	/**
+	 * Get the local part of the name of this node. This is the name after the
+	 * ":" if any.
+	 *
+	 * @return the local part of the name. For an unnamed node, returns "".
+	 */
+
+	public String getLocalPart() {
+		switch (nodeKind) {
+			case Type.ELEMENT:
+				return ((Element) node).getLocalName();
+			case Type.ATTRIBUTE:
+				return ((Attribute) node).getLocalName();
+			case Type.PROCESSING_INSTRUCTION:
+				return ((ProcessingInstruction) node).getTarget();
+			default:
+				return "";
+		}
+	}
+
+    /**
+     * Get the prefix of the name of the node. This is defined only for elements and attributes.
+     * If the node has no prefix, or for other kinds of node, return a zero-length string.
+     * @return The prefix of the name of the node.
+     */
+
+	public String getPrefix() {
+		switch (nodeKind) {
+			case Type.ELEMENT:
+				return ((Element) node).getNamespacePrefix();
+			case Type.ATTRIBUTE:
+				return ((Attribute) node).getNamespacePrefix();
+			default:
+				return "";
+		}
+	}
+
+    /**
+	 * Get the URI part of the name of this node. This is the URI corresponding
+	 * to the prefix, or the URI of the default namespace if appropriate.
+	 *
+	 * @return The URI of the namespace of this node. For an unnamed node, or
+	 *         for a node with an empty prefix, return an empty string.
+	 */
+
+	public String getURI() {
+		switch (nodeKind) {
+			case Type.ELEMENT:
+				return ((Element) node).getNamespaceURI();
+			case Type.ATTRIBUTE:
+				return ((Attribute) node).getNamespaceURI();
+			default:
+				return "";
+		}
+	}
+
+	/**
+	 * Get the display name of this node. For elements and attributes this is
+	 * [prefix:]localname. For unnamed nodes, it is an empty string.
+	 *
+	 * @return The display name of this node. For a node with no name, return an
+	 *         empty string.
+	 */
+
+	public String getDisplayName() {
+		switch (nodeKind) {
+			case Type.ELEMENT:
+				return ((Element) node).getQualifiedName();
+			case Type.ATTRIBUTE:
+				return ((Attribute) node).getQualifiedName();
+			case Type.PROCESSING_INSTRUCTION:
+				return ((ProcessingInstruction) node).getTarget();
+			default:
+				return "";
+		}
+	}
+
+	/**
+	 * Get the NodeInfo object representing the parent of this node
+	 */
+
+	public NodeInfo getParent() {
+		if (parent == null) {
+			ParentNode p = node.getParent();
+			if (p != null) parent = makeWrapper(p, docWrapper);
+		}
+		return parent;
+	}
+
+	/**
+	 * Get the index position of this node among its siblings (starting from 0)
+	 */
+
+	public int getSiblingPosition() {
+		if (index != -1) return index;
+		switch (nodeKind) {
+			case Type.ATTRIBUTE: {
+				Attribute att = (Attribute) node;
+				Element p = (Element) att.getParent();
+				if (p == null) return 0;
+				for (int i=p.getAttributeCount(); --i >= 0;) {
+					if (p.getAttribute(i) == att) {
+						index = i;
+						return i;
+					}
+				}
+				throw new IllegalStateException("XOM node not linked to parent node");
+			}
+
+			default: {
+				ParentNode p = node.getParent();
+				int i = (p == null ? 0 : p.indexOf(node));
+				if (i == -1) throw new IllegalStateException("XOM node not linked to parent node");
+				index = i;
+				return index;
+			}
+		}
+	}
+
+	/**
+	 * Return an iteration over the nodes reached by the given axis from this
+	 * node
+	 *
+	 * @param axisNumber
+	 *            the axis to be used
+	 * @return a SequenceIterator that scans the nodes reached by the axis in
+	 *         turn.
+	 */
+
+	public AxisIterator iterateAxis(byte axisNumber) {
+		return iterateAxis(axisNumber, AnyNodeTest.getInstance());
+	}
+
+	/**
+	 * Return an iteration over the nodes reached by the given axis from this
+	 * node
+	 *
+	 * @param axisNumber
+	 *            the axis to be used
+	 * @param nodeTest
+	 *            A pattern to be matched by the returned nodes
+	 * @return a SequenceIterator that scans the nodes reached by the axis in
+	 *         turn.
+	 */
+
+	public AxisIterator iterateAxis(byte axisNumber, NodeTest nodeTest) {
+		// for clarifications, see the W3C specs or:
+		// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/xmrefaxes.asp
+		switch (axisNumber) {
+		case Axis.ANCESTOR:
+			return new AncestorAxisIterator(this, false, nodeTest);
+
+		case Axis.ANCESTOR_OR_SELF:
+			return new AncestorAxisIterator(this, true, nodeTest);
+
+		case Axis.ATTRIBUTE:
+			if (nodeKind != Type.ELEMENT || ((Element) node).getAttributeCount() == 0) {
+				return EmptyIterator.getInstance();
+			} else {
+				return new AttributeAxisIterator(this, nodeTest);
+			}
+
+		case Axis.CHILD:
+			if (hasChildNodes()) {
+				return new ChildAxisIterator(this, true, true, nodeTest);
+			} else {
+				return EmptyIterator.getInstance();
+			}
+
+		case Axis.DESCENDANT:
+			if (hasChildNodes()) {
+				return new DescendantAxisIterator(this, false, false, nodeTest);
+			} else {
+				return EmptyIterator.getInstance();
+			}
+
+		case Axis.DESCENDANT_OR_SELF:
+			if (hasChildNodes()) {
+				return new DescendantAxisIterator(this, true, false, nodeTest);
+			} else {
+				return filteredSingleton(this, nodeTest);
+			}
+
+		case Axis.FOLLOWING:
+			if (getParent() == null) {
+				return EmptyIterator.getInstance();
+			} else {
+				return new DescendantAxisIterator(this, false, true, nodeTest);
+			}
+
+		case Axis.FOLLOWING_SIBLING:
+			if (nodeKind == Type.ATTRIBUTE || getParent() == null) {
+				return EmptyIterator.getInstance();
+			} else {
+				return new ChildAxisIterator(this, false, true, nodeTest);
+			}
+
+		case Axis.NAMESPACE:
+			if (nodeKind == Type.ELEMENT) {
+				return NamespaceIterator.makeIterator(this, nodeTest);
+			} else {
+				return EmptyIterator.getInstance();
+			}
+
+		case Axis.PARENT:
+			if (getParent() == null) {
+				return EmptyIterator.getInstance();
+			} else {
+				return filteredSingleton(getParent(), nodeTest);
+			}
+
+		case Axis.PRECEDING:
+			return new PrecedingAxisIterator(this, false, nodeTest);
+//			return new Navigator.AxisFilter(
+//					new Navigator.PrecedingEnumeration(this, false), nodeTest);
+
+		case Axis.PRECEDING_SIBLING:
+			if (nodeKind == Type.ATTRIBUTE || getParent() == null) {
+				return EmptyIterator.getInstance();
+			} else {
+				return new ChildAxisIterator(this, false, false, nodeTest);
+			}
+
+		case Axis.SELF:
+			return filteredSingleton(this, nodeTest);
+
+		case Axis.PRECEDING_OR_ANCESTOR:
+			// This axis is used internally by saxon for the xsl:number implementation,
+			// it returns the union of the preceding axis and the ancestor axis.
+			return new PrecedingAxisIterator(this, true, nodeTest);
+//			return new Navigator.AxisFilter(new Navigator.PrecedingEnumeration(
+//					this, true), nodeTest);
+
+		default:
+			throw new IllegalArgumentException("Unknown axis number " + axisNumber);
+		}
+	}
+
+//	private static AxisIterator makeSingleIterator(NodeWrapper wrapper, NodeTest nodeTest) {
+//		if (nodeTest == AnyNodeTest.getInstance() || nodeTest.matches(wrapper))
+//			return SingletonIterator.makeIterator(wrapper);
+//		else
+//			return EmptyIterator.getInstance();
+//	}
+
+	/**
+	 * Get the value of a given attribute of this node
+	 *
+	 * @param fingerprint
+	 *            The fingerprint of the attribute name
+	 * @return the attribute value if it exists or null if not
+	 */
+
+	public String getAttributeValue(int fingerprint) {
+		if (nodeKind == Type.ELEMENT) {
+			NamePool pool = docWrapper.getNamePool();
+			String localName = pool.getLocalName(fingerprint);
+			String uri = pool.getURI(fingerprint);
+			Attribute att = ((Element) node).getAttribute(localName, uri);
+			if (att != null) return att.getValue();
+		}
+		return null;
+	}
+
+    /**
+     * Get the root node of the tree containing this node
+     *
+     * @return the NodeInfo representing the top-level ancestor of this node.
+     *     This will not necessarily be a document node
+     */
+
+	public NodeInfo getRoot() {
+		return docWrapper;
+	}
+
+    /**
+     * Get the root node, if it is a document node.
+     *
+     * @return the DocumentInfo representing the containing document.
+     */
+
+	public DocumentInfo getDocumentRoot() {
+		if (docWrapper.node instanceof Document) {
+            return docWrapper;
+        } else {
+            return null;
+        }
+	}
+
+	/**
+	 * Determine whether the node has any children. <br />
+	 * Note: the result is equivalent to <br />
+	 * getEnumeration(Axis.CHILD, AnyNodeTest.getInstance()).hasNext()
+	 */
+
+	public boolean hasChildNodes() {
+		return node.getChildCount() > 0;
+	}
+
+	/**
+	 * Get a character string that uniquely identifies this node. Note:
+	 * a.isSameNode(b) if and only if generateId(a)==generateId(b)
+	 *
+	 * @param buffer a buffer to contain a string that uniquely identifies this node, across all documents
+     */
+
+	public void generateId(FastStringBuffer buffer) {
+        Navigator.appendSequentialKey(this, buffer, true);
+		//buffer.append(Navigator.getSequentialKey(this));
+	}
+
+	/**
+	 * Get the document number of the document containing this node. For a
+	 * free-standing orphan node, just return the hashcode.
+	 */
+
+	public long getDocumentNumber() {
+		return docWrapper.getDocumentNumber();
+	}
+
+	/**
+	 * Copy this node to a given outputter (deep copy)
+	 */
+
+	public void copy(Receiver out, int whichNamespaces,
+			boolean copyAnnotations, int locationId) throws XPathException {
+		Navigator.copy(this, out, docWrapper.getNamePool(), whichNamespaces,
+				copyAnnotations, locationId);
+	}
+
+    /**
+     * Get all namespace undeclarations and undeclarations defined on this element.
+     *
+     * @param buffer If this is non-null, and the result array fits in this buffer, then the result
+     *               may overwrite the contents of this array, to avoid the cost of allocating a new array on the heap.
+     * @return An array of integers representing the namespace declarations and undeclarations present on
+     *         this element. For a node other than an element, return null. Otherwise, the returned array is a
+     *         sequence of namespace codes, whose meaning may be interpreted by reference to the name pool. The
+     *         top half word of each namespace code represents the prefix, the bottom half represents the URI.
+     *         If the bottom half is zero, then this is a namespace undeclaration rather than a declaration.
+     *         The XML namespace is never included in the list. If the supplied array is larger than required,
+     *         then the first unused entry will be set to -1.
+     *         <p/>
+     *         <p>For a node other than an element, the method returns null.</p>
+     */
+
+    public int[] getDeclaredNamespaces(int[] buffer) {
+        if (node instanceof Element) {
+            Element elem = (Element)node;
+            int size = elem.getNamespaceDeclarationCount();
+            if (size == 0) {
+                return EMPTY_NAMESPACE_LIST;
+            }
+            int[] result = (buffer != null && size <= buffer.length ? buffer : new int[size]);
+            NamePool pool = getNamePool();
+            for (int i=0; i < size; i++) {
+                String prefix = elem.getNamespacePrefix(i);
+                String uri = elem.getNamespaceURI(prefix);
+                result[i] = pool.allocateNamespaceCode(prefix, uri);
+            }
+            if (size < result.length) {
+                result[size] = -1;
+            }
+            return result;
+        } else {
+            return null;
+        }
+    }
+
+	///////////////////////////////////////////////////////////////////////////////
+	// Axis enumeration classes
+	///////////////////////////////////////////////////////////////////////////////
+
+    /**
+	 * Handles the ancestor axis in a rather direct manner.
+	 */
+	private final class AncestorAxisIterator extends AxisIteratorImpl {
+
+		private NodeWrapper start;
+		private boolean includeSelf;
+
+		private NodeTest nodeTest;
+
+		public AncestorAxisIterator(NodeWrapper start, boolean includeSelf, NodeTest test) {
+			// use lazy instead of eager materialization (performance)
+			this.start = start;
+			if (test == AnyNodeTest.getInstance()) test = null;
+			this.nodeTest = test;
+			if (!includeSelf) this.current = start;
+			this.includeSelf = includeSelf;
+			this.position = 0;
+		}
+
+		public Item next() {
+			NodeInfo curr;
+			do { // until we find a match
+				curr = advance();
+			}
+			while (curr != null && nodeTest != null && (! nodeTest.matches(curr)));
+
+			if (curr != null) position++;
+			current = curr;
+			return curr;
+		}
+
+		private NodeInfo advance() {
+			if (current == null)
+				current = start;
+			else
+				current = current.getParent();
+
+			return current;
+		}
+
+		public Item current() {
+			return current;
+		}
+
+		public SequenceIterator getAnother() {
+			return new AncestorAxisIterator(start, includeSelf, nodeTest);
+		}
+
+		public int getProperties() {
+			return 0;
+		}
+
+	} // end of class AncestorAxisIterator
+
+    /**
+	 * Handles the attribute axis in a rather direct manner.
+	 */
+	private final class AttributeAxisIterator extends AxisIteratorImpl {
+
+		private NodeWrapper start;
+
+		private int cursor;
+
+		private NodeTest nodeTest;
+
+		public AttributeAxisIterator(NodeWrapper start, NodeTest test) {
+			// use lazy instead of eager materialization (performance)
+			this.start = start;
+			if (test == AnyNodeTest.getInstance()) test = null;
+			this.nodeTest = test;
+			this.position = 0;
+			this.cursor = 0;
+		}
+
+		public Item next() {
+			NodeInfo curr;
+			do { // until we find a match
+				curr = advance();
+			}
+			while (curr != null && nodeTest != null && (! nodeTest.matches(curr)));
+
+			if (curr != null) position++;
+			current = curr;
+			return curr;
+		}
+
+		private NodeInfo advance() {
+			Element elem = (Element) start.node;
+			if (cursor == elem.getAttributeCount()) return null;
+			NodeInfo curr = makeWrapper(elem.getAttribute(cursor), docWrapper, start, cursor);
+			cursor++;
+			return curr;
+		}
+
+		public Item current() {
+			return current;
+		}
+
+		public SequenceIterator getAnother() {
+			return new AttributeAxisIterator(start, nodeTest);
+		}
+
+ 		public int getProperties() {
+			return 0;
+		}
+
+	} // end of class AttributeAxisIterator
+
+    /**
+	 * The class ChildAxisIterator handles not only the child axis, but also the
+	 * following-sibling and preceding-sibling axes. It can also iterate the
+	 * children of the start node in reverse order, something that is needed to
+	 * support the preceding and preceding-or-ancestor axes (the latter being
+	 * used by xsl:number)
+	 */
+	private final class ChildAxisIterator extends AxisIteratorImpl {
+
+		private NodeWrapper start;
+		private NodeWrapper commonParent;
+		private int ix;
+		private boolean downwards; // iterate children of start node (not siblings)
+		private boolean forwards; // iterate in document order (not reverse order)
+
+		private ParentNode par;
+		private int cursor;
+
+		private NodeTest nodeTest;
+
+		private ChildAxisIterator(NodeWrapper start, boolean downwards, boolean forwards, NodeTest test) {
+			this.start = start;
+			this.downwards = downwards;
+			this.forwards = forwards;
+
+			if (test == AnyNodeTest.getInstance()) test = null;
+			this.nodeTest = test;
+			this.position = 0;
+
+			if (downwards)
+				commonParent = start;
+			else
+				commonParent = (NodeWrapper) start.getParent();
+
+			par = (ParentNode) commonParent.node;
+			if (downwards) {
+				ix = (forwards ? 0 : par.getChildCount());
+			} else {
+				// find the start node among the list of siblings
+//				ix = start.getSiblingPosition();
+				ix = par.indexOf(start.node);
+				if (forwards) ix++;
+			}
+			cursor = ix;
+			if (!downwards && !forwards) ix--;
+		}
+
+		public Item next() {
+			NodeInfo curr;
+			do { // until we find a match
+				curr = advance();
+			}
+			while (curr != null && nodeTest != null && (! nodeTest.matches(curr)));
+
+			if (curr != null) position++;
+			current = curr;
+			return curr;
+		}
+
+		private NodeInfo advance() {
+			Node nextChild;
+			do {
+				if (forwards) {
+					if (cursor == par.getChildCount()) return null;
+					nextChild = par.getChild(cursor++);
+				} else { // backwards
+					if (cursor == 0) return null;
+					nextChild = par.getChild(--cursor);
+				}
+			} while (nextChild instanceof DocType);
+			// DocType is not an XPath node; can occur for /child::node()
+
+			NodeInfo curr = makeWrapper(nextChild, docWrapper, commonParent, ix);
+			ix += (forwards ? 1 : -1);
+			return curr;
+		}
+
+		public Item current() {
+			return current;
+		}
+
+		public SequenceIterator getAnother() {
+			return new ChildAxisIterator(start, downwards, forwards, nodeTest);
+		}
+
+ 		public int getProperties() {
+			return 0;
+		}
+	}
+
+	/**
+	 * A bit of a misnomer; efficiently takes care of descendants,
+	 * descentants-or-self as well as "following" axis.
+	 * "includeSelf" must be false for the following axis.
+	 * Uses simple and effective O(1) backtracking via indexOf().
+	 */
+    private final class DescendantAxisIterator extends AxisIteratorImpl {
+
+		private NodeWrapper start;
+		private boolean includeSelf;
+		private boolean following;
+
+		private Node anchor; // so we know where to stop the scan
+		private Node currNode;
+		private boolean moveToNextSibling;
+
+		private NodeTest nodeTest;
+
+		private String testLocalName;
+		private String testURI;
+
+		public DescendantAxisIterator(NodeWrapper start, boolean includeSelf, boolean following, NodeTest test) {
+			this.start = start;
+			this.includeSelf = includeSelf;
+			this.following = following;
+			this.moveToNextSibling = following;
+
+			if (!following) anchor = start.node;
+			if (!includeSelf) currNode = start.node;
+
+			if (test == AnyNodeTest.getInstance()) { // performance hack
+				test = null; // mark as AnyNodeTest
+			}
+			else if (test instanceof NameTest) {
+				NameTest nt = (NameTest) test;
+				if (nt.getPrimitiveType() == Type.ELEMENT) { // performance hack
+					// mark as element name test
+					NamePool pool = getNamePool();
+					this.testLocalName = pool.getLocalName(nt.getFingerprint());
+					this.testURI = pool.getURI(nt.getFingerprint());
+				}
+			}
+			else if (test instanceof NodeKindTest) {
+				if (test.getPrimitiveType() == Type.ELEMENT) { // performance hack
+					// mark as element type test
+					this.testLocalName = "";
+					this.testURI = null;
+				}
+			}
+			this.nodeTest = test;
+			this.position = 0;
+		}
+
+		public Item next() {
+			NodeInfo curr;
+			do { // until we find a match
+				curr = advance();
+			}
+			while (curr != null && nodeTest != null && (! nodeTest.matches(curr)));
+
+			if (curr != null) position++;
+			current = curr;
+			return curr;
+		}
+
+		// might look expensive at first glance - but it's not
+		private NodeInfo advance() {
+			if (currNode == null) { // if includeSelf
+				currNode = start.node;
+				return start;
+			}
+
+			int i;
+			do {
+				i = 0;
+				Node p = currNode;
+
+				if (p.getChildCount() == 0 || moveToNextSibling) { // move to next sibling
+
+					moveToNextSibling = false; // do it just once
+					while (true) {
+						// if we've reached the root we're done scanning
+						p = currNode.getParent();
+						if (p == null) return null;
+
+						// Note: correct even if currNode is an attribute.
+						// Performance is particularly good with the O(1) patch
+						// for XOM's ParentNode.indexOf()
+						i = currNode.getParent().indexOf(currNode) + 1;
+
+						if (i < p.getChildCount()) {
+							break; // break out of while(true) loop; move to next sibling
+						}
+						else { // reached last sibling; move up
+							currNode = p;
+							// if we've come all the way back to the start anchor we're done
+							if (p == anchor) return null;
+						}
+					}
+				}
+				currNode = p.getChild(i);
+			} while (!conforms(currNode));
+
+			// note the null here: makeNodeWrapper(parent, ...) is fast, so it
+			// doesn't really matter that we don't keep a link to it.
+			// In fact, it makes objects more short lived, easing pressure on
+			// the VM allocator and collector for tenured heaps.
+			return makeWrapper(currNode, docWrapper, null, i);
+		}
+
+		// avoids NodeWrapper allocation when there's clearly a mismatch (common case)
+		private boolean conforms(Node node) {
+			if (this.testLocalName != null) { // element test?
+				if (!(node instanceof Element)) return false;
+				if (this.testURI == null) return true; // pure element type test
+
+				// element name test
+				Element elem = (Element) node;
+				return this.testLocalName.equals(elem.getLocalName()) &&
+					this.testURI.equals(elem.getNamespaceURI());
+			}
+			else { // DocType is not an XPath node; can occur for /descendants::node()
+				return !(node instanceof DocType);
+			}
+		}
+
+		public Item current() {
+			return current;
+		}
+
+		public SequenceIterator getAnother() {
+			return new DescendantAxisIterator(start, includeSelf, following, nodeTest);
+		}
+
+ 		public int getProperties() {
+			return 0;
+		}
+	}
+
+	/**
+	 * Efficiently takes care of preceding axis and Saxon internal preceding-or-ancestor axis.
+	 * Uses simple and effective O(1) backtracking via indexOf().
+	 * Implemented along similar lines as DescendantAxisIterator.
+	 */
+    private final class PrecedingAxisIterator extends AxisIteratorImpl {
+
+		private NodeWrapper start;
+		private boolean includeAncestors;
+
+		private Node currNode;
+		private ParentNode nextAncestor; // next ancestors to skip if !includeAncestors
+
+		private NodeTest nodeTest;
+
+		private String testLocalName;
+		private String testURI;
+
+		public PrecedingAxisIterator(NodeWrapper start, boolean includeAncestors, NodeTest test) {
+			this.start = start;
+			this.includeAncestors = includeAncestors;
+			this.currNode = start.node;
+			if (includeAncestors)
+				nextAncestor = null;
+			else
+				nextAncestor = start.node.getParent();
+
+			if (test == AnyNodeTest.getInstance()) { // performance hack
+				test = null; // mark as AnyNodeTest
+			}
+			else if (test instanceof NameTest) {
+				NameTest nt = (NameTest) test;
+				if (nt.getPrimitiveType() == Type.ELEMENT) { // performance hack
+					// mark as element name test
+					NamePool pool = getNamePool();
+					this.testLocalName = pool.getLocalName(nt.getFingerprint());
+					this.testURI = pool.getURI(nt.getFingerprint());
+				}
+			}
+			else if (test instanceof NodeKindTest) {
+				if (test.getPrimitiveType() == Type.ELEMENT) { // performance hack
+					// mark as element type test
+					this.testLocalName = "";
+					this.testURI = null;
+				}
+			}
+			this.nodeTest = test;
+			this.position = 0;
+		}
+
+		public Item next() {
+			NodeInfo curr;
+			do { // until we find a match
+				curr = advance();
+			}
+			while (curr != null && nodeTest != null && (! nodeTest.matches(curr)));
+
+			if (curr != null) position++;
+			current = curr;
+			return curr;
+		}
+
+		// might look expensive at first glance - but it's not
+		private NodeInfo advance() {
+			int i;
+			do {
+				Node p;
+
+				while (true) {
+					// if we've reached the root we're done scanning
+//					System.out.println("p="+p);
+					p = currNode.getParent();
+					if (p == null) return null;
+
+					// Note: correct even if currNode is an attribute.
+					// Performance is particularly good with the O(1) patch
+					// for XOM's ParentNode.indexOf()
+					i = currNode.getParent().indexOf(currNode) - 1;
+
+					if (i >= 0) { // move to next sibling's last descendant node
+						p = p.getChild(i); // move to next sibling
+						int j;
+						while ((j = p.getChildCount()-1) >= 0) { // move to last descendant node
+							p = p.getChild(j);
+							i = j;
+						}
+						break; // break out of while(true) loop
+					}
+					else { // there are no more siblings; move up
+						// if !includeAncestors skip the ancestors of the start node
+						// assert p != null
+						if (p != nextAncestor) break; // break out of while(true) loop
+
+						nextAncestor = nextAncestor.getParent();
+						currNode = p;
+					}
+				}
+				currNode = p;
+
+			} while (!conforms(currNode));
+
+			// note the null here: makeNodeWrapper(parent, ...) is fast, so it
+			// doesn't really matter that we don't keep a link to it.
+			// In fact, it makes objects more short lived, easing pressure on
+			// the VM allocator and collector for tenured heaps.
+			return makeWrapper(currNode, docWrapper, null, i);
+		}
+
+		// avoids NodeWrapper allocation when there's clearly a mismatch (common case)
+		// same as for DescendantAxisIterator
+		private boolean conforms(Node node) {
+			if (this.testLocalName != null) { // element test?
+				if (!(node instanceof Element)) return false;
+				if (this.testURI == null) return true; // pure element type test
+
+				// element name test
+				Element elem = (Element) node;
+				return this.testLocalName.equals(elem.getLocalName()) &&
+					this.testURI.equals(elem.getNamespaceURI());
+			}
+			else { // DocType is not an XPath node
+				return !(node instanceof DocType);
+			}
+		}
+
+		public Item current() {
+			return current;
+		}
+
+		public SequenceIterator getAnother() {
+			return new PrecedingAxisIterator(start, includeAncestors, nodeTest);
+		}
+
+ 		public int getProperties() {
+			return 0;
+		}
+	}
+
+    private static AxisIterator filteredSingleton(NodeInfo node, NodeTest nodeTest) {
+//    	return Navigator.filteredSingleton(node, nodeTest); // saxon >= 8.7
+        if (node != null && (nodeTest == AnyNodeTest.getInstance() || nodeTest.matches(node))) {
+            return SingleNodeIterator.makeIterator(node);
+        } else {
+            return EmptyIterator.getInstance();
+        }
+    }
+
+	@Override
+	public int getColumnNumber() {
+		return -1;
+	}
+
+	@Override
+	public boolean isId() {
+		return false;
+	}
+
+	@Override
+	public boolean isIdref() {
+		return false;
+	}
+
+	@Override
+	public boolean isNilled() {
+		return false;
+	}
+
+}
+
+//
+// The contents of this file are subject to the Mozilla Public License Version
+// 1.0 (the "License");
+// you may not use this file except in compliance with the License. You may
+// obtain a copy of the
+// License at http://www.mozilla.org/MPL/
+//
+// Software distributed under the License is distributed on an "AS IS" basis,
+// WITHOUT WARRANTY OF ANY KIND, either express or implied.
+// See the License for the specific language governing rights and limitations
+// under the License.
+//
+// The Original Code is: all this file.
+//
+// The Initial Developer of the Original Code is Michael Kay, with extensive
+// rewriting by Wolfgang Hoschek
+//
+// Portions created by (your name) are Copyright (C) (your legal entity). All
+// Rights Reserved.
+//
+// Contributor(s): none.
+//

Modified: branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/PathMapFilter.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/PathMapFilter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/PathMapFilter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -184,5 +184,13 @@
 			super.endElement();
 		}
 	}
+	
+	@Override
+	public void startContent() throws XPathException {
+		MatchContext context = matchContext.getLast();
+		if (context.matchedElement) {
+			super.startContent();
+		}
+	}
 
 }
\ No newline at end of file

Modified: branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/SaxonXQueryExpression.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/SaxonXQueryExpression.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/SaxonXQueryExpression.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,8 +24,8 @@
 
 import java.io.IOException;
 import java.io.Writer;
-import java.sql.SQLXML;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedList;
@@ -38,9 +38,7 @@
 import javax.xml.transform.Source;
 import javax.xml.transform.TransformerException;
 
-import net.sf.saxon.AugmentedSource;
 import net.sf.saxon.Configuration;
-import net.sf.saxon.event.ProxyReceiver;
 import net.sf.saxon.expr.AxisExpression;
 import net.sf.saxon.expr.ContextItemExpression;
 import net.sf.saxon.expr.Expression;
@@ -51,16 +49,15 @@
 import net.sf.saxon.expr.PathMap.PathMapNodeSet;
 import net.sf.saxon.expr.PathMap.PathMapRoot;
 import net.sf.saxon.om.Axis;
-import net.sf.saxon.om.DocumentInfo;
 import net.sf.saxon.om.Item;
 import net.sf.saxon.om.NodeInfo;
 import net.sf.saxon.om.SequenceIterator;
 import net.sf.saxon.om.StructuredQName;
 import net.sf.saxon.pattern.AnyNodeTest;
 import net.sf.saxon.pattern.NodeKindTest;
-import net.sf.saxon.query.DynamicQueryContext;
 import net.sf.saxon.query.QueryResult;
 import net.sf.saxon.query.StaticQueryContext;
+import net.sf.saxon.query.XQueryExpression;
 import net.sf.saxon.sxpath.IndependentContext;
 import net.sf.saxon.sxpath.XPathEvaluator;
 import net.sf.saxon.sxpath.XPathExpression;
@@ -93,6 +90,19 @@
 @SuppressWarnings("serial")
 public class SaxonXQueryExpression {
 	
+	public static final Properties DEFAULT_OUTPUT_PROPERTIES = new Properties();
+	{
+		DEFAULT_OUTPUT_PROPERTIES.setProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
+	    //props.setProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
+		DEFAULT_OUTPUT_PROPERTIES.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
+	}
+	
+	public interface RowProcessor {
+		
+		void processRow(NodeInfo row);
+
+	}
+	
 	public static class Result {
 		public SequenceIterator iter;
 		public List<Source> sources = new LinkedList<Source>();
@@ -147,16 +157,20 @@
         }       
     };
 
-	private net.sf.saxon.query.XQueryExpression xQuery;    
-	private Configuration config = new Configuration();
-	private PathMapRoot contextRoot;
+	XQueryExpression xQuery;
+	String xQueryString;
+	Map<String, String> namespaceMap = new HashMap<String, String>();
+	Configuration config = new Configuration();
+	PathMapRoot contextRoot;
+	String streamingPath;
 
     public SaxonXQueryExpression(String xQueryString, XMLNamespaces namespaces, List<DerivedColumn> passing, List<XMLTable.XMLColumn> columns) 
     throws QueryResolverException {
         config.setErrorListener(ERROR_LISTENER);
+        this.xQueryString = xQueryString;
         StaticQueryContext context = new StaticQueryContext(config);
         IndependentContext ic = new IndependentContext(config);
-        
+        namespaceMap.put("", ""); //$NON-NLS-1$ //$NON-NLS-2$
         if (namespaces != null) {
         	for (NamespaceItem item : namespaces.getNamespaceItems()) {
         		if (item.getPrefix() == null) {
@@ -166,10 +180,12 @@
         			} else {
         				context.setDefaultElementNamespace(item.getUri());
         				ic.setDefaultElementNamespace(item.getUri());
+        				namespaceMap.put("", item.getUri()); //$NON-NLS-1$
         			}
         		} else {
     				context.declareNamespace(item.getPrefix(), item.getUri());
     				ic.declareNamespace(item.getPrefix(), item.getUri());
+    				namespaceMap.put(item.getPrefix(), item.getUri());
         		}
 			}
         }
@@ -201,8 +217,11 @@
     public SaxonXQueryExpression clone() {
     	SaxonXQueryExpression clone = new SaxonXQueryExpression();
     	clone.xQuery = xQuery;
+    	clone.xQueryString = xQueryString;
     	clone.config = config;
     	clone.contextRoot = contextRoot;
+    	clone.namespaceMap = namespaceMap;
+    	clone.streamingPath = streamingPath;
     	return clone;
     }
     
@@ -211,6 +230,13 @@
     }
     
 	public void useDocumentProjection(List<XMLTable.XMLColumn> columns, AnalysisRecord record) {
+		try {
+			streamingPath = StreamingUtils.getStreamingPath(xQueryString, namespaceMap);
+		} catch (IllegalArgumentException e) {
+			if (record.recordDebug()) {
+				record.println("Document streaming will not be used: " + e.getMessage()); //$NON-NLS-1$
+			}
+		}
 		this.contextRoot = null;
 		PathMap map = this.xQuery.getPathMap();
 		PathMapRoot parentRoot;
@@ -246,8 +272,8 @@
 					return;
 				}
 			} else {
-				for (Iterator iter = finalNodes.iterator(); iter.hasNext(); ) {
-	                PathMapNode subNode = (PathMapNode)iter.next();
+				for (Iterator<PathMapNode> iter = finalNodes.iterator(); iter.hasNext(); ) {
+	                PathMapNode subNode = iter.next();
 	                subNode.createArc(new AxisExpression(Axis.DESCENDANT_OR_SELF, AnyNodeTest.getInstance()));
 	            }
 			}
@@ -265,6 +291,24 @@
 		}
 		this.contextRoot = parentRoot;
 	}
+	
+    public static final boolean[] isValidAncestorAxis =
+    {
+        false,          // ANCESTOR
+        false,          // ANCESTOR_OR_SELF;
+        true,           // ATTRIBUTE;
+        false,           // CHILD;
+        false,           // DESCENDANT;
+        false,           // DESCENDANT_OR_SELF;
+        false,          // FOLLOWING;
+        false,          // FOLLOWING_SIBLING;
+        true,           // NAMESPACE;
+        true,          // PARENT;
+        false,          // PRECEDING;
+        false,          // PRECEDING_SIBLING;
+        true,           // SELF;
+        false,          // PRECEDING_OR_ANCESTOR;
+    };
 
 	private PathMapRoot projectColumns(PathMapRoot parentRoot, List<XMLTable.XMLColumn> columns, PathMapNode finalNode, AnalysisRecord record) {
 		for (XMLColumn xmlColumn : columns) {
@@ -293,6 +337,9 @@
 	    		continue;
 	    	}
 	    	for (PathMapArc arc : subContextRoot.getArcs()) {
+	    		if (streamingPath != null && !validateColumnForStreaming(record, xmlColumn, arc)) {
+	    			streamingPath = null;
+	    		}
 				finalNode.createArc(arc.getStep(), arc.getTarget());
 			}
 	    	HashSet<PathMapNode> subFinalNodes = new HashSet<PathMapNode>();
@@ -319,6 +366,54 @@
 		return newMap.reduceToDownwardsAxes(newRoot);
 	}
 
+	private boolean validateColumnForStreaming(AnalysisRecord record,
+			XMLColumn xmlColumn, PathMapArc arc) {
+		boolean ancestor = false;
+		LinkedList<PathMapArc> arcStack = new LinkedList<PathMapArc>();
+		arcStack.add(arc);
+		while (!arcStack.isEmpty()) {
+			PathMapArc current = arcStack.removeFirst();
+			byte axis = current.getStep().getAxis();
+			if (ancestor) {
+				if (current.getTarget().isReturnable()) {
+					if (axis != Axis.NAMESPACE && axis != Axis.ATTRIBUTE) {
+						if (record.recordDebug()) {
+							record.println("Document streaming will not be used, since the column path contains an invalid reverse axis " + xmlColumn.getPath()); //$NON-NLS-1$
+						}
+						return false;
+					}
+				}
+				if (!isValidAncestorAxis[axis]) {
+					if (record.recordDebug()) {
+						record.println("Document streaming will not be used, since the column path contains an invalid reverse axis " + xmlColumn.getPath()); //$NON-NLS-1$
+					}
+					return false;
+				}
+			} else if (!Axis.isSubtreeAxis[axis]) {
+				if (axis == Axis.PARENT 
+						|| axis == Axis.ANCESTOR
+						|| axis == Axis.ANCESTOR_OR_SELF) {
+					if (current.getTarget().isReturnable()) {
+						if (record.recordDebug()) {
+							record.println("Document streaming will not be used, since the column path contains an invalid reverse axis " + xmlColumn.getPath()); //$NON-NLS-1$
+						}
+						return false;
+					}
+					ancestor = true; 
+				} else {
+					if (record.recordDebug()) {
+						record.println("Document streaming will not be used, since the column path may not reference an ancestor or subtree " + xmlColumn.getPath()); //$NON-NLS-1$
+					}
+					return false;
+				}
+			}
+	    	for (PathMapArc pathMapArc : current.getTarget().getArcs()) {
+	    		arcStack.add(pathMapArc);
+			}
+		}
+		return true;
+	}
+
 	private void addReturnedArcs(XMLColumn xmlColumn, PathMapNode subNode) {
 		if (xmlColumn.getSymbol().getType() == DataTypeManager.DefaultDataClasses.XML) {
 			subNode.createArc(new AxisExpression(Axis.DESCENDANT_OR_SELF, AnyNodeTest.getInstance()));
@@ -371,57 +466,7 @@
 		}
 	}
 	
-    public Result evaluateXQuery(Object context, Map<String, Object> parameterValues) throws TeiidProcessingException {
-        DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
-
-        Result result = new Result();
-        try {
-	        try {
-		        for (Map.Entry<String, Object> entry : parameterValues.entrySet()) {
-		            Object value = entry.getValue();
-		            if(value instanceof SQLXML) {                    
-		            	value = XMLSystemFunctions.convertToSource(value);
-		            	result.sources.add((Source)value);
-		            } else if (value instanceof java.util.Date) {
-		            	value = XMLSystemFunctions.convertToAtomicValue(value);
-		            }
-		            dynamicContext.setParameter(entry.getKey(), value);                
-		        }
-	        } catch (TransformerException e) {
-	        	throw new TeiidProcessingException(e);
-	        }
-	        if (context != null) {
-	        	Source source = XMLSystemFunctions.convertToSource(context);
-	        	result.sources.add(source);
-	            if (contextRoot != null) {
-	            	//create our own filter as this logic is not provided in the free saxon
-	                ProxyReceiver filter = new PathMapFilter(contextRoot);
-	                AugmentedSource sourceInput = AugmentedSource.makeAugmentedSource(source);
-	                sourceInput.addFilter(filter);
-	                source = sourceInput;
-	            }
-	            DocumentInfo doc;
-				try {
-					doc = config.buildDocument(source);
-				} catch (XPathException e) {
-					throw new TeiidProcessingException(e, QueryPlugin.Util.getString("SaxonXQueryExpression.bad_context")); //$NON-NLS-1$
-				}
-		        dynamicContext.setContextItem(doc);
-	        }
-	        try {
-	        	result.iter = xQuery.iterator(dynamicContext);
-	        	return result;
-	        } catch (TransformerException e) {
-	        	throw new TeiidProcessingException(e, QueryPlugin.Util.getString("SaxonXQueryExpression.bad_xquery")); //$NON-NLS-1$
-	        }       
-        } finally {
-        	if (result.iter == null) {
-        		result.close();
-        	}
-        }
-    }
-    
-	public XMLType createXMLType(final SequenceIterator iter, BufferManager bufferManager, boolean emptyOnEmpty) throws XPathException, TeiidComponentException, TeiidProcessingException {
+    public XMLType createXMLType(final SequenceIterator iter, BufferManager bufferManager, boolean emptyOnEmpty) throws XPathException, TeiidComponentException, TeiidProcessingException {
 		Item item = iter.next();
 		if (item == null && !emptyOnEmpty) {
 			return null;
@@ -429,17 +474,7 @@
 		XMLType.Type type = Type.CONTENT;
 		if (item instanceof NodeInfo) {
 			NodeInfo info = (NodeInfo)item;
-			switch (info.getNodeKind()) {
-				case net.sf.saxon.type.Type.DOCUMENT:
-					type = Type.DOCUMENT;
-					break;
-				case net.sf.saxon.type.Type.ELEMENT:
-					type = Type.ELEMENT;
-					break;
-				case net.sf.saxon.type.Type.TEXT:
-					type = Type.TEXT;
-					break;
-			}
+			type = getType(info);
 		}
 		Item next = iter.next();
 		if (next != null) {
@@ -450,17 +485,29 @@
 			@Override
 			public void translate(Writer writer) throws TransformerException,
 					IOException {
-				Properties props = new Properties();
-			    props.setProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
-			    //props.setProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
-			    props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$
-			    QueryResult.serializeSequence(iter.getAnother(), config, writer, props);
+			    QueryResult.serializeSequence(iter.getAnother(), config, writer, DEFAULT_OUTPUT_PROPERTIES);
 			}
 		});
 		XMLType value = new XMLType(xml);
 		value.setType(type);
 		return value;
 	}
+
+	public static XMLType.Type getType(NodeInfo info) {
+		switch (info.getNodeKind()) {
+			case net.sf.saxon.type.Type.DOCUMENT:
+				return Type.DOCUMENT;
+			case net.sf.saxon.type.Type.ELEMENT:
+				return Type.ELEMENT;
+			case net.sf.saxon.type.Type.TEXT:
+				return Type.TEXT;
+			case net.sf.saxon.type.Type.COMMENT:
+				return Type.COMMENT;
+			case net.sf.saxon.type.Type.PROCESSING_INSTRUCTION:
+				return Type.PI;
+		}
+		return Type.CONTENT;
+	}
     
     public Configuration getConfig() {
 		return config;
@@ -477,5 +524,9 @@
 			showArcs(sb, node, level + 1);
 		}
 	}
+	
+	public boolean isStreaming() {
+		return streamingPath != null;
+	}
 
 }

Copied: branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/StreamingUtils.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/xquery/saxon/StreamingUtils.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/StreamingUtils.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/StreamingUtils.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,302 @@
+/*
+ * 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 org.teiid.query.xquery.saxon;
+
+import java.io.IOException;
+import java.util.Map;
+
+import net.sf.saxon.AugmentedSource;
+import net.sf.saxon.Configuration;
+import net.sf.saxon.event.ContentHandlerProxy;
+import net.sf.saxon.event.PipelineConfiguration;
+import net.sf.saxon.event.ProxyReceiver;
+import net.sf.saxon.event.Receiver;
+import net.sf.saxon.om.Name11Checker;
+import net.sf.saxon.trans.XPathException;
+
+import org.xml.sax.ContentHandler;
+import org.xml.sax.DTDHandler;
+import org.xml.sax.EntityResolver;
+import org.xml.sax.ErrorHandler;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.SAXNotRecognizedException;
+import org.xml.sax.SAXNotSupportedException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.ext.LexicalHandler;
+
+final class StreamingUtils {
+	/**
+	 * Pre-parser that adds validation and handles a default name space
+	 * 
+	 * TODO: add support for more general paths including node tests
+	 *   this could be done as a secondary expression applied to the 
+	 *   context item 
+	 * 
+	 * @param locationPath
+	 * @param prefixMap
+	 * @return
+	 */
+	public static String getStreamingPath(String locationPath, Map<String, String> prefixMap) {
+		if (locationPath.indexOf("//") >= 0) //$NON-NLS-1$
+			throw new IllegalArgumentException("DESCENDANT axis is not supported"); //$NON-NLS-1$
+		
+		String path = locationPath.trim();
+		if (path.startsWith("/")) path = path.substring(1); //$NON-NLS-1$
+		if (path.endsWith("/")) path = path.substring(0, path.length() - 1); //$NON-NLS-1$
+		path = path.trim();
+		String[] localNames = path.split("/"); //$NON-NLS-1$
+		
+		if (localNames.length == 1) {
+			throw new IllegalArgumentException(locationPath + " refers to only the root element"); //$NON-NLS-1$
+		}
+
+		String fixedPath = ""; //$NON-NLS-1$
+				
+		// parse prefix:localName pairs and resolve prefixes to namespaceURIs
+		for (int i = 0; i < localNames.length; i++) {
+			fixedPath += "/"; //$NON-NLS-1$
+			int k = localNames[i].indexOf(':');
+			if (k >= 0 && localNames[i].indexOf(':', k+1) >= 0)
+				throw new IllegalArgumentException(
+					"QName must not contain more than one colon: " //$NON-NLS-1$
+					+ "qname='" + localNames[i] + "', path='" + path + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			if (k <= 0) {
+				fixedPath += " :"; //$NON-NLS-1$
+			} else {
+				String prefix = localNames[i].substring(0, k).trim();
+				if (k >= localNames[i].length() - 1)
+					throw new IllegalArgumentException(
+						"Missing localName for prefix: " + "prefix='" //$NON-NLS-1$ //$NON-NLS-2$
+						+ prefix + "', path='" + path + "', prefixes=" + prefixMap); //$NON-NLS-1$ //$NON-NLS-2$
+				fixedPath += prefix + ":"; //$NON-NLS-1$
+			} // end if
+			
+			localNames[i] = localNames[i].substring(k + 1).trim();
+			if (!localNames[i].equals("*") && !Name11Checker.getInstance().isValidNCName(localNames[i])) { //$NON-NLS-1$
+				throw new IllegalArgumentException(localNames[i] + " is not a valid local name."); //$NON-NLS-1$
+			}
+			fixedPath += localNames[i];
+		}
+		return fixedPath;
+	}
+
+}
+
+/**
+ * An {@link XMLReader} designed to bridge between the Saxon document projection logic and the XOM/NUX streaming logic.
+ */
+final class SaxonReader implements XMLReader {
+	
+	private ContentHandler handler;
+	private LexicalHandler lexicalHandler;
+	
+	private Configuration config;
+	private AugmentedSource source;
+	
+	public SaxonReader(Configuration config, AugmentedSource source) {
+		this.config = config;
+		this.source = source;
+	}
+	
+	@Override
+	public void setProperty(String name, Object value)
+			throws SAXNotRecognizedException, SAXNotSupportedException {
+		if ("http://xml.org/sax/properties/lexical-handler".equals(name)) { //$NON-NLS-1$
+			this.lexicalHandler = (LexicalHandler) value;
+		}
+	}
+
+	@Override
+	public void setFeature(String name, boolean value)
+			throws SAXNotRecognizedException, SAXNotSupportedException {
+	}
+
+	@Override
+	public void setErrorHandler(ErrorHandler handler) {
+		throw new UnsupportedOperationException();
+		
+	}
+
+	@Override
+	public void setEntityResolver(EntityResolver resolver) {
+		throw new UnsupportedOperationException();
+		
+	}
+
+	@Override
+	public void setDTDHandler(DTDHandler handler) {
+		
+	}
+
+	@Override
+	public void setContentHandler(ContentHandler handler) {
+		this.handler = handler;
+	}
+
+	@Override
+	public void parse(String systemId) throws IOException, SAXException {
+		throw new UnsupportedOperationException();
+	}
+
+	@Override
+	public void parse(InputSource input) throws IOException, SAXException {
+		ContentHandlerProxy chp = new ContentHandlerProxy();
+		chp.setLexicalHandler(lexicalHandler);
+		chp.setUnderlyingContentHandler(handler);
+		this.source.addFilter(new ContentHandlerProxyReceiver(chp));
+		try {
+			config.buildDocument(source);
+		} catch (XPathException e) {
+			throw new SAXException(e);
+		}
+	}
+
+	@Override
+	public Object getProperty(String name) throws SAXNotRecognizedException,
+			SAXNotSupportedException {
+		throw new UnsupportedOperationException();
+	}
+
+	@Override
+	public boolean getFeature(String name) throws SAXNotRecognizedException,
+			SAXNotSupportedException {
+		throw new UnsupportedOperationException();
+	}
+
+	@Override
+	public ErrorHandler getErrorHandler() {
+		return null;
+	}
+
+	@Override
+	public EntityResolver getEntityResolver() {
+		throw new UnsupportedOperationException();
+	}
+
+	@Override
+	public DTDHandler getDTDHandler() {
+		throw new UnsupportedOperationException();
+	}
+
+	@Override
+	public ContentHandler getContentHandler() {
+		return this.handler;
+	}
+
+}
+
+/**
+ * Adapts the {@link ContentHandlerProxy} to be a {@link ProxyReceiver}
+ */
+final class ContentHandlerProxyReceiver extends ProxyReceiver {
+	
+	private Receiver reciever;
+	
+	public ContentHandlerProxyReceiver(Receiver reciever) {
+		this.reciever = reciever; 
+	}
+
+	public void attribute(int nameCode, int typeCode, CharSequence value,
+			int locationId, int properties) throws XPathException {
+		reciever.attribute(nameCode, typeCode, value, locationId,
+				properties);
+	}
+
+	public void characters(CharSequence chars, int locationId,
+			int properties) throws XPathException {
+		reciever.characters(chars, locationId, properties);
+	}
+
+	public void close() throws XPathException {
+		reciever.close();
+		super.close();
+	}
+
+	public void comment(CharSequence content, int locationId, int properties)
+			throws XPathException {
+		reciever.comment(content, locationId, properties);
+	}
+
+	public void endDocument() throws XPathException {
+		reciever.endDocument();
+		super.endDocument() ;
+	}
+
+	public void endElement() throws XPathException {
+		reciever.endElement();
+	}
+
+	public PipelineConfiguration getPipelineConfiguration() {
+		return reciever.getPipelineConfiguration();
+	}
+
+	public String getSystemId() {
+		return reciever.getSystemId();
+	}
+
+	public void namespace(int namespaceCode, int properties)
+			throws XPathException {
+		reciever.namespace(namespaceCode, properties);
+	}
+
+	public void open() throws XPathException {
+		super.open();
+		reciever.open();
+	}
+
+	public void processingInstruction(String name, CharSequence data,
+			int locationId, int properties) throws XPathException {
+		reciever.processingInstruction(name, data, locationId, properties);
+	}
+
+	public void setPipelineConfiguration(PipelineConfiguration config) {
+		reciever.setPipelineConfiguration(config);
+		super.setPipelineConfiguration(config);
+	}
+
+	public void setSystemId(String systemId) {
+		reciever.setSystemId(systemId);
+		super.setSystemId(systemId);
+	}
+
+	public void setUnparsedEntity(String name, String systemID,
+			String publicID) throws XPathException {
+		reciever.setUnparsedEntity(name, systemID, publicID);
+	}
+
+	public void startContent() throws XPathException {
+		reciever.startContent();
+	}
+
+	public void startDocument(int properties) throws XPathException {
+		super.startDocument(properties);
+		reciever.startDocument(properties);
+	}
+
+	public void startElement(int nameCode, int typeCode, int locationId,
+			int properties) throws XPathException {
+		reciever.startElement(nameCode, typeCode, locationId, properties);
+	}
+	
+}
\ No newline at end of file

Copied: branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/XQueryEvaluator.java (from rev 3382, trunk/engine/src/main/java/org/teiid/query/xquery/saxon/XQueryEvaluator.java)
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/XQueryEvaluator.java	                        (rev 0)
+++ branches/as7/engine/src/main/java/org/teiid/query/xquery/saxon/XQueryEvaluator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,177 @@
+/*
+ * 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 org.teiid.query.xquery.saxon;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.SQLXML;
+import java.util.Map;
+
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerException;
+
+import net.sf.saxon.AugmentedSource;
+import net.sf.saxon.Configuration;
+import net.sf.saxon.event.ProxyReceiver;
+import net.sf.saxon.om.DocumentInfo;
+import net.sf.saxon.om.NodeInfo;
+import net.sf.saxon.query.DynamicQueryContext;
+import net.sf.saxon.trans.XPathException;
+import nu.xom.Builder;
+import nu.xom.DocType;
+import nu.xom.Element;
+import nu.xom.Node;
+import nu.xom.Nodes;
+import nu.xom.ParsingException;
+import nux.xom.xquery.StreamingPathFilter;
+import nux.xom.xquery.StreamingTransform;
+
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.logging.LogConstants;
+import org.teiid.logging.LogManager;
+import org.teiid.logging.MessageLevel;
+import org.teiid.query.QueryPlugin;
+import org.teiid.query.function.source.XMLSystemFunctions;
+import org.teiid.query.util.CommandContext;
+import org.teiid.query.xquery.saxon.SaxonXQueryExpression.RowProcessor;
+
+/**
+ * Used to isolate the xom/nux dependency and to better isolate the saxon processing logic.
+ */
+public class XQueryEvaluator {
+	
+	private static Nodes NONE = new Nodes(); 
+	private static InputStream FAKE_IS = new InputStream() {
+
+		@Override
+		public int read() throws IOException {
+			return 0;
+		}
+	};
+
+	public static SaxonXQueryExpression.Result evaluateXQuery(final SaxonXQueryExpression xquery, Object context, Map<String, Object> parameterValues, final RowProcessor processor, CommandContext commandContext) throws TeiidProcessingException {
+	    DynamicQueryContext dynamicContext = new DynamicQueryContext(xquery.config);
+	
+	    SaxonXQueryExpression.Result result = new SaxonXQueryExpression.Result();
+	    try {
+	        try {
+		        for (Map.Entry<String, Object> entry : parameterValues.entrySet()) {
+		            Object value = entry.getValue();
+		            if(value instanceof SQLXML) {                    
+		            	value = XMLSystemFunctions.convertToSource(value);
+		            	result.sources.add((Source)value);
+		            } else if (value instanceof java.util.Date) {
+		            	value = XMLSystemFunctions.convertToAtomicValue(value);
+		            }
+		            dynamicContext.setParameter(entry.getKey(), value);                
+		        }
+	        } catch (TransformerException e) {
+	        	throw new TeiidProcessingException(e);
+	        }
+	        if (context != null) {
+	        	Source source = XMLSystemFunctions.convertToSource(context);
+	        	result.sources.add(source);
+	            if (xquery.contextRoot != null) {
+	            	//create our own filter as this logic is not provided in the free saxon
+	                ProxyReceiver filter = new PathMapFilter(xquery.contextRoot);
+	                AugmentedSource sourceInput = AugmentedSource.makeAugmentedSource(source);
+	                sourceInput.addFilter(filter);
+	                source = sourceInput;
+	
+	            	//use streamable processing instead
+	                if (xquery.streamingPath != null && processor != null) {
+	                	if (LogManager.isMessageToBeRecorded(LogConstants.CTX_DQP, MessageLevel.DETAIL)) {
+	                		LogManager.logDetail(LogConstants.CTX_DQP, "Using stream processing for evaluation of", xquery.xQueryString); //$NON-NLS-1$
+	                	}
+	                	//set to non-blocking in case default expression evaluation blocks
+	                	boolean isNonBlocking = commandContext.isNonBlocking();
+						commandContext.setNonBlocking(true);
+						
+						final StreamingTransform myTransform = new StreamingTransform() {
+							public Nodes transform(Element elem) {
+								processor.processRow(XQueryEvaluator.wrap(elem, xquery.config));
+								return NONE;
+							}
+						};
+						
+						Builder builder = new Builder(new SaxonReader(xquery.config, sourceInput), false, 
+								new StreamingPathFilter(xquery.streamingPath, xquery.namespaceMap).createNodeFactory(null, myTransform));
+						try {
+							//the builder is hard wired to parse the source, but the api will throw an exception if the stream is null
+							builder.build(FAKE_IS);
+							return result;
+						} catch (ParsingException e) {
+							throw new TeiidProcessingException(e, QueryPlugin.Util.getString("SaxonXQueryExpression.bad_context")); //$NON-NLS-1$
+						} catch (IOException e) {
+							throw new TeiidProcessingException(e, QueryPlugin.Util.getString("SaxonXQueryExpression.bad_context")); //$NON-NLS-1$
+						} finally {
+							if (!isNonBlocking) {
+								commandContext.setNonBlocking(false);
+							}
+						}
+	                }
+	            }
+	            DocumentInfo doc;
+				try {
+					doc = xquery.config.buildDocument(source);
+				} catch (XPathException e) {
+					throw new TeiidProcessingException(e, QueryPlugin.Util.getString("SaxonXQueryExpression.bad_context")); //$NON-NLS-1$
+				}
+		        dynamicContext.setContextItem(doc);
+	        }
+	        try {
+	        	result.iter = xquery.xQuery.iterator(dynamicContext);
+	        	return result;
+	        } catch (TransformerException e) {
+	        	throw new TeiidProcessingException(e, QueryPlugin.Util.getString("SaxonXQueryExpression.bad_xquery")); //$NON-NLS-1$
+	        }       
+	    } finally {
+	    	if (result.iter == null) {
+	    		result.close();
+	    	}
+	    }
+	}
+
+	/**
+	 * Converts a xom node into something readable by Saxon
+	 * @param node
+	 * @param config
+	 * @return
+	 */
+	static NodeInfo wrap(Node node, Configuration config) {
+		if (node == null) 
+			throw new IllegalArgumentException("node must not be null"); //$NON-NLS-1$
+		if (node instanceof DocType)
+			throw new IllegalArgumentException("DocType can't be queried by XQuery/XPath"); //$NON-NLS-1$
+		
+		Node root = node;
+		while (root.getParent() != null) {
+			root = root.getParent();
+		}
+	
+		DocumentWrapper docWrapper = new DocumentWrapper(root, root.getBaseURI(), config);
+		
+		return docWrapper.wrap(node);
+	}
+
+}

Modified: branches/as7/engine/src/main/java/org/teiid/security/Credentials.java
===================================================================
--- branches/as7/engine/src/main/java/org/teiid/security/Credentials.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/java/org/teiid/security/Credentials.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,7 +26,9 @@
 
 public class Credentials implements Serializable {
     
-    private char[] credentials = null;
+	private static final long serialVersionUID = 7453114713211221240L;
+	
+	private char[] credentials = null;
     
     /**
      * Construct a new PasswordCredentials 

Modified: branches/as7/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj
===================================================================
--- branches/as7/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/javacc/org/teiid/query/parser/SQLParser.jj	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,6 +23,7 @@
 import org.teiid.query.sql.symbol.*;
 import org.teiid.metadata.*;
 import org.teiid.metadata.BaseColumn.NullType;
+import org.teiid.language.Like.MatchMode;
 
 /** 
  * <p>The SQLParser is a JavaCC-generated parser that reads a SQL string and produces a 
@@ -192,7 +193,9 @@
 |   <LANGUAGE: "language">
 |   <LARGE: "large">
 |   <LEADING: "leading">
+|   <LEAVE: "leave">
 |   <LIKE: "like">
+|   <LIKE_REGEX: "like_regex">
 |   <LIMIT: "limit">
 |   <LOCAL: "local">
 |   <LOOP: "loop">
@@ -213,6 +216,7 @@
 |   <NOT: "not">
 |   <NULL: "null">
 |   <OF: "of">
+|   <OFFSET: "offset">
 |   <OLD: "old">
 |   <ON: "on">
 |   <ONLY: "only">
@@ -406,6 +410,7 @@
 |   <QMARK: "?">
 |   <DOLLAR: "$">
 |   <SEMICOLON: ";">
+|   <COLON: ":">
 |	<CONCAT_OP: "||">
 }
 
@@ -510,7 +515,7 @@
 {
   	String target = null;
   	QueryCommand command = null;
-  	Block block = null;
+  	Statement stmt = null;
   	TriggerAction triggerAction = null;
   	Token comment = null;
   	Token event = null;
@@ -529,9 +534,9 @@
 	 		alterView.setDefinition(command);
 	 		return alterView;	
 	 	}
-		| (<PROCEDURE> target = id() <AS> { comment = getToken(1).specialToken; } block = block(info)) 
+		| (<PROCEDURE> target = id() <AS> { comment = getToken(1).specialToken; } stmt = statement(info)) 
 		{
-			CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(block);
+			CreateUpdateProcedureCommand cup = new CreateUpdateProcedureCommand(asBlock(stmt));
 			cup.setUpdateProcedure(false);
 			if (comment != null) {
 		 	    cup.setCacheHint(getQueryCacheOption(comment.image));
@@ -560,11 +565,29 @@
 
 TriggerAction forEachRowTriggerAction(ParseInfo info) :
 {
-	Block b = null;
+	Block b = new Block();
+	b.setAtomic(true);
+	Statement stmt = null;
 }
 {
 	<FOR> <EACH> <ROW>
-	b = block(info)
+	(
+	 LOOKAHEAD(1) (<BEGIN> [<ATOMIC>]
+      (
+	    stmt = statement(info)
+	    {          
+    	    b.addStatement(stmt);            	                	    
+	    }
+      )*
+      <END> 
+     )
+     |
+     stmt = statement(info)
+     {
+       b = asBlock(stmt);
+       b.setAtomic(true);
+     }
+    ) 
 	{
 		return new TriggerAction(b);
 	}
@@ -713,12 +736,25 @@
 Statement statement(ParseInfo info) :
 {
     Statement stmt = null;
+    String label = null;
 }
 {
-    (stmt = ifStatement(info) |
-	 stmt = loopStatement(info) |
-	 stmt = whileStatement(info) |
-	 stmt = delimitedStatement(info)
+    (
+	 LOOKAHEAD(2) ([label = id() <COLON>] 
+	  (
+	   stmt = loopStatement(info) |
+	   stmt = whileStatement(info) |
+	   stmt = compoundStatement(info)
+	  )
+	  {
+	  	((Statement.Labeled)stmt).setLabel(label);
+	  }
+	 )
+	 |
+	 (
+      stmt = ifStatement(info) |
+      stmt = delimitedStatement(info)
+	 )
 	)
     
     {
@@ -735,8 +771,7 @@
 	  stmt = sqlStatement(info) |
       stmt = errorStatement(info) |
 	  stmt = declareStatement(info) |
-	  stmt = continueStatement(info) |
-	  stmt = breakStatement(info)
+	  stmt = branchingStatement(info)
 	 )
 	 <SEMICOLON>
 	 {
@@ -744,32 +779,25 @@
 	 }
 }
 
-/**
- * Parse block
- * @throws ParseException
- */
-Block block(ParseInfo info) :
+Block compoundStatement(ParseInfo info) :
 {
     Statement stmt = null;  
     Block block = new Block();
+    Boolean atomic = null;
 }
 {   
-	(      
-    	stmt = statement(info)
-    	{
-        	block.addStatement(stmt);	
-    	}
-        |
-        (<BEGIN>
-            (
-        	    stmt = statement(info)
-        	    {          
-            	    block.addStatement(stmt);            	                	    
-        	    }
-    	   )*
-        <END>)    
-     )           
+    <BEGIN> [[<NOT> {atomic = Boolean.FALSE;}] <ATOMIC> {if (atomic == null) {atomic = Boolean.TRUE;}}]
+    (
+      stmt = statement(info)
+      {          
+	    block.addStatement(stmt);            	                	    
+	  }
+ 	)*
+    <END>
     {
+        if (atomic != null) {
+        	block.setAtomic(atomic);
+        }
         return block;
     }
 }        
@@ -778,37 +806,28 @@
  * Parse break statement 
  * @throws ParseException if parsing failed
  */
-BreakStatement breakStatement(ParseInfo info) :
+BranchingStatement branchingStatement(ParseInfo info) :
 {
-    BreakStatement breakStmt = null;      
+    BranchingStatement breakStmt = new BranchingStatement();
+    Token mode = null;
+    String label = null;
 }
 {
- 	<BREAK>
+ 	(
+ 	 (
+ 	  (mode = <BREAK> | mode = <CONTINUE>) [label = id()] 
+ 	 )
+ 	 | 
+ 	 (mode = <LEAVE> label = id())
+ 	)
  	{
- 		breakStmt = new BreakStatement();
- 		
+ 	    breakStmt.setMode(BranchingStatement.BranchingMode.valueOf(mode.image.toUpperCase()));
+ 	    breakStmt.setLabel(label);
  		return breakStmt;
  	}
 } 	
 
 /**
- * Parse break statement 
- * @throws ParseException if parsing failed
- */
-ContinueStatement continueStatement(ParseInfo info) :
-{
-    ContinueStatement contStmt = null;      
-}
-{
- 	<CONTINUE>
- 	{
- 		contStmt = new ContinueStatement();
- 		
- 		return contStmt;
- 	}
-} 	
-
-/**
  * Parse while statement 
  * @throws ParseException if parsing failed
  */
@@ -816,18 +835,16 @@
 {
     WhileStatement whileStmt = null;    
     Criteria criteria = null;
-    Block block = null;
+    Statement stmt = null;
 }
 {
     <WHILE>
     <LPAREN>  
     criteria = criteria(info)
     <RPAREN>
-    block = block(info)
-    
+    stmt = statement(info)
     {
-        whileStmt = new WhileStatement(criteria, block);   
-
+        whileStmt = new WhileStatement(criteria, asBlock(stmt));   
         return whileStmt;
     }    
 }    
@@ -841,7 +858,7 @@
     LoopStatement loopStmt = null;    
     String cursor = null;
     QueryCommand query = null;
-    Block block = null;
+    Statement stmt = null;
 }
 {
     <LOOP>
@@ -851,11 +868,9 @@
     <RPAREN>
     <AS>
     cursor = id()
-    block = block(info)
-    
+    stmt = statement(info)
     {
-        loopStmt = new LoopStatement(block, query, cursor);   
-
+        loopStmt = new LoopStatement(asBlock(stmt), query, cursor);   
         return loopStmt;
     }    
 }   
@@ -868,21 +883,20 @@
 {
     IfStatement ifStmt = null;    
     Criteria criteria = null;
-    Block ifBlock = null;
-    Block elseBlock = null;
+    Statement ifStatement = null;
+    Statement elseStatement = null;
 }
 {
     <IF>
     <LPAREN>  
     criteria = criteria(info)
     <RPAREN>
-    ifBlock = block(info)
+    ifStatement = statement(info)
     //else blocks will be associated with the closest if block
-    [LOOKAHEAD(1)<ELSE> elseBlock = block(info)]
-    
+    [LOOKAHEAD(1)<ELSE> elseStatement = statement(info)]
     {
-        ifStmt = new IfStatement(criteria, ifBlock);
-        ifStmt.setElseBlock(elseBlock);
+        ifStmt = new IfStatement(criteria, asBlock(ifStatement));
+        ifStmt.setElseBlock(asBlock(elseStatement));
         return ifStmt;
     }    
 }    
@@ -896,7 +910,7 @@
     CriteriaSelector critSelector = new CriteriaSelector();
     
     String element = null;
-    List elements = new ArrayList();
+    List elements = new ArrayList(2);
     Token operator = null;
 }
 {
@@ -1109,7 +1123,7 @@
 
         [<WITH>
          {
-            critList = new ArrayList();
+            critList = new ArrayList(2);
          }
          <LPAREN>
         element = id()
@@ -1160,16 +1174,16 @@
 {
     CreateUpdateProcedureCommand updateProcCmd = 
         new CreateUpdateProcedureCommand();
-    Block block = null;  
+    Statement stmt = null;  
 }
 { 
     <CREATE> [<VIRTUAL> {updateProcCmd.setUpdateProcedure(false);}] 
     [<UPDATE>] 
     <PROCEDURE>
 
-    block = block(info)
+    stmt = statement(info)
     {        
-        updateProcCmd.setBlock(block);
+        updateProcCmd.setBlock(asBlock(stmt));
         return updateProcCmd;        
     }    
 }   
@@ -1480,8 +1494,9 @@
 	}]
 
 	(
-		( <VALUES>
-		  values = rowValues(info)
+		( <VALUES> <LPAREN>
+		  values = expressionList(info)
+		  <RPAREN>
 		  {
 		    // Store each row of values
 		    insert.setValues(values);
@@ -1543,13 +1558,12 @@
  * @return List of values, never null
  * @throws ParseException if parsing failed
  */
-List rowValues(ParseInfo info) :
+ArrayList<Expression> expressionList(ParseInfo info) :
 {
-	List rowVals = new ArrayList();
+	ArrayList<Expression> rowVals = new ArrayList<Expression>(4);
 	Expression value = null;
 }
 {
-	<LPAREN>
 	value = expression(info)
 	{
         rowVals.add(value);
@@ -1560,8 +1574,6 @@
             rowVals.add(value);
 	    }
 	)*
-	<RPAREN>
-
 	{
 		return rowVals;
 	}
@@ -1741,7 +1753,7 @@
         query=query(info) | 
         (<TABLE> name=id() {
            Query q = new Query();
-           q.setSelect(new Select(Arrays.asList(new AllSymbol())));
+           q.setSelect(new Select(Arrays.asList(new MultipleElementSymbol())));
            q.setFrom(new From(Arrays.asList(new UnaryFromClause(new GroupSymbol(name)))));
            query = q;
         }) |
@@ -1821,14 +1833,13 @@
 	boolean isDistinct = false;		// unless DISTINCT keyword in SELECT
 	SelectSymbol symbol = null;
 	Select select = new Select();
-	info.aggregatesAllowed = true;
 }
 {
 	<SELECT>
 	[<ALL> | (<DISTINCT> {isDistinct=true;})]
 	(<STAR>
 		{
-			select.addSymbol(new AllSymbol());
+			select.addSymbol(new MultipleElementSymbol());
 		}
 	|
 		(	symbol=selectSymbol(info)      { select.addSymbol(symbol); }
@@ -1838,7 +1849,6 @@
 		)
 	)		
 	{
-		info.aggregatesAllowed = false;	
  		select.setDistinct(isDistinct);
 		return select;
 	}
@@ -1872,17 +1882,11 @@
 	)
 	{		
 		SingleElementSymbol es = null;
-		if(expression instanceof ElementSymbol) {
-			es = (ElementSymbol) expression;
+		if(!(expression instanceof SingleElementSymbol)) {
+			String functionName = generateFunctionName(info, null);
+			es = new ExpressionSymbol(functionName, expression);
 		} else {
-			String func = null;
-			if(expression instanceof AggregateSymbol) {
-		    	es = (AggregateSymbol)expression;
-		    	func = ((AggregateSymbol)expression).getAggregateFunction().name();
-			} else {
-				String functionName = generateFunctionName(info, null);
-				es = new ExpressionSymbol(functionName, expression);
-			}
+		    es = (SingleElementSymbol)expression;
 		}
 		if(alias != null) {
 			alias = validateAlias(alias); 
@@ -1911,7 +1915,7 @@
 	}
 }
 
-AllInGroupSymbol allInGroupSymbol() :
+MultipleElementSymbol allInGroupSymbol() :
 {
 	Token allInGroupToken = null;
 	
@@ -1919,59 +1923,34 @@
 {
    	allInGroupToken = <ALL_IN_GROUP>    
     {
-		return new AllInGroupSymbol(normalizeId(allInGroupToken.image));
+		return new MultipleElementSymbol(normalizeId(allInGroupToken.image.substring(0, allInGroupToken.image.length() - 2)));
 	}
 }
 
-AggregateSymbol xmlAgg(ParseInfo info) :
+AggregateSymbol orderedAgg(ParseInfo info) :
 {
+    Token t = null;
 	Expression expression = null;
 	OrderBy orderBy = null;
+	Expression condition = null;
 }
 {
-	<XMLAGG> <LPAREN>
+	(t=<XMLAGG>|t=<ARRAY_AGG>)
+	<LPAREN>
 	expression = expression(info)
-	[
-		orderBy = orderby(info)
-	]
+	[ orderBy = orderby(info) ]
 	<RPAREN>
+	condition = filterClause(info)
 	{
-		if(! info.aggregatesAllowed) {
-			throw new ParseException(QueryPlugin.Util.getString("SQLParser.Aggregate_only_top_level")); //$NON-NLS-1$
-		}
-		
-		String name = generateFunctionName(info, "XMLAGG");
-		AggregateSymbol	agg = new AggregateSymbol(name, "XMLAGG", false, expression);
+		String aggName = t.image.toUpperCase();
+		String name = generateFunctionName(info, aggName);
+		AggregateSymbol	agg = new AggregateSymbol(name, aggName, false, expression);
 		agg.setOrderBy(orderBy);
+		agg.setCondition(condition);
 		return agg;
 	}
 }
 
-AggregateSymbol arrayAgg(ParseInfo info) :
-{
-	Expression expression = null;
-	OrderBy orderBy = null;
-}
-{
-	<ARRAY_AGG> <LPAREN>
-	expression = expression(info)
-	[
-		orderBy = orderby(info)
-	]
-	<RPAREN>
-	{
-		if(! info.aggregatesAllowed) {
-			throw new ParseException(QueryPlugin.Util.getString("SQLParser.Aggregate_only_top_level")); //$NON-NLS-1$
-		}
-		
-		String name = generateFunctionName(info, "ARRAY_AGG");
-		AggregateSymbol	agg = new AggregateSymbol(name, "ARRAY_AGG", false, expression);
-		agg.setOrderBy(orderBy);
-		return agg;
-	}
-}
-
-
 AggregateSymbol textAgg(ParseInfo info) :
 {
 	DerivedColumn expression = null;
@@ -1981,6 +1960,7 @@
 	List<DerivedColumn> expressions = new ArrayList<DerivedColumn>();
 	OrderBy orderBy = null;
 	String encoding = null;
+	Expression condition = null;
 }
 {
 	nonReserved("TEXTAGG") <LPAREN>
@@ -2014,20 +1994,18 @@
 		orderBy = orderby(info)
 	]	
 	<RPAREN>
+	condition = filterClause(info)
 	{
-		if(! info.aggregatesAllowed) {
-			throw new ParseException(QueryPlugin.Util.getString("SQLParser.Aggregate_only_top_level")); //$NON-NLS-1$
-		}
-			
 		TextLine tf = new TextLine();
 		tf.setDelimiter(delimiter);
 		tf.setQuote(quote);
 		tf.setIncludeHeader(header);
 		tf.setExpressions(expressions);
 		tf.setEncoding(encoding);
-		String name = generateFunctionName(info, "TEXTAGG");
+        String name = generateFunctionName(info, "TEXTAGG");
 		AggregateSymbol agg = new AggregateSymbol(name, "TEXTAGG", false, tf);
 		agg.setOrderBy(orderBy);
+		agg.setCondition(condition);
 		return agg;		
 	}
 }
@@ -2039,16 +2017,18 @@
 	AggregateSymbol agg = null;
 	boolean isDistinct = false;
 	Expression expression = null;
+	Expression condition = null;
 }
 {
 	(
 		// COUNT(*)
-		LOOKAHEAD(3) (
+		(LOOKAHEAD(3) (
 			func = nonReserved("COUNT")
 			<LPAREN>
 			starToken = <STAR>
 			<RPAREN> )	|
-			
+		LOOKAHEAD(<ID>, {matchesAny(getToken(1).image, "rank", "dense_rank", "row_number") != null}) (func = nonReserved("row_number", "rank", "dense_rank", "percent_rank", "cume_dist")
+			<LPAREN> <RPAREN>) |
 		// Remaining aggregates
 		(	(func = nonReserved("COUNT", "SUM", "AVG", "MIN", "MAX", "EVERY", "STDDEV_POP", "STDDEV_SAMP", "VAR_SAMP", "VAR_POP") 
 				|
@@ -2060,12 +2040,10 @@
 			[ <DISTINCT> {isDistinct=true;} | <ALL>]
 			expression = expression(info)
 			<RPAREN>
-		) 
+		)) 
+		condition = filterClause(info)
 	)
 	{
-		if(! info.aggregatesAllowed) {
-			throw new ParseException(QueryPlugin.Util.getString("SQLParser.Aggregate_only_top_level")); //$NON-NLS-1$
-		}
 		func = func.toUpperCase();
 		String name = generateFunctionName(info, func);
 		if(starToken == null) { 
@@ -2075,10 +2053,22 @@
 			// COUNT(*)			
 			agg = new AggregateSymbol(name, func, false, null);
 		}
+		agg.setCondition(condition);
 		return agg;
 	}
 }
 
+Expression filterClause(ParseInfo info) :
+{
+	Expression condition = null;
+}
+{
+	[ <FILTER> <LPAREN> <WHERE> condition = booleanPrimary(info) <RPAREN> ]
+	{
+		return condition;	
+	}
+}
+
 /**
  * <p>Parse a FROM.  The from must handle groups, aliased groups or
  * joined groups. This also handles JDBC escape processinf syntax for outer joins.</p>
@@ -2297,6 +2287,7 @@
 	Expression file = null;
 	TextTable.TextColumn column = null;
 	List<TextTable.TextColumn> columns = new ArrayList<TextTable.TextColumn>();
+	boolean useRowDelimiter = true;
 	Character delimiter = null;
 	boolean escape = false;
 	Character quote = null;
@@ -2318,6 +2309,12 @@
 		}
 	)* 
 	[
+	  <NO> <ROW> nonReserved("DELIMITER")
+	  {
+	    useRowDelimiter = false;
+	  }
+	]
+	[
 	  LOOKAHEAD(<ID>, { "delimiter".equalsIgnoreCase(getToken(1).image) }) <ID>
 	  delimiter = charVal(info, "DELMITER")
 	]
@@ -2354,6 +2351,7 @@
  		result.setSkip(skip);
  		result.setName(validateAlias(aliasID));
  		result.setQuote(quote);
+ 		result.setUsingRowDelimiter(useRowDelimiter);
  		return result;
  	}
 }
@@ -2363,6 +2361,7 @@
 	String name = null;
 	Constant datatype = null;
 	Integer width = null;
+	boolean noTrim = false;
 }
 {
 	name = id()
@@ -2370,9 +2369,15 @@
 	[ 
 	  	LOOKAHEAD(<ID>, { "width".equalsIgnoreCase(getToken(1).image) }) <ID>
 	  	width = intVal() 
+	  	[ LOOKAHEAD(2)
+		  	<NO> nonReserved("TRIM")
+		  	{
+				noTrim = true;	  	
+		  	}
+		]
 	]
 	{
-		return new TextTable.TextColumn(validateElementName(name), (String)datatype.getValue(), width);
+		return new TextTable.TextColumn(validateElementName(name), (String)datatype.getValue(), width, noTrim);
 	}
 }
 
@@ -2630,7 +2635,7 @@
  */
 Criteria compoundCritOr(ParseInfo info) :
 {
-    ArrayList logicList = new ArrayList();
+    ArrayList logicList = new ArrayList(2);
     Criteria logicPart = null;
 }
 {
@@ -2653,7 +2658,7 @@
  */
 Criteria compoundCritAnd(ParseInfo info) :
 {
-    ArrayList logicList = new ArrayList();
+    ArrayList logicList = new ArrayList(2);
     Criteria logicPart = null;
 }
 {
@@ -2676,14 +2681,20 @@
  */
 Criteria notCrit(ParseInfo info) :
 {
-    Criteria crit = null;
+    Expression ex = null;
 	boolean isNot = false;
 }
 {
 	[<NOT> {isNot=true;}] 
-	crit=booleanPrimary(info)
+	ex=booleanPrimary(info)
 
 	{
+	    Criteria crit = null;
+	    if (ex instanceof Criteria) {
+	      crit = (Criteria)ex;
+	    } else {
+	      crit = new ExpressionCriteria(ex);
+	    }
   		if(isNot) { 
   			return new NotCriteria(crit);
 		} else {
@@ -2697,38 +2708,31 @@
  * @return criteria
  * @throws ParseException if parsing failed
  */
-Criteria booleanPrimary(ParseInfo info) :
+Expression booleanPrimary(ParseInfo info) :
 {
     Expression ex = null;
-    Criteria crit = null;
 }
 {
     (
-		LOOKAHEAD(2) crit = translateCriteria(info)
+		LOOKAHEAD(2) ex = translateCriteria(info)
 		|
 	    (ex = commonValueExpression(info)
-	     {
-		  	 if (ex instanceof Criteria) {
-		  	 	crit = (Criteria)ex;
-		  	 } else {
-		     	crit = new ExpressionCriteria(ex);
-		     }
-	     }
 	     [(
-			LOOKAHEAD(2) crit=betweenCrit(info, ex) |
-			LOOKAHEAD(2) crit=matchCrit(info, ex) |
-			crit=setCrit(info, ex) |
-			crit=isNullCrit(info, ex) |
-			LOOKAHEAD(operator() (<ANY>|<SOME>|<ALL>) subquery(info)) crit=subqueryCompareCriteria(info, ex) |
-			crit=compareCrit(info, ex)
+			LOOKAHEAD(2) ex=betweenCrit(info, ex) |
+			LOOKAHEAD(2) ex=matchCrit(info, ex) |
+			LOOKAHEAD(2) ex=regexMatchCrit(info, ex) |
+			ex=setCrit(info, ex) |
+			ex=isNullCrit(info, ex) |
+			LOOKAHEAD(operator() (<ANY>|<SOME>|<ALL>) subquery(info)) ex=subqueryCompareCriteria(info, ex) |
+			ex=compareCrit(info, ex)
 	     )]
 	    )
 	    |
-		crit=existsCriteria(info) |
-		crit = hasCriteria() 
+		ex=existsCriteria(info) |
+		ex = hasCriteria() 
     )
 	{
-		return crit;
+		return ex;
 	}
 }
 
@@ -2792,7 +2796,7 @@
 		proc = storedProcedure(info, new StoredProcedure()) //deprecated	  
 	 )
 	 {
-	    subquery = new Query(new Select(Arrays.asList(new AllSymbol())), new From(Arrays.asList(new SubqueryFromClause("x", proc))), null, null, null);
+	    subquery = new Query(new Select(Arrays.asList(new MultipleElementSymbol())), new From(Arrays.asList(new SubqueryFromClause("x", proc))), null, null, null);
 	 }
 	)
 	<RPAREN>
@@ -2866,13 +2870,14 @@
     Character esc = null;
 	Expression value = null;
 	boolean negated = false;
+	boolean similar = false;
 }
 {
 	[<NOT> {negated = true;}]
-    <LIKE>
+    (<LIKE>|(<SIMILAR> <TO> {similar = true;}))
 	value=commonValueExpression(info)
-    [   <ESCAPE> esc = charVal(info, "LIKE ESCAPE") |
-        (<LBRACE> <ESCAPE> esc = charVal(info, "LIKE ESCAPE") <RBRACE>) 
+    [   <ESCAPE> esc = charVal(info, "LIKE/SIMILAR TO ESCAPE") |
+        (<LBRACE> <ESCAPE> esc = charVal(info, "LIKE/SIMILAR TO ESCAPE") <RBRACE>) 
     ]
 	{
     	MatchCriteria matchcriteria = new MatchCriteria(expression, value);
@@ -2880,10 +2885,28 @@
 	    if(esc != null) {
 			matchcriteria.setEscapeChar(esc.charValue());
 		}
+		matchcriteria.setMode(similar?MatchMode.SIMILAR:MatchMode.LIKE);
 		return matchcriteria;
    	}
 }
 
+MatchCriteria regexMatchCrit(ParseInfo info, Expression expression) :
+{
+	Expression value = null;
+	boolean negated = false;
+}
+{
+	[<NOT> {negated = true;}]
+    <LIKE_REGEX>
+	value=commonValueExpression(info)
+	{
+    	MatchCriteria matchcriteria = new MatchCriteria(expression, value);
+		matchcriteria.setNegated(negated);
+		matchcriteria.setMode(MatchMode.REGEX);
+		return matchcriteria;
+   	}
+}
+
 Character charVal(ParseInfo info, String type) :
 {
 	String escStr = null;
@@ -3017,53 +3040,17 @@
  */
 GroupBy groupBy(ParseInfo info) :
 {
-	GroupBy groupBy = new GroupBy();
-	SingleElementSymbol symbol = null;
+	List<Expression> expressions = null;
 }
 {
 	<GROUP> <BY>
-	(	symbol = groupByItem(info)
-		{
-			groupBy.addSymbol(symbol);
-		}
-		
-		(<COMMA> symbol = groupByItem(info)
-			{
-				groupBy.addSymbol(symbol);
-			}
-		)*
-	)
+    expressions = expressionList(info)	
 	{
-		return groupBy;
+		return new GroupBy(expressions);
 	}
 }
 
 /**
- * <p>Parse a GROUP BY list item.  </p>
- * @return Parsed group by item
- * @throws ParseException if parsing failed
- */
-SingleElementSymbol groupByItem(ParseInfo info) :
-{
-	Expression expr = null;
-	SingleElementSymbol symbol = null;
-}
-{
-	expr = expression(info)
-	{
-		if(expr instanceof ElementSymbol) {
-			symbol = (ElementSymbol) expr;
-		} else {
-			String exprName = generateFunctionName(info, null);
-			symbol = new ExpressionSymbol(exprName, expr);
-		}
-	}
-	{
-		return symbol;
-	}
-}
-
-/**
  * <p>Parse a HAVING clause.  </p>
  * @return Parsed having
  * @throws ParseException if parsing failed
@@ -3071,14 +3058,11 @@
 Criteria having(ParseInfo info) :
 {
     Criteria criteria = null;
-	info.aggregatesAllowed = true;
 }
 {
     <HAVING>
 	criteria = criteria(info)
-	
 	{
-		info.aggregatesAllowed = false;
 		return criteria;
 	}
 }
@@ -3157,41 +3141,63 @@
     }
 }
 
+Expression intParam(ParseInfo info) :
+{
+   Integer val = null;
+}
+{
+   (val = intVal() | <QMARK>)
+   {
+     if (val == null) {
+       return new Reference(info.referenceCount++);
+     } 
+     return new Constant(val, DataTypeManager.DefaultDataClasses.INTEGER);
+   }
+}
+
 /** 
  * <p>Parse an LIMIT clause.</p>
  * @return Parsed LIMIT
-  * @throws ParseException if parsing failed
+ * @throws ParseException if parsing failed
  */
 Limit limit(ParseInfo info) :
 {
-	Token val = null;
-	Token rowLimit = null;
-	Token ref = null;
-	Expression expr1 = null;
-	Expression expr2 = null;
+	Expression limit = null;
+	Expression offset = null;
 }
 {
-	<LIMIT>
-	(val=<INTEGERVAL> | <QMARK>)
-	[<COMMA> (rowLimit=<INTEGERVAL> | ref=<QMARK>)]
+    ((<LIMIT> offset = intParam(info)
+	[<COMMA> limit = intParam(info)])
 	{
-	    if (val == null) {
-	        expr1 = new Reference(info.referenceCount++);
-	    } else {
-	        expr1 = new Constant(Integer.valueOf(val.image), DataTypeManager.DefaultDataClasses.INTEGER);
-	    }
-		if (rowLimit == null && ref == null) {
-		    return new Limit(null, expr1);
-		}
-		if (rowLimit == null) {
-		    expr2 = new Reference(info.referenceCount++);
-		} else {
-	        expr2 = new Constant(Integer.valueOf(rowLimit.image), DataTypeManager.DefaultDataClasses.INTEGER);
-		}
-		return new Limit(expr1, expr2);
+	  if (limit == null) {
+	    limit = offset;
+	    offset = null;
+	  }
 	}
+	|
+	(<OFFSET> offset = intParam(info) (<ROW>|<ROWS>) 
+    [limit = fetchLimit(info)])
+    |
+    (limit = fetchLimit(info)))
+	{
+		return new Limit(offset, limit);
+	}
 }
 
+Expression fetchLimit(ParseInfo info) :
+{
+    Expression limit = null;
+}
+{
+    <FETCH> nonReserved("FIRST", "NEXT") [limit = intParam(info)] (<ROW>|<ROWS>) <ONLY>
+    {
+      if (limit == null) {
+        return new Constant(1, DataTypeManager.DefaultDataClasses.INTEGER); 
+      }
+      return limit;
+    }
+}
+
 /** 
  * <p>Parse an OPTION clause.</p>
  * @return Parsed OPTION clause
@@ -3415,19 +3421,20 @@
 			<RBRACE>
 		)
 		|
-		LOOKAHEAD(<ID> <LPAREN> <FOR>) (expression=textAgg(info))				
+		LOOKAHEAD(<ID> <LPAREN>, {matchesAny(getToken(1).image, "textagg") != null}) 
+		(expression=textAgg(info) [expression = windowSpecification(expression, info)])				
 		|		
 		// Aggregate function
-		LOOKAHEAD(<ID>, {matchesAny(getToken(1).image, "count", "min", "max", "sum", "avg", "every", "STDDEV_POP", "STDDEV_SAMP", "VAR_SAMP", "VAR_POP") != null}) (expression=aggregateSymbol(info))
+		LOOKAHEAD(<ID> <LPAREN>, {matchesAny(getToken(1).image, "count", "min", "max", "sum", "avg", "every", "STDDEV_POP", "STDDEV_SAMP", "VAR_SAMP", "VAR_POP") != null}) 
+		(expression=aggregateSymbol(info) [expression = windowSpecification(expression, info)])
 		|
-		LOOKAHEAD(<ANY>) (expression=aggregateSymbol(info))
+		LOOKAHEAD(<ANY>|<SOME>) (expression=aggregateSymbol(info) [expression = windowSpecification(expression, info)])
 		|
-		LOOKAHEAD(<SOME>) (expression=aggregateSymbol(info))
+		expression=orderedAgg(info) [expression = windowSpecification(expression, info)]
 		|
-		(expression=xmlAgg(info))
+		LOOKAHEAD(<ID> <LPAREN>, {matchesAny(getToken(1).image, "rank", "dense_rank", "row_number") != null}) 
+		(expression=aggregateSymbol(info) expression = windowSpecification(expression, info))
 		|
-		(expression=arrayAgg(info))
-		|
 		// Function
 		LOOKAHEAD(2) (expression=function(info))
 		|
@@ -3478,6 +3485,31 @@
 	}
 }
 
+Expression windowSpecification(Expression agg, ParseInfo info) :
+{
+	List<Expression> partitionList = null;
+	OrderBy orderBy = null;
+}
+{
+	<OVER> 
+    <LPAREN> 
+    [<PARTITION> <BY> partitionList = expressionList(info)]
+    [orderBy = orderby(info)]
+    <RPAREN>
+    {
+        String aggName = "win_" + ((AggregateSymbol)agg).getName();
+		String name = generateFunctionName(info, aggName);
+        
+    	WindowFunction result = new WindowFunction(aggName);
+    	WindowSpecification ws = new WindowSpecification();
+    	result.setFunction((AggregateSymbol)agg);
+    	ws.setPartition(partitionList);
+    	ws.setOrderBy(orderBy);
+    	result.setWindowSpecification(ws);
+    	return result;
+    }
+}
+
 /**
  * Parse a non-searched CASE expression.
  * @return CaseExpression
@@ -3486,8 +3518,8 @@
 CaseExpression caseExpression(ParseInfo info) :
 {
 	Expression expression = null, whenExpression = null, thenExpression = null, elseExpression = null;
-	ArrayList whenExpressions = new ArrayList();
-	ArrayList thenExpressions = new ArrayList();
+	ArrayList whenExpressions = new ArrayList(2);
+	ArrayList thenExpressions = new ArrayList(2);
 }
 {
 	<CASE>
@@ -3520,8 +3552,8 @@
 {
 	Expression thenExpression = null, elseExpression = null;
 	Criteria whenCriteria = null;
-	ArrayList whenCriteriaList = new ArrayList();
-	ArrayList thenExpressions = new ArrayList();
+	ArrayList whenCriteriaList = new ArrayList(2);
+	ArrayList thenExpressions = new ArrayList(2);
 }
 {
 	<CASE>
@@ -3555,7 +3587,7 @@
 	String funcName = null;
     
 	Expression expression = null;
-	ArrayList args = new ArrayList();
+	ArrayList args = new ArrayList(2);
 	Token funcToken = null;
 }
 {
@@ -3564,16 +3596,14 @@
 		expression = expression(info)
 		{
 			args.add(expression);
-			expression = null;
 		}
 		<COMMA>
 		expression = dataType()	
 		{
 			args.add(expression);
-			expression = null;			
 		}
 		<RPAREN> 
-	)	
+	)
 	|
 	(			
 		funcToken = <CAST>
@@ -3581,30 +3611,102 @@
 		expression = expression(info)
 		{
 			args.add(expression);
-			expression = null;
 		} 
 		<AS>
 		expression = dataType()
 		{
 			args.add(expression);
-			expression = null;
 		}
 		<RPAREN>				
 	)
 	|
+	LOOKAHEAD(4, {getToken(1).image.equalsIgnoreCase("SUBSTRING")}) (
+	   funcName = nonReserved("SUBSTRING")
+	   <LPAREN>
+	   expression = expression(info)
+	   {
+	      args.add(expression);
+	   }
+	   <FROM> expression = expression(info)
+	   {
+	      args.add(expression);
+	   }
+  	   [<FOR> expression = expression(info)
+	    {
+	      args.add(expression);
+	    }
+	   ]
+	   <RPAREN>
+	)
+	|
+	LOOKAHEAD(2, {getToken(1).image.equalsIgnoreCase("EXTRACT")}) (
+	   nonReserved("EXTRACT")
+	   <LPAREN>
+	   (funcToken = <YEAR> | 
+	    funcToken = <MONTH> |
+	    funcToken = <DAY> |
+	    funcToken = <HOUR> |
+	    funcToken = <MINUTE> |
+	    funcToken = <SECOND>)
+	   <FROM> expression = expression(info)
+	   {
+	   	  if (funcToken.image.equalsIgnoreCase("DAY")) {
+	         funcName = "DAYOFMONTH";
+	      }  	      
+	      args.add(expression);
+	   }
+	   <RPAREN>
+	)
+	|
+	LOOKAHEAD(2, {getToken(1).image.equalsIgnoreCase("TRIM")}) (
+	   funcName= nonReserved("TRIM")
+	   <LPAREN>
+	   { funcToken = null; expression = null;}
+	   [
+	    LOOKAHEAD(2) (((funcToken = <LEADING>|
+	      funcToken = <TRAILING>|
+	      funcToken = <BOTH>)
+	    [expression = expression(info)])
+	    |
+	    expression = expression(info))
+		<FROM>
+	   ]
+  	   {
+	      if (funcToken == null) {
+	      	  args.add(new Constant("BOTH"));
+	      } else {
+	          args.add(new Constant(funcToken.image));
+	      }
+	      if (expression == null) {
+	          args.add(new Constant(" "));
+	      } else {
+	          if (expression instanceof Constant) {
+	              Object value = ((Constant)expression).getValue();
+	              if (value instanceof String && ((String)value).length() != 1) {
+				      throw new ParseException(QueryPlugin.Util.getString("SQLParser.Invalid_char", "TRIM CHAR", value)); //$NON-NLS-1$
+	              }
+	          }
+	          args.add(expression);
+	      }
+	   }
+	   expression = expression(info)
+	   {
+	      args.add(expression);
+	   }
+	   <RPAREN>
+	)
+	|
 	LOOKAHEAD(<ID>, {matchesAny(getToken(1).image, "to_chars", "to_bytes") != null}) (	
 		funcName = nonReserved("TO_CHARS", "TO_BYTES")
 		<LPAREN>
 		expression = expression(info) 
 		{		
 			args.add(expression);
-			expression = null;
 		}
 		<COMMA>
 		expression = stringConstant()
 		{
 			args.add(expression);
-			expression = null;
 		} 
 		<RPAREN>				
 	)
@@ -3615,19 +3717,16 @@
 		expression = intervalType() 
 		{		
 			args.add(expression);
-			expression = null;
 		}
 		<COMMA>
 		expression = expression(info)
 		{
 			args.add(expression);
-			expression = null;
 		} 
 		<COMMA>
 		expression = expression(info)
 		{
 			args.add(expression);
-			expression = null;
 		} 
 		<RPAREN>				
 	)
@@ -3642,62 +3741,16 @@
 		                    | funcToken = <YEAR> | funcToken = <MONTH> | funcToken = <HOUR>
 		                    | funcToken = <MINUTE> | funcToken = <SECOND> | funcToken = <XMLCONCAT>
 		                    | funcToken = <XMLCOMMENT>)
-		<LPAREN>
-		[
-			expression = expression(info)
-			{
-				args.add(expression);	
-				expression = null;
-			}
-				
-			(<COMMA> expression=expression(info)
-			{
-				args.add(expression);
-				expression = null;
-			}
-			)*
-		]
+        <LPAREN>
+		[args = expressionList(info)]
 		<RPAREN>
 	)		
 	|
-	LOOKAHEAD(<INSERT> <LPAREN>) (
-		(funcToken = <INSERT>)
+	LOOKAHEAD(<TRANSLATE>|<INSERT> <LPAREN>) (
+		(funcToken = <TRANSLATE> | funcToken = <INSERT>)
 		<LPAREN>
-		[
-			expression = expression(info)
-			{
-				args.add(expression);	
-				expression = null;
-			}
-				
-			(<COMMA> expression=expression(info)
-			{
-				args.add(expression);
-				expression = null;
-			}
-			)*
-		]
+		[args = expressionList(info)]
 		<RPAREN>
-	)  			
-	|
-	LOOKAHEAD(<TRANSLATE> <LPAREN>) (
-		(funcToken = <TRANSLATE>)
-		<LPAREN>
-		[
-			expression = expression(info)
-			{
-				args.add(expression);	
-				expression = null;
-			}
-				
-			(<COMMA> expression=expression(info)
-			{
-				args.add(expression);
-				expression = null;
-			}
-			)*
-		]
-		<RPAREN>
 	)  
 	| expression = xmlParse(info)
 	  {
@@ -3716,13 +3769,11 @@
 		)
 		{
 			args.add(expression);	
-			expression = null;
 		}
 		[
 			<COMMA> expression = expression(info)
 			{
 				args.add(expression);	
-				expression = null;
 			}	
 		]
 		<RPAREN>
@@ -3742,20 +3793,7 @@
 	|   
 	(	funcName = id()
 		<LPAREN>
-		[
-			expression = expression(info)
-			{
-				args.add(expression);	
-				expression = null;
-			}
-				
-			(<COMMA> expression=expression(info)
-			{
-				args.add(expression);
-				expression = null;
-			}
-			)*
-		]
+		[ args = expressionList(info) ]
 		<RPAREN>
 	))		
 	{
@@ -3807,7 +3845,7 @@
 {
 	Expression path = null;
 	DerivedColumn arg = null;
-	ArrayList<DerivedColumn> args = new ArrayList<DerivedColumn>();
+	ArrayList<DerivedColumn> args = new ArrayList<DerivedColumn>(2);
 }
 {
  	nonReserved("QUERYSTRING") <LPAREN>
@@ -3827,7 +3865,7 @@
 XMLElement xmlElement(ParseInfo info) :
 {
 	String name = null;
-	ArrayList content = new ArrayList();
+	ArrayList content = new ArrayList(2);
 	XMLNamespaces xmlNamespaces = null;
 	XMLAttributes xmlAttributes = null;
 	Expression expression = null;
@@ -3848,7 +3886,6 @@
 	(<COMMA> expression=expression(info)
 	{
 		content.add(expression);
-		expression = null;
 	}
 	)*
 	<RPAREN>
@@ -3863,19 +3900,17 @@
 XMLAttributes xmlAttributes(ParseInfo info) :
 {
 	DerivedColumn expression = null;
-	ArrayList<DerivedColumn> args = new ArrayList<DerivedColumn>();
+	ArrayList<DerivedColumn> args = new ArrayList<DerivedColumn>(2);
 }
 {
  	<XMLATTRIBUTES> <LPAREN>
 	expression = derivedColumn(info)
 	{
 		args.add(expression);
-		expression = null;
 	}
 	(<COMMA> expression=derivedColumn(info)
 	 {
 		args.add(expression);
-		expression = null;
 	 }
 	)*
 	<RPAREN>  		
@@ -3888,7 +3923,7 @@
 {
 	DerivedColumn expression = null;
 	XMLNamespaces xmlNamespaces = null;
-	ArrayList<DerivedColumn> args = new ArrayList<DerivedColumn>();
+	ArrayList<DerivedColumn> args = new ArrayList<DerivedColumn>(2);
 }
 {
  	<XMLFOREST> <LPAREN>
@@ -3898,12 +3933,10 @@
 	expression = derivedColumn(info)
 	{
 		args.add(expression);
-		expression = null;
 	}
 	(<COMMA> expression=derivedColumn(info)
 	 {
 		args.add(expression);
-		expression = null;
 	 }
 	)*
 	<RPAREN>  		
@@ -3916,7 +3949,7 @@
 		
 XMLNamespaces xmlNamespaces(ParseInfo info) :
 {
-	ArrayList namespaces = new ArrayList();
+	ArrayList namespaces = new ArrayList(2);
 	XMLNamespaces.NamespaceItem item = null;
 }
 {

Modified: branches/as7/engine/src/main/resources/org/teiid/query/i18n.properties
===================================================================
--- branches/as7/engine/src/main/resources/org/teiid/query/i18n.properties	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/main/resources/org/teiid/query/i18n.properties	2011-08-18 16:17:24 UTC (rev 3394)
@@ -94,7 +94,6 @@
 ERR.015.008.0010= INSERT statement must have the same number of elements and values specified.  This statement has {0} elements and {1} values.
 ERR.015.008.0011= Error parsing query plan transformation for {0}
 ERR.015.008.0013= Error parsing query plan transformation for {0}
-ERR.015.008.0015= Unknown statement type: {0}
 ERR.015.008.0019= Unable to resolve element: {0}
 ERR.015.008.0020= Element is ambiguous and must be qualified: {0}
 ERR.015.008.0022= Failed parsing reference binding: {0}
@@ -113,7 +112,7 @@
 ERR.015.008.0040= The function ''{0}'' is a valid function form, but the arguments do not match a known type signature and cannot be converted using implicit type conversions.
 ERR.015.008.0041= Expected value of type ''{0}'' but ''{1}'' is of type ''{2}'' and no implicit conversion is available.
 ERR.015.008.0042= Element ''{0}'' in ORDER BY is ambiguous and may refer to more than one element of SELECT clause.
-ERR.015.008.0043= Element ''{0}'' in ORDER BY was not found in SELECT clause.
+ERR.015.008.0043= Element ''{0}'' in ORDER BY was not found in the FROM clause.
 ERR.015.008.0045= Failed parsing {1} plan for {0}
 ERR.015.008.0046= The symbol {0} may only be used once in the FROM clause.
 ERR.015.008.0047= The symbol {0} refers to a group not defined in the FROM clause.
@@ -131,6 +130,7 @@
 ERR.015.008.0068= Could not find a common type to which all {0} expressions can be implicitly converted: {1}
 ERR.015.008.0070= Aliased Select Symbols are not valid in XML Queries.
 XMLQueryResolver.no_expressions_in_select=Expressions cannot be selected by XML Queries
+XMLQueryResolver.aliased_subquery=Aliased subquery contexts are not allowed: {0}
 
 # sql (010)
 ERR.015.010.0001= Invalid compare operator: {0}
@@ -196,6 +196,10 @@
 ValidationVisitor.insert_qe_partition = Inserts with query expressions cannot be performed against a partitioned UNION view {0}.
 ValidationVisitor.insert_no_partition = Could not determine INSERT target for a partitioned UNION view {0} with values {1}.
 ValidationVisitor.multisource_constant = The multisource column or parameter {0} requires a literal value.
+ValidationVisitor.duplicate_block_label = Duplicate label {0}.
+ValidationVisitor.no_loop = CONTINUE/BREAK can only be used in a LOOP/WHILE statement.
+ValidationVisitor.invalid_label = CONTINUE/BREAK labels can only target LOOP/WHILE statements. {0} targets a block.
+ValidationVisitor.unknown_block_label = No label found in containing scope with name {0}.
 ERR.015.012.0029 = INSERT, UPDATE, and DELETE not allowed on XML documents
 ERR.015.012.0030 = Commands used in stored procedure language not allowed on XML documents
 ERR.015.012.0031 = Queries against XML documents can not have a GROUP By clause
@@ -203,10 +207,10 @@
 ERR.015.012.0033 = Metadata does not allow updates on the group: {0}
 ERR.015.012.0034 = Queries involving UNIONs, INTERSECTs and EXCEPTs not allowed on XML documents
 ERR.015.012.0035 = Queries combined with the set operator {0} must have the same number of output elements.
-ERR.015.012.0037 = Invalid symbol: {0}. When an aggregate function is used in the SELECT clause and no GROUP BY clause is specified, the SELECT clause may contain only aggregate functions and constants.
-ERR.015.012.0038 = Invalid symbol: {0}. When a GROUP BY clause is used, all elements in the SELECT clause must be declared in the GROUP BY clause.
+ERR.015.012.0037 = {0} cannot be used outside of aggregate functions since they are not present in a GROUP BY clause.
 ERR.015.012.0039 = Nested aggregate expressions are not allowed: {0}
 ERR.015.012.0041 = The aggregate function {0} cannot be used with non-numeric expressions: {1}
+ERR.015.012.0042 = A windowed aggregate function {0} cannot use its own order by clause or be distinct: {1}
 AggregateValidationVisitor.non_comparable = The aggregate function {0} cannot be used with non-comparable expressions: {1}
 AggregateValidationVisitor.non_xml = The XMLAGG aggregate function {0} requires an expression of type XML: {1}
 AggregateValidationVisitor.non_boolean=The boolean aggregate functions ANY, SOME, EVERY require a boolean expression.
@@ -231,7 +235,7 @@
 ERR.015.004.0010= Unknown group specified in OPTION MAKEDEP/MAKENOTDEP: {0}
 ERR.015.004.0012= Group has an access pattern which has not been met: group(s) {0}; access pattern(s) {1}
 ERR.015.004.0020= Error getting model for {0}
-ERR.015.004.0023= Error rewriting criteria: {0}
+ERR.015.004.0023= Error rewriting: {0}
 ERR.015.004.0024= Unable to create a query plan that sends a criteria to \"{0}\".  This connection factory requires criteria set to true indicating that a query against this model requires criteria.  
 ERR.015.004.0029= Could not resolve group symbol {0}
 ERR.015.004.0035= The criteria {0} has elements from the root staging table and the document nodes which is not allowed.
@@ -258,7 +262,8 @@
 
 
 SQLParser.Unknown_join_type=Unknown join type: {0}
-SQLParser.Aggregate_only_top_level=Aggregate expressions are allowed only as top level functions in the SELECT and HAVING clauses.
+SQLParser.Aggregate_only_top_level=Aggregate functions are only allowed HAVING/SELECT/ORDER BY clauses.  Window functions are only allowed in the SELECT/ORDER BY clauses: {0}.  Both require a FROM clause to be present.
+SQLParser.window_only_top_level=Window functions are not allowed in the HAVING clause: {0}
 SQLParser.Unknown_agg_func=Unknown aggregate function: {0}
 SQLParser.Invalid_func=Invalid function name: [{0}]
 SQLParser.Integer_parse=Unable to parse integer literal: {0}
@@ -393,6 +398,11 @@
 SystemSource.Rand_result_desc=Generated Random Number
 SystemSource.uuid_desc=UUID
 SystemSource.uuid_result_desc=type 4 UUID
+SystemSource.trim_desc=Trim characters from the front and/or back of a string
+SystemSource.trim_arg1=Trim specification, can be one of TRAILING, LEADING, or BOTH
+SystemSource.trim_arg2=Trim character - must be a single character
+SystemSource.trim_arg3=String to trim
+SystemSource.trim_result=Trimmed string
 SystemSource.Double_arg2=Number
 SystemSource.Atan_arg1=Number parameter1 
 SystemSource.Atan_arg2=Number parameter2 
@@ -676,7 +686,10 @@
 SimpleQueryResolver.procedure_cache_used=Procedure caching will be used for {0}.
 SimpleQueryResolver.procedure_cache_not_usable=Procedure caching will not be used for {0} since the result set cache is disabled or the results/parameters cannot be cached.
 SimpleQueryResolver.procedure_cache_not_used=Procedure caching will not be used for {0} due to the use of OPTION NOCACHE.
-ValidationVisitor.groupby_subquery=Expressions used in a GROUP BY cannot be constant and must not contain subqueries: "{0}".
+ValidationVisitor.groupby_subquery=Expressions used in a GROUP BY clause cannot be constant and must not contain subqueries: "{0}".
+ValidationVisitor.filter_subquery=Expressions used in a FILTER clause or a window function must not contain subqueries nor outer references: "{0}".
+ValidationVisitor.ranking_requires_order_by=The window ranking functions RANK, DENSE_RANK, and ROW_NUMBER require the use of an ORDER BY clause in the window specification: {0}.
+ValidationVisitor.window_order_by=The window specification for TEXTAGG and ARRAY_AGG cannot use an ORDER BY clause: {0}.
 ValidationVisitor.Procedure_has_group_self_reference=Procedure cannot have a Group reference to itself.
 ExpressionEvaluator.Expected_props_for_payload_function=Unable to evaluate {0}: expected Properties for command payload but got object of type {1}
 ValidationVisitor.The_rowlimit_function_cannot_be_used_in_a_non-XML_command=The ''rowlimit'' and ''rowlimitexception'' functions cannot be used in a non-XML command
@@ -697,7 +710,7 @@
 XMLQueryResolver.xml_only_valid_alone=If any symbol in SELECT clause is ''xml'' or group.''xml'' , then no other element is allowed.
 ResolveVariablesVisitor.datatype_for_the_expression_not_resolvable=The datatype for the expression was not resolvable.
 TempTableResolver.unqualified_name_required=Cannot create temporary table "{0}". Local temporary tables must be created with unqualified names.
-TempTableResolver.table_already_exists=Cannot create temporary table "{0}". A table with the same name already exists.
+TempTableResolver.table_already_exists=Cannot create temporary table "{0}". An object with the same name already exists.
 ValidationVisitor.drop_of_nontemptable=Cannot drop a non temporary table "{0}".							
 ValidationVisitor.orderby_expression_xml=XML queries cannot order by an expression.
 ValidationVisitor.text_table_invalid_width=For a fixed width text table, all columns must have width set.
@@ -779,6 +792,9 @@
 TempTableStore.table_doesnt_exist_error=Temporary table "{0}" does not exist.
 
 XMLQueryPlanner.cannot_plan=Cannot create a query for MappingClass with user criteria {0}
+XMLQueryPlanner.invalid_relationship=Conjunct "{0}" has no relationship with target context {1}.
+XMLQueryPlanner.non_simple_relationship=Conjunct "{0}" has a non-simple relationship to its parent through context {1}.
+
 CriteriaPlanner.staging_context=Staging table criteria cannot contian context functions
 CriteriaPlanner.multiple_staging=Staging table criteria {0} was not specified against a single staging table
 CriteriaPlanner.invalid_context=Element {0} is not in the scope of the context {1}
@@ -800,7 +816,8 @@
 TextTableNode.character_not_allowed=Text parse error: Non-whitespace character found between the qualifier and the delimiter in text line {0} in {1}.
 TextTableNode.unknown_escape=Text parse error: Unknown escape sequence \\{0} in text line {1} in {2}.
 TextTableNode.invalid_width=Text parse error: Fixed width line width {0} is smaller than the expected {1} on text line {2} in {3}.
-TextTableNode.line_too_long=Text parse error: Delimited line is longer than the expected max of {2} on text line {0} in {1}.  
+TextTableNode.line_too_long=Text parse error: Delimited line is longer than the expected max of {2} on text line {0} in {1}.
+ValidationVisitor.fixed_option=NO ROW DELIMITER can only be used in fixed parsing mode.  
 
 XMLTableNode.error=Error evaluating XQuery row context for XMLTable: {0}
 XMLTableNode.path_error=Error evaluating XMLTable column path expression for column: {0}
@@ -809,6 +826,7 @@
 TempTableDataManager.failed_load=Failed to load materialized view table {0}.
 TempTableDataManager.loaded=Loaded materialized view table {0} with row count {1}.
 TempTableDataManager.loading=Loading materialized view table {0}
+TempTableDataManager.cache_load=Loaded materialized view table {0} from cached contents from another clustered node.
 TempTableDataManager.not_implicit_matview={0} does not target an internal materialized view.
 TempTableDataManager.row_refresh_pk=Materialized view {0} cannot have a row refreshed since there is no primary key.
 TempTableDataManager.row_refresh_composite=Materialized view {0} cannot have a row refreshed because it uses a composite key.
@@ -897,7 +915,8 @@
 datasource_not_found=Data Source {0} not accessible.
 
 RequestWorkItem.cache_nondeterministic=Caching command "{0}" at a session level, but less deterministic functions were evaluated. 
-not_found_cache=Failed to restore results
+not_found_cache=Failed to restore results, since batch entries were missing.  The entry will be re-populated. 
+unexpected_exception_restoring_results=Failed to restore results.  The entry will be re-populated.
 failed_to_cache=Failed to store the result set contents to disk.
 failed_to_unwrap_connection=Failed to unwrap the source connection.
 connection_factory_not_found=Failed to find the Connection Factory with JNDI name {0}. Please check the name or deploy the Connection Factory with specified name.
@@ -909,6 +928,7 @@
 MultiSource.out_procedure=The multisource plan must execute a procedure returning parameter values exactly 1: {0}
 
 FunctionMethods.not_array_value=Expected a java.sql.Array, or java array type, but got: {0}
+FunctionMethods.unknown_level=Unknown log level: {0}, expected one of {1}
 FunctionMethods.array_index=Array index out of range: {0}
 ArrayTableNode.conversion_error=Could not convert value for column: {0}
 
@@ -916,4 +936,5 @@
 ValidationVisitor.not_a_procedure={0} is not a valid virtual procedure.
 
 DdlPlan.event_not_exists={0} does not have an INSTEAD OF trigger defined for {1}.
-DdlPlan.event_already_exists={0} already has an INSTEAD OF trigger defined for {1}.
\ No newline at end of file
+DdlPlan.event_already_exists={0} already has an INSTEAD OF trigger defined for {1}.
+error_refresh=error occurred during refreshing the materialized view entries for view {0}
\ No newline at end of file

Modified: branches/as7/engine/src/test/java/org/teiid/cdk/CommandBuilder.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/cdk/CommandBuilder.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/cdk/CommandBuilder.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -38,7 +38,7 @@
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.symbol.AllSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 
 
 /**
@@ -90,8 +90,8 @@
             List expandedSymbols = new ArrayList();
             for (Iterator i = originalSymbols.iterator(); i.hasNext(); ) {
                 Object next = i.next();
-                if (next instanceof AllSymbol) {
-                    AllSymbol allSymbol = (AllSymbol) next;
+                if (next instanceof MultipleElementSymbol) {
+                    MultipleElementSymbol allSymbol = (MultipleElementSymbol) next;
                     expandedSymbols.addAll(allSymbol.getElementSymbols());
                 } else {
                     expandedSymbols.add(next);

Modified: branches/as7/engine/src/test/java/org/teiid/common/buffer/BufferManagerFactory.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/common/buffer/BufferManagerFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/common/buffer/BufferManagerFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -58,16 +58,35 @@
     }
 
 	public static BufferManagerImpl createBufferManager() {
-		BufferManagerImpl bufferMgr = new BufferManagerImpl();
-		try {
-			bufferMgr.initialize();
+		return initBufferManager(new BufferManagerImpl());
+	}
+
+	public static BufferManagerImpl getTestBufferManager(long bytesAvailable, int procBatchSize, int connectorBatchSize) {
+		BufferManagerImpl bufferManager = new BufferManagerImpl();
+		bufferManager.setProcessorBatchSize(procBatchSize);
+		bufferManager.setConnectorBatchSize(connectorBatchSize);
+		bufferManager.setMaxProcessingKB((int) (bytesAvailable/1024));
+		bufferManager.setMaxReserveKB((int) (bytesAvailable/1024));
+	    return initBufferManager(bufferManager);
+	}
+
+	public static BufferManagerImpl getTestBufferManager(long bytesAvailable, int procBatchSize) {
+		BufferManagerImpl bufferManager = new BufferManagerImpl();
+		bufferManager.setProcessorBatchSize(procBatchSize);
+		bufferManager.setMaxProcessingKB((int) (bytesAvailable/1024));
+		bufferManager.setMaxReserveKB((int) (bytesAvailable/1024));
+		return initBufferManager(bufferManager);
+	}
+
+	public static BufferManagerImpl initBufferManager(BufferManagerImpl bufferManager) {
+	    try {
+			bufferManager.initialize();
 		} catch (TeiidComponentException e) {
 			throw new RuntimeException(e);
 		}
-
-		// Add unmanaged memory storage manager
-		bufferMgr.setStorageManager(new MemoryStorageManager());
-		return bufferMgr;
+	
+	    bufferManager.setStorageManager(new MemoryStorageManager());
+	    return bufferManager;
 	}
 
 }

Modified: branches/as7/engine/src/test/java/org/teiid/common/buffer/TestSTree.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/common/buffer/TestSTree.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/common/buffer/TestSTree.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,7 +33,7 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.query.sql.symbol.ElementSymbol;
 
- at SuppressWarnings("nls")
+ at SuppressWarnings({"nls", "unchecked"})
 public class TestSTree {
 	
 	@Test public void testRemoveAll() throws TeiidComponentException {
@@ -42,7 +42,7 @@
 		e1.setType(Integer.class);
 		ElementSymbol e2 = new ElementSymbol("y");
 		e2.setType(String.class);
-		List elements = Arrays.asList(e1, e2);
+		List<ElementSymbol> elements = Arrays.asList(e1, e2);
 		STree map = bm.createSTree(elements, "1", 1);
 		
 		for (int i = 20000; i > 0; i--) {
@@ -83,7 +83,7 @@
 		
 		ElementSymbol e1 = new ElementSymbol("x");
 		e1.setType(Integer.class);
-		List elements = Arrays.asList(e1);
+		List<ElementSymbol> elements = Arrays.asList(e1);
 		STree map = bm.createSTree(elements, "1", 1);
 		
 		int size = (1<<16)+(1<<4)+1;

Copied: branches/as7/engine/src/test/java/org/teiid/common/buffer/impl/TestSizeUtility.java (from rev 3382, trunk/engine/src/test/java/org/teiid/common/buffer/impl/TestSizeUtility.java)
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/common/buffer/impl/TestSizeUtility.java	                        (rev 0)
+++ branches/as7/engine/src/test/java/org/teiid/common/buffer/impl/TestSizeUtility.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,185 @@
+/*
+ * 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 org.teiid.common.buffer.impl;
+
+import static org.junit.Assert.*;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.common.buffer.TupleBatch;
+
+public class TestSizeUtility {
+
+    public void helpTestGetStaticSize(Object obj, long expectedSize) {
+        helpTestGetSize(obj, expectedSize);
+    }
+
+    public void helpTestGetSize(Object obj, long expectedSize) {  
+        long actualSize = new SizeUtility().getSize(obj, true, false);
+        assertEquals("Got unexpected size: ", expectedSize, actualSize); //$NON-NLS-1$
+    }
+
+    @Test public void testGetSizeChar() {
+        helpTestGetStaticSize(new Character('a'), 10);
+    }
+
+    @Test public void testGetSizeBoolean() {
+        helpTestGetStaticSize(Boolean.TRUE, 1);
+    }
+
+    @Test public void testGetSizeByte() {
+        helpTestGetStaticSize(new Byte((byte)0), 1);
+    }
+
+    @Test public void testGetSizeShort() {
+        helpTestGetStaticSize(new Short((short)0), 10);
+    }
+
+    @Test public void testGetSizeInteger() {
+        helpTestGetStaticSize(new Integer(0), 12);
+    }
+
+    @Test public void testGetSizeLong() {
+        helpTestGetStaticSize(new Long(0l), 16);
+    }
+    
+    @Test public void testGetSizeFloat() {
+        helpTestGetStaticSize(new Float(0), 12);
+    }
+
+    @Test public void testGetSizeDouble() {
+        helpTestGetStaticSize(new Double(0), 16);
+    }
+
+    @Test public void testGetSizeTimestamp() {
+        helpTestGetStaticSize(new Timestamp(12301803), 28);
+    }
+
+    @Test public void testGetSizeDate() {
+        helpTestGetStaticSize(new Date(12301803), 28);
+    }
+
+    @Test public void testGetSizeTime() {
+        helpTestGetStaticSize(new Time(12301803), 28);
+    }
+
+    @Test public void testGetSizeEmptyString() {
+        helpTestGetSize("", 40); //$NON-NLS-1$
+    }
+
+    @Test public void testGetSizeShortString() {
+        helpTestGetSize("abcdefghij", 64); //$NON-NLS-1$
+    }
+
+    public void XtestGetSizeLongString() {
+        // There is no clear way of figuring out the actual size of a string that is created
+        // from a StringBuffer because the buffer can sometimes be twice as big as the actual length of the string
+        // Since the data comin from the connector is not created this way, this test is an inaccurate setup 
+        int size = 10000;
+        StringBuffer str = new StringBuffer();
+        for(int i=0; i<size; i++) { 
+            str.append("a"); //$NON-NLS-1$
+        }
+        helpTestGetSize(str.toString(), size+3);
+    }
+
+    @Test public void testGetSizeRow1() {
+        List<Object> row = new ArrayList<Object>(1);
+        row.add(new Integer(0));
+        helpTestGetStaticSize(row, 36);
+    }
+    
+    @Test public void testGetSizeRow2() {
+        List<Object> row = new ArrayList<Object>(4);
+        row.add(new Integer(0));
+        row.add(new Integer(101));
+        row.add(Boolean.TRUE);
+        row.add(new Double(1091203.00));
+        helpTestGetStaticSize(row, 89);
+    }
+    
+    @Test public void testGetSizeRows1() {
+        helpTestGetStaticSize(new List[] { }, 16);
+    }
+
+    @Test public void testGetSizeRows2() {
+        List<Object> row1 = new ArrayList<Object>(2);
+        row1.add(new Integer(0));
+        row1.add(new Integer(100));
+
+        List<Object> row2 = new ArrayList<Object>(2);
+        row2.add(new Integer(0));
+        row2.add(new Integer(100));
+
+        helpTestGetStaticSize(new List[] { row1, row2 }, 144);
+    }
+   
+    @Test public void testGetSizeBigInteger() {
+        BigInteger b = BigInteger.ONE;
+                
+        helpTestGetStaticSize(b, 48);
+    }    
+    
+    @Test public void testGetSizeBigDecimal() {
+        BigDecimal bd = new BigDecimal("1.0"); //$NON-NLS-1$
+        
+        helpTestGetStaticSize(bd, 96);
+    }
+    
+    @Test public void testGetSizeByteArray() {
+        byte[] bytes = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+        helpTestGetSize(bytes, 32);
+    }
+    
+    @Test public void testResultSet() {
+        List<?>[] expected = new List[] { 
+                Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0),    "a",    new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0),    "a",    new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0),    "a",    new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0),    "a",    new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0),    "a",    new Integer(3) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0),    "a",    new Integer(3) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(3),     Boolean.TRUE,   new Double(7.0),    "a",    new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(3),     Boolean.TRUE,   new Double(7.0),    "a",    new Integer(0) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "a",   new Integer(3),     Boolean.TRUE,   new Double(7.0),    "a",    new Integer(3) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "b",   new Integer(2),     Boolean.FALSE,  new Double(0.0),    "b",    new Integer(2) }), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList(new Object[] { "c",   new Integer(1),     Boolean.FALSE,  new Double(0.0),    "c",    new Integer(1) })  //$NON-NLS-1$ //$NON-NLS-2$
+           };     
+        
+        String[] types = {"string", "integer", "boolean", "double", "string", "integer"};     //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ //$NON-NLS-5$//$NON-NLS-6$
+
+        TupleBatch tb = new TupleBatch(1, expected);
+        tb.setDataTypes(types);
+        long actualSize = new SizeUtility().getBatchSize(tb);
+        assertEquals("Got unexpected size: ", 2667, actualSize); //$NON-NLS-1$        
+    }
+    
+}
\ No newline at end of file

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/FakeConnector.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/FakeConnector.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/FakeConnector.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,35 +22,25 @@
 
 package org.teiid.dqp.internal.datamgr;
 
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
-import junit.framework.Assert;
-
 import org.teiid.language.Command;
-import org.teiid.language.QueryExpression;
 import org.teiid.metadata.RuntimeMetadata;
-import org.teiid.translator.TranslatorException;
 import org.teiid.translator.DataNotAvailableException;
 import org.teiid.translator.Execution;
 import org.teiid.translator.ExecutionContext;
 import org.teiid.translator.ExecutionFactory;
 import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
 import org.teiid.translator.UpdateExecution;
 
-public class FakeConnector extends ExecutionFactory {
-	private static final int RESULT_SIZE = 5;
-	
-	private boolean executeBlocks;
-    private boolean nextBatchBlocks;
-    private boolean returnsFinalBatch;
-    private boolean driverThrowsExceptionOnCancel;
-    private long simulatedBatchRetrievalTime = 1000L;
-    private ClassLoader classloader;
+public class FakeConnector extends ExecutionFactory<Object, Object> {
     
     private int connectionCount;
     private int executionCount;
-    
+
     public int getConnectionCount() {
 		return connectionCount;
 	}
@@ -62,123 +52,52 @@
     @Override
     public Execution createExecution(Command command, ExecutionContext executionContext, RuntimeMetadata metadata, Object connection) throws TranslatorException {
     	executionCount++;
-        return new FakeBlockingExecution(executionContext);
+        return new FakeExecution(executionContext);
     }
     
-    public Object getConnection() {
-        return new FakeConnection();
-    }
-    
     @Override
     public Object getConnection(Object factory) throws TranslatorException {
+    	connectionCount++;
     	return factory;
     }
     
     @Override
     public void closeConnection(Object connection, Object factory) {
     }
-	
-    private class FakeConnection {
-    	public FakeConnection() {
-			connectionCount++;
-		}
-    	
-        public boolean released = false;
-        public void close() {
-            Assert.assertFalse("The connection should not be released more than once", released); //$NON-NLS-1$
-            released = true;
-        }
-    }   
     
-    private final class FakeBlockingExecution implements ResultSetExecution, UpdateExecution {
-        private boolean closed = false;
-        private boolean cancelled = false;
+    public final class FakeExecution implements ResultSetExecution, UpdateExecution {
         private int rowCount;
         ExecutionContext ec;
-        public FakeBlockingExecution(ExecutionContext ec) {
+        
+        public FakeExecution(ExecutionContext ec) {
             this.ec = ec;
         }
-        public void execute(QueryExpression query, int maxBatchSize) throws TranslatorException {
-            if (executeBlocks) {
-                waitForCancel();
-            }
-            if (classloader != null) {
-            	Assert.assertSame(classloader, Thread.currentThread().getContextClassLoader());
-            }
-        }
-        public synchronized void cancel() throws TranslatorException {
-            cancelled = true;
-            this.notify();
-        }
-        public void close() {
-            Assert.assertFalse("The execution should not be closed more than once", closed); //$NON-NLS-1$
-            closed = true;
-        }
         @Override
         public void execute() throws TranslatorException {
             ec.addWarning(new Exception("Some warning")); //$NON-NLS-1$
         }
         @Override
-        public List next() throws TranslatorException, DataNotAvailableException {
-        	if (nextBatchBlocks) {
-                waitForCancel();
-            }
-            if (this.rowCount >= RESULT_SIZE || returnsFinalBatch) {
+        public List<?> next() throws TranslatorException, DataNotAvailableException {
+            if (this.rowCount == 1) {
             	return null;
             }
             this.rowCount++;
-            return Arrays.asList(this.rowCount - 1);
+            return new ArrayList<Object>(Arrays.asList(this.rowCount - 1));
         }
-        private synchronized void waitForCancel() throws TranslatorException {
-            try {
-                this.wait(simulatedBatchRetrievalTime);
-                if (cancelled && driverThrowsExceptionOnCancel) {
-                    throw new TranslatorException("Request cancelled"); //$NON-NLS-1$
-                }
-            } catch (InterruptedException e) {
-                throw new RuntimeException(e);
-            }
-        }
 		@Override
 		public int[] getUpdateCounts() throws DataNotAvailableException,
 				TranslatorException {
 			return new int[] {1};
 		}
+		
+		@Override
+		public void close() {
+		}
+		
+		@Override
+		public void cancel() throws TranslatorException {
+		}
     }
 
-	public boolean isExecuteBlocks() {
-		return executeBlocks;
-	}
-	public void setExecuteBlocks(boolean executeBlocks) {
-		this.executeBlocks = executeBlocks;
-	}
-	public boolean isNextBatchBlocks() {
-		return nextBatchBlocks;
-	}
-	public void setNextBatchBlocks(boolean nextBatchBlocks) {
-		this.nextBatchBlocks = nextBatchBlocks;
-	}
-	public boolean isReturnsFinalBatch() {
-		return returnsFinalBatch;
-	}
-	public void setReturnsFinalBatch(boolean returnsFinalBatch) {
-		this.returnsFinalBatch = returnsFinalBatch;
-	}
-	public boolean isDriverThrowsExceptionOnCancel() {
-		return driverThrowsExceptionOnCancel;
-	}
-	public void setDriverThrowsExceptionOnCancel(
-			boolean driverThrowsExceptionOnCancel) {
-		this.driverThrowsExceptionOnCancel = driverThrowsExceptionOnCancel;
-	}
-	public long getSimulatedBatchRetrievalTime() {
-		return simulatedBatchRetrievalTime;
-	}
-	public void setSimulatedBatchRetrievalTime(long simulatedBatchRetrievalTime) {
-		this.simulatedBatchRetrievalTime = simulatedBatchRetrievalTime;
-	}
 	
-	public void setClassloader(ClassLoader classloader) {
-		this.classloader = classloader;
-	}
 }

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorManager.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -50,7 +50,7 @@
 				return c;
 			}
 			protected Object getConnectionFactory(){
-				return c.getConnection();
+				return c;
 			}
 		};
 		cm.start();

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestConnectorWorkItem.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -49,14 +49,14 @@
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.StoredProcedure;
 import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.ProcedureExecution;
 import org.teiid.translator.TranslatorException;
 
 
 public class TestConnectorWorkItem {
 
-	private static final QueryMetadataInterface EXAMPLE_BQT = FakeMetadataFactory.exampleBQTCached();
+	private static final QueryMetadataInterface EXAMPLE_BQT = RealMetadataFactory.exampleBQTCached();
 
 	private static Command helpGetCommand(String sql,
 			QueryMetadataInterface metadata) throws Exception {
@@ -68,7 +68,7 @@
 	static AtomicRequestMessage createNewAtomicRequestMessage(int requestid, int nodeid) throws Exception {
 		RequestMessage rm = new RequestMessage();
 		
-		DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(EXAMPLE_BQT, FakeMetadataFactory.exampleBQTVDB());
+		DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(EXAMPLE_BQT, RealMetadataFactory.exampleBQTVDB());
 		workContext.getSession().setSessionId(String.valueOf(1));
 		workContext.getSession().setUserName("foo"); //$NON-NLS-1$
 		
@@ -87,7 +87,7 @@
 		int total_columns = 3;
 		StoredProcedure command = (StoredProcedure)helpGetCommand("{call pm2.spTest8(?)}", EXAMPLE_BQT); //$NON-NLS-1$      
 		command.getInputParameters().get(0).setExpression(new Constant(1));
-		Call proc = (Call)new LanguageBridgeFactory(EXAMPLE_BQT).translate(command);
+		Call proc = new LanguageBridgeFactory(EXAMPLE_BQT).translate(command);
 
 		ProcedureBatchHandler pbh = new ProcedureBatchHandler(proc, exec);
 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestElementImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,7 +27,6 @@
 import org.teiid.language.ColumnReference;
 import org.teiid.language.NamedTable;
 import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataObject;
 
 
 public class TestElementImpl extends TestCase {
@@ -44,10 +43,6 @@
         ElementSymbol symbol = new ElementSymbol(elementName);
         symbol.setType(String.class);
         symbol.setGroupSymbol(TestGroupImpl.helpExample(groupName));
-        FakeMetadataObject obj = new FakeMetadataObject(groupName + "." + elementName, FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        obj.putProperty(FakeMetadataObject.Props.GROUP, new FakeMetadataObject(groupName, FakeMetadataObject.GROUP));
-        obj.putProperty(FakeMetadataObject.Props.LENGTH, "3"); //$NON-NLS-1$
-        symbol.setMetadataID(obj);
         return symbol;
         
     }
@@ -56,12 +51,7 @@
         ElementSymbol symbol = new ElementSymbol(elementName);
         symbol.setType(Integer.class);
         symbol.setGroupSymbol(TestGroupImpl.helpExample(groupName));
-        FakeMetadataObject obj = new FakeMetadataObject(groupName + "." + elementName, FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        obj.putProperty(FakeMetadataObject.Props.GROUP, new FakeMetadataObject(groupName, FakeMetadataObject.GROUP));
-        obj.putProperty(FakeMetadataObject.Props.LENGTH, "3"); //$NON-NLS-1$
-        symbol.setMetadataID(obj);
         return symbol;
-        
     }
     
     public static ElementSymbol helpExample(String groupName, String elementName, Object metadataID) {
@@ -82,7 +72,7 @@
     
     public void testGetName() throws Exception {
         Object metadataID = TstLanguageBridgeFactory.metadata.getElementID("pm1.g1.e1"); //$NON-NLS-1$
-        assertEquals("pm1.g1.e1", example("pm1.g1", "e1", metadataID).getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        assertEquals("e1", example("pm1.g1", "e1", metadataID).getName()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     }
 
     public void testGetGroup() throws Exception {

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestGroupImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,13 +23,12 @@
 package org.teiid.dqp.internal.datamgr;
 
 
+import junit.framework.TestCase;
+
 import org.teiid.language.NamedTable;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataObject;
 
-import junit.framework.TestCase;
 
-
 public class TestGroupImpl extends TestCase {
 
     /**
@@ -45,17 +44,14 @@
     }
     
     public static GroupSymbol helpExample(String groupName, String definition) {
-        String name = groupName;
-        if (definition != null) {
-            name = definition;
-        }
-        Object obj = new FakeMetadataObject(name, FakeMetadataObject.GROUP);
-        return helpExample(groupName, definition, obj);
+        return helpExample(groupName, definition, null);
     }
     
     public static GroupSymbol helpExample(String groupName, String definition, Object metadataID) {
         GroupSymbol symbol = new GroupSymbol(groupName, definition);
-        symbol.setMetadataID(metadataID);
+        if (metadataID != null) {
+        	symbol.setMetadataID(metadataID);
+        }
         return symbol;
     }
     

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestInsertImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -67,10 +67,10 @@
     
     public static org.teiid.query.sql.lang.Insert helpExample2(String groupName) {
         GroupSymbol group = TestGroupImpl.helpExample(groupName);
-        ArrayList elements = new ArrayList();
+        ArrayList<ElementSymbol> elements = new ArrayList<ElementSymbol>();
         elements.add(TestElementImpl.helpExample(groupName, "e1")); //$NON-NLS-1$
         
-        ArrayList values = new ArrayList();
+        ArrayList<org.teiid.query.sql.symbol.Expression> values = new ArrayList<org.teiid.query.sql.symbol.Expression>();
         values.add(TestSearchedCaseExpressionImpl.helpExample());
         
         return new org.teiid.query.sql.lang.Insert(group,
@@ -94,9 +94,6 @@
         Insert insert = example("a.b"); //$NON-NLS-1$
         assertNotNull(insert.getColumns());
         assertEquals(4, insert.getColumns().size());
-        for (Iterator i = insert.getColumns().iterator(); i.hasNext();) {
-            assertTrue(i.next() instanceof ColumnReference);
-        }
 
         // verify that elements are not qualified by group
         String sInsertSQL = insert.toString();

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TestMetadataFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,39 +24,61 @@
  */
 package org.teiid.dqp.internal.datamgr;
 
-import java.util.List;
+import static org.junit.Assert.assertEquals;
 
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.LinkedHashMap;
+import java.util.Map;
 
-import junit.framework.TestCase;
+import org.jboss.vfs.VFS;
+import org.jboss.vfs.VirtualFile;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.query.metadata.CompositeMetadataStore;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.metadata.TransformationMetadata.Resource;
 
-
-public class TestMetadataFactory  extends TestCase {
-    private RuntimeMetadataImpl metadataFactory;
-    private FakeMetadataObject pm1g1;
+ at SuppressWarnings("nls")
+public class TestMetadataFactory {
+    private static final String MY_RESOURCE_PATH = "my/resource/path";
+	private RuntimeMetadataImpl metadataFactory;
+	static VirtualFile root;
+	static Closeable fileMount;
+	
+	@BeforeClass public static void beforeClass() throws IOException {
+    	FileWriter f = new FileWriter(UnitTestUtil.getTestScratchPath()+"/foo");
+    	f.write("ResourceContents");
+    	f.close();
+    	
+    	root = VFS.getChild("location");
+    	fileMount = VFS.mountReal(new File(UnitTestUtil.getTestScratchPath()), root);		
+	}
+	
+	@AfterClass public static void afterClass() throws IOException {
+		fileMount.close();
+	}
     
-    public TestMetadataFactory(String name) {
-        super(name);
+    @Before public void setUp() {
+        MetadataStore metadataStore = new MetadataStore();
+        CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
+    	VDBMetaData vdbMetaData = new VDBMetaData();
+    	vdbMetaData.setName("foo"); //$NON-NLS-1$
+    	vdbMetaData.setVersion(1);
+    	Map<String, Resource> vdbEntries = new LinkedHashMap<String, Resource>();
+    	vdbEntries.put(MY_RESOURCE_PATH, new Resource(root.getChild("foo"), true));
+        metadataFactory = new RuntimeMetadataImpl(new TransformationMetadata(vdbMetaData, store, vdbEntries, null, null));
     }
     
-    public void setUp(){
-        FakeMetadataStore store = new FakeMetadataStore();
-        pm1g1 = FakeMetadataFactory.createPhysicalGroup("pm1.g1", FakeMetadataFactory.createPhysicalModel("pm1.g1")); //$NON-NLS-1$ //$NON-NLS-2$
-        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        store.addObject(pm1g1);
-        store.addObjects(pm1g1e);
-        metadataFactory = new RuntimeMetadataImpl(new FakeMetadataFacade(store));
-    }
-    
-    public void testGetVDBResourcePaths() throws Exception {
-        String[] expectedPaths = new String[] {"my/resource/path"}; //$NON-NLS-1$
+    @Test public void testGetVDBResourcePaths() throws Exception {
+        String[] expectedPaths = new String[] {MY_RESOURCE_PATH}; //$NON-NLS-1$
         String[] mfPaths = metadataFactory.getVDBResourcePaths();
         assertEquals(expectedPaths.length, mfPaths.length);
         for (int i = 0; i < expectedPaths.length; i++) {
@@ -64,17 +86,17 @@
         }
     }
      
-    public void testGetBinaryVDBResource() throws Exception {
+    @Test public void testGetBinaryVDBResource() throws Exception {
         byte[] expectedBytes = "ResourceContents".getBytes(); //$NON-NLS-1$
-        byte[] mfBytes =  metadataFactory.getBinaryVDBResource(null);
+        byte[] mfBytes =  metadataFactory.getBinaryVDBResource(MY_RESOURCE_PATH);
         assertEquals(expectedBytes.length, mfBytes.length);
         for (int i = 0; i < expectedBytes.length; i++) {
             assertEquals("Byte at index " + i + " differs from expected content", expectedBytes[i], mfBytes[i]); //$NON-NLS-1$ //$NON-NLS-2$
         }
     }
      
-    public void testGetCharacterVDBResource() throws Exception {
-        assertEquals("ResourceContents", metadataFactory.getCharacterVDBResource(null)); //$NON-NLS-1$
+    @Test public void testGetCharacterVDBResource() throws Exception {
+        assertEquals("ResourceContents", metadataFactory.getCharacterVDBResource(MY_RESOURCE_PATH)); //$NON-NLS-1$
     }
      
 }

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/datamgr/TstLanguageBridgeFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,12 +25,12 @@
 import org.teiid.dqp.internal.datamgr.LanguageBridgeFactory;
 import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
 import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TstLanguageBridgeFactory {
     
-    public static final QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+    public static final QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     public static final RuntimeMetadataImpl metadataFactory = new RuntimeMetadataImpl(metadata);
     public static final LanguageBridgeFactory factory = new LanguageBridgeFactory(metadata);
 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestAuthorizationValidationVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,29 +29,25 @@
 import java.util.HashSet;
 import java.util.Set;
 
-import org.junit.Ignore;
+import org.junit.Before;
 import org.junit.Test;
 import org.teiid.adminapi.DataPolicy;
 import org.teiid.adminapi.DataPolicy.PermissionType;
 import org.teiid.adminapi.impl.DataPolicyMetadata;
+import org.teiid.adminapi.impl.SessionMetadata;
 import org.teiid.adminapi.impl.VDBMetaData;
 import org.teiid.adminapi.impl.DataPolicyMetadata.PermissionMetaData;
 import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.api.exception.query.QueryValidatorException;
 import org.teiid.core.TeiidComponentException;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionTree;
 import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.FakeFunctionMetadataSource;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
 import org.teiid.query.validator.Validator;
 import org.teiid.query.validator.ValidatorFailure;
 import org.teiid.query.validator.ValidatorReport;
@@ -60,6 +56,13 @@
 public class TestAuthorizationValidationVisitor {
 
     public static final String CONN_ID = "connID"; //$NON-NLS-1$
+    private CommandContext context;
+    
+    @Before public void setup() {
+    	context = new CommandContext();
+    	context.setSession(new SessionMetadata());
+    	context.setDQPWorkContext(new DQPWorkContext());
+    }
 
     PermissionMetaData addResource(PermissionType type, boolean flag, String resource) {
     	PermissionMetaData p = new PermissionMetaData();
@@ -133,7 +136,7 @@
         svc.addPermission(addResource(DataPolicy.PermissionType.DELETE, "pm1.g4.e2")); //$NON-NLS-1$
 
         svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.sq1")); //$NON-NLS-1$
-        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "foo.xyz")); //$NON-NLS-1$
+        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "pm1.xyz")); //$NON-NLS-1$
         
         return svc;
     }
@@ -153,6 +156,9 @@
         // pm3.g2
         svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm3.g2.e1")); //$NON-NLS-1$
         svc.addPermission(addResource(DataPolicy.PermissionType.CREATE, "pm3.g2.e2")); //$NON-NLS-1$
+        
+        svc.addPermission(addResource(DataPolicy.PermissionType.READ, "xmltest.doc1")); //$NON-NLS-1$
+        
         svc.setAllowCreateTemporaryTables(false);
         return svc;
     }
@@ -173,9 +179,10 @@
         
         HashMap<String, DataPolicy> policies = new HashMap<String, DataPolicy>();
         policies.put(policy.getName(), policy);
-        
-        AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(policies, "test"); //$NON-NLS-1$
-        visitor.setAllowFunctionCallsByDefault(false);
+        this.context.getDQPWorkContext().setPolicies(policies);
+        DataRolePolicyDecider dataRolePolicyDecider = new DataRolePolicyDecider();
+        dataRolePolicyDecider.setAllowFunctionCallsByDefault(false);
+        AuthorizationValidationVisitor visitor = new AuthorizationValidationVisitor(dataRolePolicyDecider, context); //$NON-NLS-1$
         ValidatorReport report = Validator.validate(command, metadata, visitor);
         if(report.hasItems()) {
             ValidatorFailure firstFailure = report.getItems().iterator().next();
@@ -199,148 +206,125 @@
     
     @Test public void testTemp() throws Exception {
     	//allowed by default
-    	helpTest(exampleAuthSvc1(), "create local temporary table x (y string)", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    	helpTest(exampleAuthSvc1(), "create local temporary table x (y string)", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     	//explicitly denied
-        helpTest(exampleAuthSvc2(), "create local temporary table x (y string)", FakeMetadataFactory.example1Cached(), new String[] {"x"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ 
+        helpTest(exampleAuthSvc2(), "create local temporary table x (y string)", RealMetadataFactory.example1Cached(), new String[] {"x"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
     
     @Test public void testFunction() throws Exception {
-    	FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new FakeFunctionMetadataSource()));
-        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
-    	helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g1 where xyz() > 0", metadata, new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
-        helpTest(exampleAuthSvc2(), "SELECT e1, curdate() FROM pm1.g2 where xyz() > 0", metadata, new String[] {"xyz()"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+    	helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g1 where xyz() > 0", metadata, new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc2(), "SELECT e1, curdate() FROM pm1.g2 where xyz() > 0", metadata, new String[] {"xyz()"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ 
     }
     
     @Test public void testEverythingAccessible() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g1", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
     
     @Test public void testEverythingAccessible1() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1 FROM (select e1 from pm1.g1) x", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "SELECT e1 FROM (select e1 from pm1.g1) x", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
     
     @Test public void testEverythingAccessible2() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e1', '1'), e1 FROM (select e1 from pm1.g1) x", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e1', '1'), e1 FROM (select e1 from pm1.g1) x", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
 
     @Test public void testInaccesibleElement() throws Exception {        
-        helpTest(exampleAuthSvc1(), "SELECT e2 FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "SELECT e2 FROM pm1.g1", RealMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testInaccesibleElement2() throws Exception {        
-        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e2', '1')", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "SELECT lookup('pm1.g1', 'e1', 'e2', '1')", RealMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testInaccesibleGroup() throws Exception {        
-        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g2", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2", "pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        helpTest(exampleAuthSvc1(), "SELECT e1 FROM pm1.g2", RealMetadataFactory.example1Cached(), new String[] {"pm1.g2", "pm1.g2.e1"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     }
 
     @Test public void testInsert() throws Exception {        
-        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
 
     @Test public void testInsertInaccessible() throws Exception {        
-        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g2 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "INSERT INTO pm1.g2 (e1, e2, e3, e4) VALUES ('x', 5, {b'true'}, 1.0)", RealMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testUpdate() throws Exception {        
-        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e2 = 5", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e2 = 5", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
 
     @Test public void testUpdateCriteriaInaccessibleForRead() throws Exception {        
-        helpTest(exampleAuthSvc1(), "UPDATE pm1.g2 SET e2 = 5 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "UPDATE pm1.g2 SET e2 = 5 WHERE e1 = 'x'", RealMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testUpdateCriteriaInaccessibleForRead1() throws Exception {        
-        helpTest(exampleAuthSvc1(), "UPDATE pm1.g2 SET e2 = cast(e1 as integer)", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "UPDATE pm1.g2 SET e2 = cast(e1 as integer)", RealMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testUpdateElementInaccessibleForUpdate() throws Exception {        
-        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e1 = 5 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "UPDATE pm1.g1 SET e1 = 5 WHERE e1 = 'x'", RealMetadataFactory.example1Cached(), new String[] {"pm1.g1.e1"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testDelete() throws Exception {        
-        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g1", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
 
     @Test public void testDeleteCriteriaInaccesibleForRead() throws Exception {        
-        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g2 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g2 WHERE e1 = 'x'", RealMetadataFactory.example1Cached(), new String[] {"pm1.g2.e1"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testDeleteInaccesibleGroup() throws Exception {        
-        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g3", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g3"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "DELETE FROM pm1.g3", RealMetadataFactory.example1Cached(), new String[] {"pm1.g3"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testProc() throws Exception {
-        helpTest(exampleAuthSvc1(), "EXEC pm1.sq1()", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB());         //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "EXEC pm1.sq1()", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB());         //$NON-NLS-1$
     }
 
     @Test public void testProcInaccesible() throws Exception {
-        helpTest(exampleAuthSvc1(), "EXEC pm1.sq2('xyz')", FakeMetadataFactory.example1Cached(), new String[] {"pm1.sq2"}, FakeMetadataFactory.example1VDB());         //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "EXEC pm1.sq2('xyz')", RealMetadataFactory.example1Cached(), new String[] {"pm1.sq2"}, RealMetadataFactory.example1VDB());         //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testSelectIntoEverythingAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm1.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm1.g2 FROM pm2.g1", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
 
     @Test public void testSelectIntoTarget_e1_NotAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm2.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm2.g2.e2","pm2.g2.e4","pm2.g2.e3"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm2.g2 FROM pm2.g1", RealMetadataFactory.example1Cached(), new String[] {"pm2.g2", "pm2.g2.e2","pm2.g2.e4","pm2.g2.e3"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
     }
 
     @Test public void testSelectIntoTarget_e1e2_NotAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm3.g2 FROM pm2.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm3.g2.e4", "pm3.g2.e3"},FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        helpTest(exampleAuthSvc2(), "SELECT e1, e2, e3, e4 INTO pm3.g2 FROM pm2.g1", RealMetadataFactory.example1Cached(), new String[] {"pm3.g2", "pm3.g2.e4", "pm3.g2.e3"},RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     }
     
     @Test public void testTempTableSelectInto() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1 INTO #temp FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "SELECT e1 INTO #temp FROM pm1.g1", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc2(), "SELECT e1 INTO #temp FROM pm1.g1", RealMetadataFactory.example1Cached(), new String[] {"#temp"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
     
     @Test public void testTempTableSelectInto1() throws Exception {
-        helpTest(exampleAuthSvc1(), "SELECT e1, e2 INTO #temp FROM pm1.g1", FakeMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "SELECT e1, e2 INTO #temp FROM pm1.g1", RealMetadataFactory.example1Cached(), new String[] {"pm1.g1.e2"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testTempTableInsert() throws Exception {
-        helpTest(exampleAuthSvc2(), "insert into #temp (e1, e2, e3, e4) values ('1', '2', '3', '4')", FakeMetadataFactory.example1Cached(), new String[] {}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc1(), "insert into #temp (e1, e2, e3, e4) values ('1', '2', '3', '4')", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
+        helpTest(exampleAuthSvc2(), "insert into #temp (e1, e2, e3, e4) values ('1', '2', '3', '4')", RealMetadataFactory.example1Cached(), new String[] {"#temp"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$
     }
-
+    
     @Test public void testXMLAccessible() throws Exception {
-        helpTest(exampleAuthSvc2(), "select * from xmltest.doc1", FakeMetadataFactory.example1Cached(), new String[] {"xmltest.doc1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc2(), "select * from xmltest.doc1", RealMetadataFactory.example1Cached(), new String[] {}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testXMLInAccessible() throws Exception {
-        helpTest(exampleAuthSvc1(), "select * from xmltest.doc1", FakeMetadataFactory.example1Cached(), new String[] {"xmltest.doc1"}, FakeMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "select * from xmltest.doc1", RealMetadataFactory.example1Cached(), new String[] {"xmltest.doc1"}, RealMetadataFactory.example1VDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testAlter() throws Exception {
-        helpTest(exampleAuthSvc1(), "alter view SmallA_2589 as select * from bqt1.smalla", RealMetadataFactory.exampleBQTCached(), new String[] {"SmallA_2589"}, FakeMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
-        helpTest(examplePolicyBQT(), "alter view SmallA_2589 as select * from bqt1.smalla", RealMetadataFactory.exampleBQTCached(), new String[] {}, FakeMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "alter view SmallA_2589 as select * from bqt1.smalla", RealMetadataFactory.exampleBQTCached(), new String[] {"SmallA_2589"}, RealMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(examplePolicyBQT(), "alter view SmallA_2589 as select * from bqt1.smalla", RealMetadataFactory.exampleBQTCached(), new String[] {}, RealMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
         
-        helpTest(exampleAuthSvc1(), "alter trigger on SmallA_2589 INSTEAD OF UPDATE enabled", RealMetadataFactory.exampleBQTCached(), new String[] {"SmallA_2589"}, FakeMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
-        helpTest(examplePolicyBQT(), "alter trigger on SmallA_2589 INSTEAD OF UPDATE enabled", RealMetadataFactory.exampleBQTCached(), new String[] {}, FakeMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(exampleAuthSvc1(), "alter trigger on SmallA_2589 INSTEAD OF UPDATE enabled", RealMetadataFactory.exampleBQTCached(), new String[] {"SmallA_2589"}, RealMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTest(examplePolicyBQT(), "alter trigger on SmallA_2589 INSTEAD OF UPDATE enabled", RealMetadataFactory.exampleBQTCached(), new String[] {}, RealMetadataFactory.exampleBQTVDB()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
-	private void helpTestLookupVisibility(boolean visible) throws QueryParserException, QueryValidatorException, TeiidComponentException {
-		VDBMetaData vdb = FakeMetadataFactory.example1VDB();
-		vdb.getModel("pm1").setVisible(visible); //$NON-NLS-1$
-		AuthorizationValidationVisitor mvvv = new AuthorizationValidationVisitor(new HashMap<String, DataPolicy>(), "test"); //$NON-NLS-1$
-		String sql = "select lookup('pm1.g1', 'e1', 'e2', 1)"; //$NON-NLS-1$
-		Command command = QueryParser.getQueryParser().parseCommand(sql);
-		Request.validateWithVisitor(mvvv, FakeMetadataFactory.example1Cached(), command);
-	}
-	
-	@Ignore("visibility no longer ristricts access")
-	@Test public void testLookupVisibility() throws Exception {
-		helpTestLookupVisibility(true);
-	}
-	
-	@Ignore("visibility no longer ristricts access")
-	@Test public void testLookupVisibilityFails() throws Exception {
-		try {
-			helpTestLookupVisibility(false);
-			fail("expected exception"); //$NON-NLS-1$
-		} catch (QueryValidatorException e) {
-			assertEquals("Group does not exist: pm1.g1", e.getMessage()); //$NON-NLS-1$
-		}
-	}
-
 }

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCachedResults.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,7 +40,6 @@
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
@@ -91,9 +90,9 @@
 		
 		CachedResults cachedResults = UnitTestUtil.helpSerialize(results);
 		
-		FakeMetadataFactory.buildWorkContext(RealMetadataFactory.exampleBQT());
+		RealMetadataFactory.buildWorkContext(RealMetadataFactory.exampleBQT());
 		
-		cachedResults.restore(cache, bm);
+		assertTrue(cachedResults.restore(cache, bm));
 		
 		// since restored, simulate a async cache flush
 		cache.clear();
@@ -107,5 +106,10 @@
 		assertArrayEquals(tb.getBatch(1).getAllTuples(), cachedTb.getBatch(1).getAllTuples());
 		assertArrayEquals(tb.getBatch(9).getAllTuples(), cachedTb.getBatch(9).getAllTuples());
 		assertTrue(ts - cachedResults.getAccessInfo().getCreationTime() <= 5000);
+		
+		//ensure that an incomplete load fails
+		cache.remove(results.getId()+","+1); //$NON-NLS-1$
+		cachedResults = UnitTestUtil.helpSerialize(results);
+		assertFalse(cachedResults.restore(cache, bm));
 	}	
 }

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,7 +32,7 @@
 import org.junit.Test;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.query.processor.HardcodedDataManager;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestCallableStatement {
@@ -41,7 +41,7 @@
 		String sql = "{? = call pm4.spTest9()}"; //$NON-NLS-1$
 
 		try {
-			TestPreparedStatement.helpTestProcessing(sql, Collections.EMPTY_LIST, null, new HardcodedDataManager(), FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
+			TestPreparedStatement.helpTestProcessing(sql, Collections.EMPTY_LIST, null, new HardcodedDataManager(), RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
 			fail();
 		} catch (QueryResolverException e) {
 			assertEquals("Required parameter 'pm4.spTest9.inkey' has no value was set or is an invalid parameter.", e.getMessage()); //$NON-NLS-1$
@@ -60,7 +60,7 @@
 		HardcodedDataManager dataManager = new HardcodedDataManager();
 		dataManager.addData("? = EXEC pm4.spTest9(1)", expected);
 		
-		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
+		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
 	}
 	
 	/**
@@ -79,7 +79,7 @@
 		HardcodedDataManager dataManager = new HardcodedDataManager();
 		dataManager.addData("EXEC pm4.spTest9(1)", expected);
 		
-		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
+		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
 	}
 		
 	@Test public void testOutParameter() throws Exception {
@@ -94,7 +94,7 @@
 		HardcodedDataManager dataManager = new HardcodedDataManager();
 		dataManager.addData("EXEC pm2.spTest8(2)", expected);
 		
-		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
+		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
 	}
 	
 	@Test(expected=QueryResolverException.class) public void testInvalidReturn() throws Exception {
@@ -105,7 +105,7 @@
 		List[] expected = new List[0];
 		
 		HardcodedDataManager dataManager = new HardcodedDataManager();
-		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
+		TestPreparedStatement.helpTestProcessing(sql, values, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
 	}
 	
 	@Test public void testInputExpression() throws Exception {
@@ -117,7 +117,7 @@
 		HardcodedDataManager dataManager = new HardcodedDataManager();
 		dataManager.addData("EXEC pm2.spTest8(1)", expected);
 		
-		TestPreparedStatement.helpTestProcessing(sql, null, expected, dataManager, FakeMetadataFactory.exampleBQTCached(), true, FakeMetadataFactory.exampleBQTVDB());
+		TestPreparedStatement.helpTestProcessing(sql, null, expected, dataManager, RealMetadataFactory.exampleBQTCached(), true, RealMetadataFactory.exampleBQTVDB());
 	}
 
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestCallableStatement.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestConnectorCapabilitiesFinder.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,11 +22,11 @@
 
 package org.teiid.dqp.internal.process;
 
+import static org.junit.Assert.*;
+
 import java.util.ArrayList;
-import java.util.List;
 
-import junit.framework.TestCase;
-
+import org.junit.Test;
 import org.mockito.Mockito;
 import org.teiid.adminapi.impl.ModelMetaData;
 import org.teiid.adminapi.impl.VDBMetaData;
@@ -34,26 +34,18 @@
 import org.teiid.dqp.internal.datamgr.CapabilitiesConverter;
 import org.teiid.dqp.internal.datamgr.ConnectorManager;
 import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
-import org.teiid.metadata.FunctionMethod;
-import org.teiid.metadata.FunctionParameter;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities;
 import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.TranslatorException;
 
 
 /**
  */
-public class TestConnectorCapabilitiesFinder extends TestCase {
+ at SuppressWarnings("nls")
+public class TestConnectorCapabilitiesFinder {
 
-    /**
-     * Constructor for TestConnectorCapabilitiesFinder.
-     * @param name
-     */
-    public TestConnectorCapabilitiesFinder(String name) {
-        super(name);
-    }
-
-    public void testFind() throws Exception {
+    @Test public void testFind() throws Exception {
         String modelName = "model"; //$NON-NLS-1$
         String functionName = "fakeFunction"; //$NON-NLS-1$
         
@@ -84,19 +76,17 @@
     }
 
     
-    public void testPushdownFunctionSupport() throws Exception {
+    @Test public void testPushdownFunctionSupport() throws Exception {
     	ExecutionFactory<Object, Object> ef  = new ExecutionFactory<Object, Object>(){
-    	    public List<FunctionMethod> getPushDownFunctions(){
-    	    	ArrayList<FunctionMethod> list = new ArrayList<FunctionMethod>();
-    	    	list.add(new FunctionMethod("ns.func", "function", "misc",   //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-    	                new FunctionParameter[] {
-    	                new FunctionParameter("param", DataTypeManager.DefaultDataTypes.STRING, "")}, //$NON-NLS-1$ //$NON-NLS-2$
-    	                new FunctionParameter("result", DataTypeManager.DefaultDataTypes.STRING, "" ) )); //$NON-NLS-1$ //$NON-NLS-2$    	    	
-    	    	return list;
-    	    }    		
+    		
+    		@Override
+    		public void start() throws TranslatorException {
+    			super.start();
+    			addPushDownFunction("ns", "func", DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING);
+    		}
     	};
-    	
+    	ef.start();
     	BasicSourceCapabilities bsc = CapabilitiesConverter.convertCapabilities(ef, "conn"); //$NON-NLS-1$
-        assertEquals("Did not get expected capabilities", true, bsc.supportsFunction("ns.func")); //$NON-NLS-1$ //$NON-NLS-2$
+        assertTrue("Did not get expected capabilities", bsc.supportsFunction("ns.func")); //$NON-NLS-1$ //$NON-NLS-2$
     }
 }

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,9 +41,13 @@
 import org.teiid.client.RequestMessage;
 import org.teiid.client.ResultsMessage;
 import org.teiid.client.RequestMessage.StatementType;
+import org.teiid.client.lob.LobChunk;
+import org.teiid.client.util.ResultsFuture;
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.common.buffer.BufferManagerFactory;
 import org.teiid.common.buffer.impl.BufferManagerImpl;
+import org.teiid.core.TeiidProcessingException;
+import org.teiid.core.types.BlobType;
 import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
 import org.teiid.dqp.internal.datamgr.FakeTransactionService;
 import org.teiid.dqp.internal.process.AbstractWorkItem.ThreadState;
@@ -52,19 +56,52 @@
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestDQPCore {
 
-    private DQPCore core;
+    private final class LobThread extends Thread {
+		BlobType bt;
+		private final RequestMessage reqMsg;
+		volatile ResultsFuture<LobChunk> chunkFuture;
+		protected DQPWorkContext workContext;
+
+		private LobThread(RequestMessage reqMsg) {
+			this.reqMsg = reqMsg;
+		}
+		
+		@Override
+		public void run() {
+			synchronized (this) {
+				while (workContext == null) {
+					try {
+						this.wait();
+					} catch (InterruptedException e) {
+					}
+				}
+			}
+			workContext.runInContext(new Runnable() {
+				
+				@Override
+				public void run() {
+					try {
+						chunkFuture = core.requestNextLobChunk(1, reqMsg.getExecutionId(), bt.getReferenceStreamId());
+					} catch (TeiidProcessingException e) {
+						e.printStackTrace();
+					}
+				}
+			});
+		}
+	}
+
+	private DQPCore core;
     private DQPConfiguration config;
     private AutoGenDataService agds;
 
     @Before public void setUp() throws Exception {
     	agds = new AutoGenDataService();
-        DQPWorkContext context = FakeMetadataFactory.buildWorkContext(RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.exampleBQTCached().getMetadataStore(), "bqt"));
+        DQPWorkContext context = RealMetadataFactory.buildWorkContext(RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.exampleBQTCached().getMetadataStore(), "bqt"));
         context.getVDB().getModel("BQT3").setVisible(false); //$NON-NLS-1$
         context.getVDB().getModel("VQT").setVisible(false); //$NON-NLS-1$
 
@@ -326,6 +363,27 @@
     	assertEquals(1, agds.getExecuteCount().get());
     }
     
+    @Test public void testUsingFinalBuffer() throws Exception {
+    	String sql = "select intkey from bqt1.smalla union select 1";
+    	((BufferManagerImpl)core.getBufferManager()).setProcessorBatchSize(2);
+    	agds.sleep = 500;
+        RequestMessage reqMsg = exampleRequestMessage(sql);
+        Future<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+        ResultsMessage rm = message.get(500000, TimeUnit.MILLISECONDS);
+        assertNull(rm.getException());
+        assertEquals(1, rm.getResults().length);
+
+        message = core.processCursorRequest(reqMsg.getExecutionId(), 3, 2);
+        rm = message.get(500000, TimeUnit.MILLISECONDS);
+        assertNull(rm.getException());
+        assertEquals(1, rm.getResults().length);
+        
+        message = core.processCursorRequest(reqMsg.getExecutionId(), 3, 2);
+        rm = message.get(500000, TimeUnit.MILLISECONDS);
+        assertNull(rm.getException());
+        assertEquals(0, rm.getResults().length);
+    }
+    
     @Test public void testPreparedPlanInvalidation() throws Exception {
         String sql = "insert into #temp select * FROM vqt.SmallB"; //$NON-NLS-1$
         String userName = "1"; //$NON-NLS-1$
@@ -412,6 +470,34 @@
         assertEquals(1, this.core.getRsCache().getCacheHitCount());
     }
     
+    @Test public void testLobConcurrency() throws Exception {
+    	RequestMessage reqMsg = exampleRequestMessage("select to_bytes(stringkey, 'utf-8') FROM BQT1.SmallA"); 
+        reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_OFF);
+        agds.setSleep(100);
+        ResultsFuture<ResultsMessage> message = core.executeRequest(reqMsg.getExecutionId(), reqMsg);
+        final LobThread t = new LobThread(reqMsg);
+        t.start();
+        message.addCompletionListener(new ResultsFuture.CompletionListener<ResultsMessage>() {
+        	@Override
+        	public void onCompletion(ResultsFuture<ResultsMessage> future) {
+        		try {
+        			final BlobType bt = (BlobType)future.get().getResults()[0].get(0);
+        			t.bt = bt;
+        			t.workContext = DQPWorkContext.getWorkContext();
+        			synchronized (t) {
+            			t.notify();
+					}
+        			Thread.sleep(100); //give the Thread a chance to run
+				} catch (Exception e) {
+					throw new RuntimeException(e);
+				}
+        	}
+		});
+        message.get();
+        t.join();
+        assertNotNull(t.chunkFuture.get().getBytes());
+    }
+    
 	public void helpTestVisibilityFails(String sql) throws Exception {
         RequestMessage reqMsg = exampleRequestMessage(sql); 
         reqMsg.setTxnAutoWrapMode(RequestMessage.TXN_WRAP_OFF);


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCore.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPCoreRequestHandling.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDQPWorkContext.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,7 +41,7 @@
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 public class TestDataTierManager {
@@ -72,8 +72,8 @@
     }
     
     private void helpSetup(String sql, int nodeId) throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.exampleBQTVDB());
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.exampleBQTVDB());
         
         rm = new DQPCore();
         rm.setTransactionService(new FakeTransactionService());


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestDataTierManager.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,10 +24,12 @@
 
 import static org.junit.Assert.*;
 
+import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import org.junit.Test;
+import org.teiid.adminapi.impl.ModelMetaData;
 import org.teiid.adminapi.impl.VDBMetaData;
 import org.teiid.client.RequestMessage;
 import org.teiid.client.metadata.MetadataResult;
@@ -35,11 +37,17 @@
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.dqp.internal.datamgr.FakeTransactionService;
 import org.teiid.dqp.message.RequestID;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 /**
@@ -57,7 +65,7 @@
         DQPCore requestMgr = new DQPCore();
         requestMgr.setTransactionService(new FakeTransactionService());
 
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, vdb);
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
 
         // Initialize components
         RequestID requestID = workContext.getRequestID(1);  
@@ -70,27 +78,27 @@
     }
     
     @Test public void testSimpleQuery() throws Exception {
-        Map[] metadata = helpGetMetadata("SELECT e1 FROM pm1.g1", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        Map[] metadata = helpGetMetadata("SELECT e1 FROM pm1.g1", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNotNull(metadata);
         assertEquals(1, metadata.length);
     }
 
     @Test public void testSimpleUpdate() throws Exception {
-        Map[] metadata = helpGetMetadata("INSERT INTO pm1.g1 (e1) VALUES ('x')", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        Map[] metadata = helpGetMetadata("INSERT INTO pm1.g1 (e1) VALUES ('x')", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNull(metadata);
         
-        metadata = helpGetMetadata("DELETE FROM pm1.g1 WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        metadata = helpGetMetadata("DELETE FROM pm1.g1 WHERE e1 = 'x'", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNull(metadata);
         
-        metadata = helpGetMetadata("UPDATE pm1.g1 SET e1='y' WHERE e1 = 'x'", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        metadata = helpGetMetadata("UPDATE pm1.g1 SET e1='y' WHERE e1 = 'x'", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNull(metadata);
         
-        metadata = helpGetMetadata("SELECT e1, e2, e3, e4 INTO pm1.g2 FROM pm1.g1", FakeMetadataFactory.example1Cached(),FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        metadata = helpGetMetadata("SELECT e1, e2, e3, e4 INTO pm1.g2 FROM pm1.g1", RealMetadataFactory.example1Cached(),RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNull(metadata);
     }
     
     @Test public void testElementLabel() throws Exception {
-    	Map[] metadata = helpGetMetadata("SELECT E2 FROM pm1.g1", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+    	Map[] metadata = helpGetMetadata("SELECT E2 FROM pm1.g1", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNotNull(metadata);
         assertEquals(1, metadata.length);
         assertEquals("e2", metadata[0].get(ResultsMetadataConstants.ELEMENT_NAME)); //$NON-NLS-1$
@@ -98,13 +106,13 @@
     }
     
     @Test public void testSimpleExec() throws Exception {
-        Map[] metadata = helpGetMetadata("EXEC pm1.sq1()", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        Map[] metadata = helpGetMetadata("EXEC pm1.sq1()", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNotNull(metadata);
         assertEquals(2, metadata.length);        
     }
     
     @Test public void testExecNoResultColumns() throws Exception {
-        Map[] metadata = helpGetMetadata("EXEC pm1.sp5()", FakeMetadataFactory.example1Cached(), FakeMetadataFactory.example1VDB()); //$NON-NLS-1$
+        Map[] metadata = helpGetMetadata("EXEC pm1.sp5()", RealMetadataFactory.example1Cached(), RealMetadataFactory.example1VDB()); //$NON-NLS-1$
         assertNotNull(metadata);
         assertEquals(0, metadata.length);                
     }
@@ -116,7 +124,7 @@
         // Initialize components
         MetaDataProcessor mdProc = new MetaDataProcessor(new DQPCore(), prepPlanCache, "MyVDB", 1);
                      
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, vdb);
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
         return mdProc.processMessage(workContext.getRequestID(1), workContext, sql, true);    
     }
 
@@ -129,25 +137,35 @@
     }
 
     @Test public void testDefect16629_moneyType() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.examplePrivatePhysicalModel(); 
+        QueryMetadataInterface metadata = TestMetaDataProcessor.examplePrivatePhysicalModel(); 
         String sql = "SELECT e1 FROM pm1.g2"; //$NON-NLS-1$
         
-        MetadataResult response = helpTestQuery(metadata, sql, FakeMetadataFactory.examplePrivatePhysicalModelVDB());
+        MetadataResult response = helpTestQuery(metadata, sql, TestMetaDataProcessor.examplePrivatePhysicalModelVDB());
         
         helpCheckNumericAttributes(response, 0, 21, 19, 4);
     }
 
     @Test public void testDefect16629_aggregatesOnMoneyType() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.examplePrivatePhysicalModel(); 
+        QueryMetadataInterface metadata = TestMetaDataProcessor.examplePrivatePhysicalModel(); 
         String sql = "SELECT min(e1), max(e1), sum(e1), avg(e1) FROM pm1.g2"; //$NON-NLS-1$
         
-        MetadataResult response = helpTestQuery(metadata, sql, FakeMetadataFactory.examplePrivatePhysicalModelVDB());
+        MetadataResult response = helpTestQuery(metadata, sql, TestMetaDataProcessor.examplePrivatePhysicalModelVDB());
         helpCheckNumericAttributes(response, 0, 21, 19, 4);
         helpCheckNumericAttributes(response, 1, 21, 19, 4);
         helpCheckNumericAttributes(response, 2, 22, 20, 0);
         helpCheckNumericAttributes(response, 3, 22, 20, 0);
     }
-    
+
+    @Test public void testWindowFunction() throws Exception {
+        QueryMetadataInterface metadata = TestMetaDataProcessor.examplePrivatePhysicalModel(); 
+        String sql = "SELECT min(e1) over () FROM pm1.g2"; //$NON-NLS-1$
+        
+        MetadataResult response = helpTestQuery(metadata, sql, TestMetaDataProcessor.examplePrivatePhysicalModelVDB());
+        helpCheckNumericAttributes(response, 0, 21, 19, 4);
+        assertEquals("e1", response.getColumnMetadata()[0].get(ResultsMetadataConstants.ELEMENT_NAME)); //$NON-NLS-1$
+        assertEquals("win_min", response.getColumnMetadata()[0].get(ResultsMetadataConstants.ELEMENT_LABEL)); //$NON-NLS-1$
+    }
+
     @Test public void testMetadataGenerationForAllTypes() throws Exception {
         Set<String> dataTypes = DataTypeManager.getAllDataTypeNames();
         for (String type : dataTypes) {
@@ -222,4 +240,52 @@
             fail("Invalid searchable constant value: " + searchable);          //$NON-NLS-1$
         }
     }
+
+	public static TransformationMetadata examplePrivatePhysicalModel() { 
+		MetadataStore metadataStore = new MetadataStore();
+	    // Create models
+	    Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+	    Schema vm1 = RealMetadataFactory.createVirtualModel("vm1", metadataStore);  //$NON-NLS-1$
+	
+	    // Create physical groups
+	    Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+	        
+	    QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table vm1g1 = RealMetadataFactory.createVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+	    
+	    Table pm1g2 = RealMetadataFactory.createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+	    
+	    // Create physical elements
+	    RealMetadataFactory.createElements(pm1g1, 
+	        new String[] { "e1"}, //$NON-NLS-1$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.SHORT});
+	
+	    // Create physical elements
+	    List<Column> pm1g2e = RealMetadataFactory.createElements(pm1g2, 
+	        new String[] { "e1"}, //$NON-NLS-1$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.BIG_DECIMAL});
+	    
+	    Column e1 = pm1g2e.get(0);
+	    e1.setPrecision(19);
+	    e1.setLength(21);
+	    e1.setScale(4);
+	    
+	    RealMetadataFactory.createElements(vm1g1, 
+	                                new String[] { "e1" }, //$NON-NLS-1$
+	                                new String[] { DataTypeManager.DefaultDataTypes.STRING });
+	    // Create the facade from the store
+	    return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
+	}
+
+	public static VDBMetaData examplePrivatePhysicalModelVDB() {
+		VDBMetaData vdb = new VDBMetaData();
+		vdb.setName("example1");
+		vdb.setVersion(1);
+		ModelMetaData m = RealMetadataFactory.createModel("pm1", true);
+		m.setVisible(false);
+		vdb.addModel(m);
+		vdb.addModel(RealMetadataFactory.createModel("vm1", false));
+		
+		return vdb;
+	}
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestMetaDataProcessor.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedPlanCache.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -52,8 +52,7 @@
 import org.teiid.query.processor.HardcodedDataManager;
 import org.teiid.query.processor.ProcessorDataManager;
 import org.teiid.query.processor.TestProcessor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings({"nls", "unchecked"})
 public class TestPreparedStatement {
@@ -151,7 +150,7 @@
 		List<?> values = Arrays.asList((short)0);
 		FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);
-		helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, FakeMetadataFactory.example1VDB());
+		helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, RealMetadataFactory.example1VDB());
 	}
     
     @Test public void testSessionSpecificFunction() throws Exception { 
@@ -168,7 +167,7 @@
         List<?> values = Arrays.asList((short)0);
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);
-		helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, true, FakeMetadataFactory.example1VDB());
+		helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, true, RealMetadataFactory.example1VDB());
 	}
     
     @Test public void testFunctionWithReferencePushDown() throws Exception { 
@@ -192,26 +191,26 @@
         caps.setFunctionSupport("convert", true); //$NON-NLS-1$
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         List values = Arrays.asList(0);
 
-        PreparedStatementRequest plan = helpGetProcessorPlan(preparedSql, values, capFinder, metadata, new SessionAwareCache<PreparedPlan>(), SESSION_ID, false, false,FakeMetadataFactory.example1VDB());
+        PreparedStatementRequest plan = helpGetProcessorPlan(preparedSql, values, capFinder, metadata, new SessionAwareCache<PreparedPlan>(), SESSION_ID, false, false,RealMetadataFactory.example1VDB());
         
         TestOptimizer.checkNodeTypes(plan.processPlan, TestOptimizer.FULL_PUSHDOWN);  
     }
     
 	static public PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values, SessionAwareCache<PreparedPlan> prepPlanCache)
 			throws TeiidComponentException, TeiidProcessingException {    	
-		return helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), prepPlanCache, SESSION_ID, false, false, FakeMetadataFactory.example1VDB());
+		return helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), prepPlanCache, SESSION_ID, false, false, RealMetadataFactory.example1VDB());
     }
 	
 	static public PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values,
 			SessionAwareCache<PreparedPlan> prepPlanCache, int conn)
 			throws TeiidComponentException, TeiidProcessingException {
 		return helpGetProcessorPlan(preparedSql, values,
-				new DefaultCapabilitiesFinder(), FakeMetadataFactory
-						.example1Cached(), prepPlanCache, conn, false, false, FakeMetadataFactory.example1VDB());
+				new DefaultCapabilitiesFinder(), RealMetadataFactory
+						.example1Cached(), prepPlanCache, conn, false, false, RealMetadataFactory.example1VDB());
 	}
 
 	static PreparedStatementRequest helpGetProcessorPlan(String preparedSql, List values,
@@ -233,7 +232,7 @@
         	request.setRowLimit(1);
         }
        
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, vdb);
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
         workContext.getSession().setSessionId(String.valueOf(conn)); 
         
         PreparedStatementRequest serverRequest = new PreparedStatementRequest(prepPlanCache);
@@ -243,7 +242,9 @@
         
         serverRequest.initialize(request, BufferManagerFactory.getStandaloneBufferManager(), null, new FakeTransactionService(), null, workContext, prepPlanCache);
         serverRequest.setMetadata(capFinder, metadata, null);
-        serverRequest.setAuthorizationValidator(new DataRoleAuthorizationValidator(false, true, true));
+        DefaultAuthorizationValidator drav = new DefaultAuthorizationValidator();
+        drav.setEnabled(false);
+        serverRequest.setAuthorizationValidator(drav);
         serverRequest.processRequest();
         
         assertNotNull(serverRequest.processPlan);
@@ -357,9 +358,9 @@
         
         SessionAwareCache<PreparedPlan> planCache = new SessionAwareCache<PreparedPlan>();
         
-		helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), planCache, SESSION_ID, false, true, FakeMetadataFactory.example1VDB());
+		helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), planCache, SESSION_ID, false, true, RealMetadataFactory.example1VDB());
 
-		helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), planCache, SESSION_ID, false, true, FakeMetadataFactory.example1VDB());
+		helpGetProcessorPlan(preparedSql, values, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), planCache, SESSION_ID, false, true, RealMetadataFactory.example1VDB());
 		//make sure the plan wasn't reused
 		assertEquals(0, planCache.getCacheHitCount());
     }
@@ -373,8 +374,8 @@
     
 		List<String> values = Arrays.asList("aa "); //$NON-NLS-1$
         FakeDataManager dataManager = new FakeDataManager();
-        TestProcessor.sampleData2b(dataManager);
-		helpTestProcessing(preparedSql, values, expected, dataManager, TestOptimizer.getGenericFinder(), FakeMetadataFactory.example1Cached(), null, false, false, false, FakeMetadataFactory.example1VDB());
+        TestProcessor.sampleData2b(dataManager, RealMetadataFactory.example1Cached());
+		helpTestProcessing(preparedSql, values, expected, dataManager, TestOptimizer.getGenericFinder(), RealMetadataFactory.example1Cached(), null, false, false, false, RealMetadataFactory.example1VDB());
     }
     
     @Test(expected=QueryValidatorException.class) public void testLimitValidation() throws Exception {
@@ -382,7 +383,7 @@
         
 		List values = Arrays.asList(-1);
         FakeDataManager dataManager = new FakeDataManager();
-		helpTestProcessing(preparedSql, values, null, dataManager, FakeMetadataFactory.example1Cached(), false, false, FakeMetadataFactory.example1VDB());
+		helpTestProcessing(preparedSql, values, null, dataManager, RealMetadataFactory.example1Cached(), false, false, RealMetadataFactory.example1VDB());
     }
     
     @Test public void testExecParam() throws Exception {
@@ -395,7 +396,7 @@
         
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);
-		helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, false, FakeMetadataFactory.example1VDB());
+		helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, false, RealMetadataFactory.example1VDB());
     }
     
     @Test public void testLimitParam() throws Exception {
@@ -408,7 +409,7 @@
         
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);
-		helpTestProcessing(preparedSql, values, expected, dataManager, FakeMetadataFactory.example1Cached(), false, false,FakeMetadataFactory.example1VDB());
+		helpTestProcessing(preparedSql, values, expected, dataManager, RealMetadataFactory.example1Cached(), false, false,RealMetadataFactory.example1VDB());
     }
     
     @Test public void testWithSubqueryPushdown() throws Exception {
@@ -420,14 +421,14 @@
     
 		List values = Arrays.asList("a"); //$NON-NLS-1$
 		
-		QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+		QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         HardcodedDataManager dataManager = new HardcodedDataManager(metadata);
         dataManager.addData("SELECT g_0.e1 FROM g1 AS g_0 WHERE g_0.e2 IN (SELECT g_1.e2 FROM g2 AS g_1 WHERE g_1.e1 = 'a')", new List[] {Arrays.asList("a")});
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
 	    caps.setCapabilitySupport(Capability.CRITERIA_IN_SUBQUERY, true);
         
-		helpTestProcessing(preparedSql, values, expected, dataManager, new DefaultCapabilitiesFinder(caps), metadata, null, false, false, false, FakeMetadataFactory.example1VDB());
+		helpTestProcessing(preparedSql, values, expected, dataManager, new DefaultCapabilitiesFinder(caps), metadata, null, false, false, false, RealMetadataFactory.example1VDB());
     }
     
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatement.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestPreparedStatementBatchedUpdate.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -38,7 +38,7 @@
 import org.teiid.query.processor.TestProcessor;
 import org.teiid.query.sql.lang.Update;
 import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 /**
@@ -74,7 +74,7 @@
         };
     	
     	// Create the plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, false,FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false,RealMetadataFactory.example1VDB());
     	Update update = (Update)dataManager.getCommandHistory().iterator().next();
     	assertTrue(((Constant)update.getChangeList().getClauses().get(0).getValue()).isMultiValued());
     }
@@ -148,7 +148,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = null, e3 = FALSE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
     	
     	// Create the plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, false,FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false,RealMetadataFactory.example1VDB());
 
     	// Repeat with different number of commands in batch
     	// Create expected results
@@ -168,7 +168,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'b', e3 = TRUE WHERE pm1.g1.e2 = 5")); //$NON-NLS-1$
     	
     	// Use the cached plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, true,FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true,RealMetadataFactory.example1VDB());
 
     	// Verify all the queries that were run
     	assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$
@@ -242,7 +242,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e2 = 1 WHERE pm1.g1.e1 = 'b'")); //$NON-NLS-1$
     	
     	// Create the plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, false, FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false, RealMetadataFactory.example1VDB());
 
     	// Repeat
         expected = new List[] { 
@@ -260,7 +260,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e2 = 3 WHERE pm1.g1.e1 = 'd'")); //$NON-NLS-1$
     	
     	// Use the cached plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, true,FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true,RealMetadataFactory.example1VDB());
 
     	// Verify all the queries that were run
     	assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$
@@ -337,7 +337,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = null, e3 = FALSE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
     	
     	// Create the plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, false, FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false, RealMetadataFactory.example1VDB());
 
     	// Repeat with different number of commands in batch
     	// Create expected results
@@ -354,7 +354,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'a', e3 = FALSE WHERE pm1.g1.e2 = 0")); //$NON-NLS-1$
     	
     	// Use the cached plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, true, FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true, RealMetadataFactory.example1VDB());
 
     	// Repeat with different number of commands in batch
 		// Create expected results
@@ -382,7 +382,7 @@
 		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'c', e3 = TRUE WHERE pm1.g1.e2 = 4")); //$NON-NLS-1$
 		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'b', e3 = TRUE WHERE pm1.g1.e2 = 5")); //$NON-NLS-1$
     	
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, true, FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true, RealMetadataFactory.example1VDB());
 
     	// Verify all the queries that were run
     	assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$
@@ -458,7 +458,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'b', e3 = TRUE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
     	
     	// Create the plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, false, FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, false, RealMetadataFactory.example1VDB());
 
     	// Repeat with different number of commands in batch
         expected = new List[] { 
@@ -473,7 +473,7 @@
    		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'c', e3 = FALSE WHERE pm1.g1.e2 = 1")); //$NON-NLS-1$
     	
     	// Use the cached plan and process the query
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, true, FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true, RealMetadataFactory.example1VDB());
 
     	// Repeat with different number of commands in batch
         expected = new List[] { 
@@ -496,7 +496,7 @@
 		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'f', e3 = TRUE WHERE pm1.g1.e2 = 2")); //$NON-NLS-1$
 		finalQueryList.add(new String("UPDATE pm1.g1 SET e1 = 'g', e3 = TRUE WHERE pm1.g1.e2 = 3")); //$NON-NLS-1$
     	
-    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, FakeMetadataFactory.example1Cached(), prepPlanCache, false, false, true,FakeMetadataFactory.example1VDB());
+    	TestPreparedStatement.helpTestProcessing(preparedSql, values, expected, dataManager, capFinder, RealMetadataFactory.example1Cached(), prepPlanCache, false, false, true,RealMetadataFactory.example1VDB());
 
     	// Verify all the queries that were run
     	assertEquals("Unexpected queries executed -", finalQueryList, dataManager.getQueries()); //$NON-NLS-1$

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,6 +30,7 @@
 import org.teiid.client.RequestMessage;
 import org.teiid.client.RequestMessage.StatementType;
 import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
@@ -41,7 +42,7 @@
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.tempdata.TempTableStore;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.ContextProperties;
 
 
@@ -70,18 +71,23 @@
      * @since 4.2
      */
     public void testValidateEntitlement() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         Request request = new Request();
         Command command = QueryParser.getQueryParser().parseCommand(QUERY);
         QueryResolver.resolveCommand(command, metadata);
         
         RequestMessage message = new RequestMessage();
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.example1VDB());
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
         
-        request.initialize(message, null, null,new FakeTransactionService(), TEMP_TABLE_STORE, workContext, null); 
+        request.initialize(message, BufferManagerFactory.getStandaloneBufferManager(), null,new FakeTransactionService(), TEMP_TABLE_STORE, workContext, null); 
         request.initMetadata();
-        request.setAuthorizationValidator(new DataRoleAuthorizationValidator(true, true, true));
+        DefaultAuthorizationValidator drav = new DefaultAuthorizationValidator();
+        DataRolePolicyDecider drpd = new DataRolePolicyDecider();
+        drpd.setAllowCreateTemporaryTablesByDefault(true);
+        drpd.setAllowFunctionCallsByDefault(true);
+        drav.setPolicyDecider(drpd);
+        request.setAuthorizationValidator(drav);
         request.validateAccess(command);
     }
     
@@ -94,12 +100,12 @@
      * @since 4.2
      */
     public void testProcessRequest() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         //Try before plan is cached.
         //If this doesn't throw an exception, assume it was successful.
         RequestMessage message = new RequestMessage(QUERY);
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.example1VDB());
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
 
         helpProcessMessage(message, null, workContext);
         
@@ -110,12 +116,12 @@
     }
     
     public void testCommandContext() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         //Try before plan is cached.
         //If this doesn't throw an exception, assume it was successful.
         RequestMessage message = new RequestMessage(QUERY);
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.example1VDB());
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
         
         Request request = helpProcessMessage(message, null, workContext);
         assertEquals("1", request.context.getEnvironmentProperties().get(ContextProperties.SESSION_ID)); //$NON-NLS-1$
@@ -135,7 +141,9 @@
         
         request.initialize(message, Mockito.mock(BufferManager.class),
 				new FakeDataManager(), new FakeTransactionService(), TEMP_TABLE_STORE, workContext, null);
-        request.setAuthorizationValidator(new DataRoleAuthorizationValidator(false, true, true));
+        DefaultAuthorizationValidator drav = new DefaultAuthorizationValidator();
+        drav.setEnabled(false);
+        request.setAuthorizationValidator(drav);
         request.processRequest();
         return request;
     }
@@ -147,14 +155,14 @@
      * @since 4.2
      */
     public void testProcessRequestPreparedStatement() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         SessionAwareCache<PreparedPlan> cache = new SessionAwareCache<PreparedPlan>();
         
 
         //Try before plan is cached.
         //If this doesn't throw an exception, assume it was successful.
         RequestMessage message = new RequestMessage(QUERY);
-        DQPWorkContext workContext = FakeMetadataFactory.buildWorkContext(metadata, FakeMetadataFactory.example1VDB());
+        DQPWorkContext workContext = RealMetadataFactory.buildWorkContext(metadata, RealMetadataFactory.example1VDB());
         
         message.setStatementType(StatementType.PREPARED);
         message.setParameterValues(new ArrayList());


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestRequest.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,7 +40,6 @@
 		}
 		
 		private TestWorkItem(boolean done, boolean callMoreWork) {
-			super(false);
 			this.isDone = done;
 			this.callMoreWork = callMoreWork;
 		}
@@ -152,5 +151,5 @@
     		
     	}
     }
-        
+    
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/TestWorkItemState.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceElementReplacementVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,7 +32,7 @@
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.navigator.DeepPostOrderNavigator;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 
@@ -43,7 +43,7 @@
 
     public QueryMetadataInterface getMetadata() throws Exception {
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         Set<String> multiSourceModels = new HashSet<String>();
         multiSourceModels.add("MultiModel"); //$NON-NLS-1$
         MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(metadata, multiSourceModels);  

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourceMetadataWrapper.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,7 +30,7 @@
 
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 
@@ -42,7 +42,7 @@
     public void testMultiSourcePseudoElement() throws Exception {
         HashSet<String> multiSourceModels = new HashSet<String>();
         multiSourceModels.add("BQT1");
-        MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(FakeMetadataFactory.exampleBQTCached(), multiSourceModels);
+        MultiSourceMetadataWrapper wrapper = new MultiSourceMetadataWrapper(RealMetadataFactory.exampleBQTCached(), multiSourceModels);
         
         Object groupID = wrapper.getGroupID("BQT1.SmallA"); //$NON-NLS-1$
         List elements = wrapper.getElementIDsInGroupID(groupID);

Modified: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -35,7 +35,6 @@
 import org.teiid.adminapi.impl.VDBMetaData;
 import org.teiid.common.buffer.TupleSource;
 import org.teiid.core.id.IDGenerator;
-import org.teiid.core.id.IntegerIDFactory;
 import org.teiid.dqp.internal.process.DQPWorkContext;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.metadata.QueryMetadataInterface;
@@ -52,8 +51,7 @@
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 /** 
@@ -88,7 +86,7 @@
     
     public void helpTestMultiSourcePlan(QueryMetadataInterface metadata, String userSql, String multiModel, int sourceCount, ProcessorDataManager dataMgr, List[] expectedResults, VDBMetaData vdb) throws Exception {
         
-       DQPWorkContext dqpContext = FakeMetadataFactory.buildWorkContext(metadata, vdb);
+       DQPWorkContext dqpContext = RealMetadataFactory.buildWorkContext(metadata, vdb);
      
         Set<String> multiSourceModels = vdb.getMultiSourceModelNames();
         for (String model:multiSourceModels) {
@@ -114,7 +112,6 @@
         CapabilitiesFinder finder = new MultiSourceCapabilitiesFinder(fakeFinder, multiSourceModels);
         
         IDGenerator idGenerator = new IDGenerator();
-        idGenerator.setDefaultFactory(new IntegerIDFactory());            
         
         Properties props = new Properties();
         CommandContext context = new CommandContext("0", "test", "user", null, vdb.getName(), vdb.getVersion(), props, false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
@@ -131,18 +128,18 @@
     }
 
     @Test public void testNoReplacement() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "SELECT * FROM MultiModel.Phys WHERE SOURCE_NAME = 'bogus'"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 2;
         final List[] expected = 
             new List[0];
         final ProcessorDataManager dataMgr = new MultiSourceDataManager();
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
 
     @Test public void testSingleReplacement() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "SELECT * FROM MultiModel.Phys WHERE SOURCE_NAME = 'a'"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 2;
@@ -150,11 +147,11 @@
             new List[] { Arrays.asList(new Object[] { null, null, null}) };
         final HardcodedDataManager dataMgr = new MultiSourceDataManager();
         dataMgr.setMustRegisterCommands(false);
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testMultiReplacement() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "SELECT * FROM MultiModel.Phys"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
@@ -163,11 +160,11 @@
                          Arrays.asList(new Object[] { null, null, null}),
                          Arrays.asList(new Object[] { null, null, null})};
         final ProcessorDataManager dataMgr = new MultiSourceDataManager();
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testMultiReplacementWithOrderBy() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleMultiBinding();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
 
         final String userSql = "SELECT * FROM MultiModel.Phys order by a"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
@@ -187,11 +184,11 @@
                         new List[] {
                             Arrays.asList("e", "z", "b"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                             Arrays.asList("f", "z", "b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
 
     @Test public void testMultiReplacementWithLimit() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "SELECT distinct * FROM MultiModel.Phys order by a limit 1"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 2;
@@ -207,11 +204,11 @@
                         new List[] {
                             Arrays.asList("e", "z", "b"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                             Arrays.asList("f", "z", "b")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testMultiDependentJoin() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleMultiBinding();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         
         final String userSql = "SELECT a.a FROM MultiModel.Phys a inner join MultiModel.Phys b makedep on (a.a = b.a) order by a"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
@@ -233,31 +230,31 @@
         dataMgr.addData("SELECT g_0.a FROM MultiModel.Phys AS g_0 WHERE g_0.a IN ('x', 'y')",  //$NON-NLS-1$
                         new List[] { Arrays.asList(new Object[] { "x" }), //$NON-NLS-1$
                                      Arrays.asList(new Object[] { "y" })}); //$NON-NLS-1$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testSingleReplacementInDynamicCommand() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "exec Virt.sq1('a')"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
         final List[] expected = new List[] { Arrays.asList(new Object[] { null, null}), };
         final ProcessorDataManager dataMgr = new MultiSourceDataManager();
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testSingleReplacementInDynamicCommandNullValue() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "exec Virt.sq1(null)"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
         final List[] expected = new List[0];
         final ProcessorDataManager dataMgr = new MultiSourceDataManager();
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testMultiUpdateAll() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "update MultiModel.Phys set a = '1' where b = 'z'"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
@@ -265,11 +262,11 @@
         final MultiSourceDataManager dataMgr = new MultiSourceDataManager();
         dataMgr.setMustRegisterCommands(true);
         dataMgr.addData("UPDATE MultiModel.Phys SET a = '1' WHERE b = 'z'", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testInsertMatching() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "INSERT INTO MultiModel.Phys(a, SOURCE_NAME) VALUES ('a', 'a')"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
@@ -277,22 +274,22 @@
         final MultiSourceDataManager dataMgr = new MultiSourceDataManager();
         dataMgr.setMustRegisterCommands(true);
         dataMgr.addData("INSERT INTO MultiModel.Phys (a) VALUES ('a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testInsertNotMatching() throws Exception {
-        final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+        final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "INSERT INTO MultiModel.Phys(a, SOURCE_NAME) VALUES ('a', 'x')"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
         final List[] expected = new List[] { Arrays.asList(0)};
         final MultiSourceDataManager dataMgr = new MultiSourceDataManager();
         dataMgr.setMustRegisterCommands(true);
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testInsertAll() throws Exception {
-    	final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+    	final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "INSERT INTO MultiModel.Phys(a) VALUES ('a')"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
@@ -300,11 +297,11 @@
         final MultiSourceDataManager dataMgr = new MultiSourceDataManager();
         dataMgr.setMustRegisterCommands(true);
         dataMgr.addData("INSERT INTO MultiModel.Phys (a) VALUES ('a')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testProcedure() throws Exception {
-    	final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+    	final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "exec MultiModel.proc('b', 'a')"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
@@ -312,11 +309,11 @@
         final MultiSourceDataManager dataMgr = new MultiSourceDataManager();
         dataMgr.setMustRegisterCommands(true);
         dataMgr.addData("EXEC MultiModel.proc('b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
     
     @Test public void testProcedureAll() throws Exception {
-    	final QueryMetadataInterface metadata = FakeMetadataFactory.exampleMultiBinding();
+    	final QueryMetadataInterface metadata = RealMetadataFactory.exampleMultiBinding();
         final String userSql = "exec MultiModel.proc(\"in\"=>'b')"; //$NON-NLS-1$
         final String multiModel = "MultiModel"; //$NON-NLS-1$
         final int sources = 3;
@@ -324,7 +321,7 @@
         final MultiSourceDataManager dataMgr = new MultiSourceDataManager();
         dataMgr.setMustRegisterCommands(true);
         dataMgr.addData("EXEC MultiModel.proc('b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
-        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, FakeMetadataFactory.exampleMultiBindingVDB());
+        helpTestMultiSourcePlan(metadata, userSql, multiModel, sources, dataMgr, expected, RealMetadataFactory.exampleMultiBindingVDB());
     }
 
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/dqp/internal/process/multisource/TestMultiSourcePlanToProcessConverter.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/engine/src/test/java/org/teiid/query/function/TestFunction.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/function/TestFunction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/function/TestFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1000,9 +1000,10 @@
     }
 
     @Test public void testTimestampDiffTimeStamp_Day_1() throws Exception {
+    	// Moving to June, March fails because of DST
         helpTestTimestampDiff(NonReserved.SQL_TSI_DAY,
-                              TimestampUtil.createTimestamp((2004-1900), 2, 1, 0, 0, 0, 0),
-                              TimestampUtil.createTimestamp((2004-1900), 3, 1, 0, 0, 0, 0),
+                              TimestampUtil.createTimestamp((2004-1900), 4, 1, 0, 0, 0, 0),
+                              TimestampUtil.createTimestamp((2004-1900), 5, 1, 0, 0, 0, 0),
                               new Long(31));
     }
 


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/function/TestFunction.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/function/TestFunction.java:3281-3325
/trunk/engine/src/test/java/org/teiid/query/function/TestFunction.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -55,7 +55,7 @@
 import org.teiid.core.util.TimestampWithTimezone;
 import org.teiid.language.SQLConstants.NonReserved;
 import org.teiid.metadata.FunctionMethod.PushDown;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.unittest.TimestampUtil;
 import org.teiid.query.util.CommandContext;
 import org.teiid.translator.SourceSystemFunctions;
@@ -77,7 +77,7 @@
 	private static final Class<Date> T_DATE = DataTypeManager.DefaultDataClasses.DATE;
 	private static final Class<Timestamp> T_TIMESTAMP = DataTypeManager.DefaultDataClasses.TIMESTAMP;
 	
-	private FunctionLibrary library = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions());
+	private FunctionLibrary library = new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions());
 
 	@Before public void setUp() { 
 		TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$ 
@@ -1408,4 +1408,16 @@
 		assertEquals(1, helpInvokeMethod("array_get", new Class<?>[] {DefaultDataClasses.OBJECT, DefaultDataClasses.INTEGER}, new Object[] {new Object[] {1}, 1}, null)); //$NON-NLS-1$
 	}
 	
+	@Test() public void testTrim() throws Exception {
+		helpInvokeMethod("trim", new Object[] {"leading", "x", "xaxx"}, "axx"); //$NON-NLS-1$
+	}
+
+	@Test() public void testTrim1() throws Exception {
+		helpInvokeMethod("trim", new Object[] {"both", " ", "   a   "}, "a"); //$NON-NLS-1$
+	}
+
+	@Test() public void testTrim2() throws Exception {
+		helpInvokeMethod("trim", new Object[] {"trailing", "x", "xaxx"}, "xa"); //$NON-NLS-1$
+	}
+
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/function/TestFunctionLibrary.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -39,7 +39,7 @@
 import org.teiid.metadata.FunctionMethod.Determinism;
 import org.teiid.query.function.metadata.FunctionCategoryConstants;
 import org.teiid.query.function.source.SystemSource;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestFunctionTree {
@@ -78,11 +78,11 @@
 	 	    	new FunctionParameter("output", DataTypeManager.DefaultDataTypes.STRING), false, Determinism.DETERMINISTIC); //$NON-NLS-1$
     	
     	//allowed, since we're not validating the class
-    	new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method))));
+    	new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method))));
     	
     	//should fail, no class
     	try {
-    		new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+    		new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
     		fail();
     	} catch (TeiidRuntimeException e) {
     		
@@ -92,7 +92,7 @@
     	
     	//should fail, no method
     	try {
-    		new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+    		new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
     		fail();
     	} catch (TeiidRuntimeException e) {
     		
@@ -102,7 +102,7 @@
     	
     	//should fail, not void
     	try {
-    		new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+    		new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
     		fail();
     	} catch (TeiidRuntimeException e) {
     		
@@ -112,7 +112,7 @@
     	
     	//should fail, not public
     	try {
-    		new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+    		new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
     		fail();
     	} catch (TeiidRuntimeException e) {
     		
@@ -122,7 +122,7 @@
     	
     	//should fail, not static
     	try {
-    		new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+    		new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
     		fail();
     	} catch (TeiidRuntimeException e) {
     		
@@ -131,7 +131,7 @@
     	method.setInvocationMethod("y");
     	
     	//valid!
-    	new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
+    	new FunctionLibrary(RealMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new UDFSource(Arrays.asList(method)), true));
     }
     
     @Test public void testNullCategory() {


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/function/TestFunctionTree.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,7 +32,7 @@
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.util.ResolverVisitor;
 import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 import junit.framework.TestCase;
 
@@ -90,7 +90,7 @@
                                               BlockedException,
                                               TeiidComponentException, QueryResolverException {
         Expression expr = QueryParser.getQueryParser().parseExpression(sql);
-        ResolverVisitor.resolveLanguageObject(expr, FakeMetadataFactory.example1Cached());
+        ResolverVisitor.resolveLanguageObject(expr, RealMetadataFactory.example1Cached());
         return Evaluator.evaluate(expr);
     }
     


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/function/TestResolvedFunctions.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/mapping/xml/TestMappingElement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -232,7 +232,7 @@
     public void testAddNullStagingTable() {        
         MappingElement element = new MappingElement("Test"); //$NON-NLS-1$
         element.addStagingTable(null);
-        List stagingTables = element.getStagingTables();
+        List<String> stagingTables = element.getStagingTables();
         assertTrue(stagingTables.isEmpty());
     } 
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/metadata/TestTransformationMetadata.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,6 +27,7 @@
 
 import java.util.*;
 
+import org.jboss.vfs.VFS;
 import org.jboss.vfs.VirtualFile;
 import org.junit.Test;
 import org.mockito.Mockito;
@@ -39,7 +40,7 @@
 import org.teiid.metadata.MetadataFactory;
 import org.teiid.metadata.Table;
 import org.teiid.query.metadata.TransformationMetadata.Resource;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.TranslatorException;
 
 @SuppressWarnings("nls")
@@ -84,7 +85,7 @@
 		table.setResourcePath("/a/b/doc.xmi");
 		
 		HashMap<String, Resource> resources = new HashMap<String, Resource>();
-		resources.put("/x.xsd", new Resource(Mockito.mock(VirtualFile.class), true));
+		resources.put("/x.xsd", new Resource(VFS.getRootVirtualFile(), true));
 		
 		CompositeMetadataStore cms = new CompositeMetadataStore(Arrays.asList(mf.getMetadataStore(), mf1.getMetadataStore()));
 		
@@ -96,7 +97,7 @@
 		vdb.addModel(buildModel("x1"));
 		vdb.addModel(buildModel("y"));
 		
-		return new TransformationMetadata(vdb, cms, resources, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+		return new TransformationMetadata(vdb, cms, resources, RealMetadataFactory.SFM.getSystemFunctions(), null);
 	}
 	
 	ModelMetaData buildModel(String name) {
@@ -129,15 +130,15 @@
 		model2.setVisible(true);
 		vdb.addModel(model2);		
 
-		TransformationMetadata tm = new TransformationMetadata(vdb, cms, null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+		TransformationMetadata tm = new TransformationMetadata(vdb, cms, null, RealMetadataFactory.SFM.getSystemFunctions(), null);
 		Collection result = tm.getGroupsForPartialName("y"); //$NON-NLS-1$
 		assertEquals(2, result.size());
 
-		FakeMetadataFactory.buildWorkContext(tm, vdb);
+		RealMetadataFactory.buildWorkContext(tm, vdb);
 
 		model.setVisible(false);
 
-		tm = new TransformationMetadata(vdb, cms, null, FakeMetadataFactory.SFM.getSystemFunctions(), null);
+		tm = new TransformationMetadata(vdb, cms, null, RealMetadataFactory.SFM.getSystemFunctions(), null);
 		result = tm.getGroupsForPartialName("y"); //$NON-NLS-1$
 		assertEquals(1, result.size());
 	}

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,10 +23,10 @@
 package org.teiid.query.optimizer;
 
 import org.junit.Test;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.validator.TestValidator;
 
 
@@ -43,7 +43,7 @@
 
     @Test public void testVirtualAccessPatternPassing1() {
         String sql = "delete from vm1.g37 where e1 = 1"; //$NON-NLS-1$
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {});
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {});
     }
     
     @Test public void testVirtualAccessPatternFailing() {
@@ -53,7 +53,7 @@
     
     @Test public void testVirtualAccessPatternFailing1() {
         String sql = "delete from vm1.g37"; //$NON-NLS-1$
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, null, null, TestOptimizer.SHOULD_FAIL);
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, null, null, TestOptimizer.SHOULD_FAIL);
     }
 
     @Test public void testAccessPattern1() throws Exception {
@@ -103,7 +103,7 @@
      * satisfied by user criteria - the other should be made dependent
      */
     @Test public void testNodesBothHaveAccessPatterns1() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm4.g1.e1 from pm4.g1, pm4.g2 where pm4.g2.e5 = 'abc' and pm4.g1.e1 = pm4.g2.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm4.g1.e1 from pm4.g1, pm4.g2 where pm4.g2.e5 = 'abc' and pm4.g1.e1 = pm4.g2.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm4.g2 AS g_0 WHERE g_0.e5 = 'abc'"}, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         TestDependentJoins.checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
     }
@@ -114,7 +114,7 @@
      * (same query written slightly different).
      */
     @Test public void testNodesBothHaveAccessPatterns1a() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm4.g1.e1 from pm4.g2, pm4.g1 where pm4.g2.e1 = pm4.g1.e1 and pm4.g2.e5 = 'abc'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm4.g1.e1 from pm4.g2, pm4.g1 where pm4.g2.e1 = pm4.g1.e1 and pm4.g2.e5 = 'abc'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm4.g2 AS g_0 WHERE g_0.e5 = 'abc'"}, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         TestDependentJoins.checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
     }
@@ -124,7 +124,7 @@
      * criteria (therefore merge join should be used)
      */
     @Test public void testSelfJoinAccessPatterns() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm4.g1.e1 from pm4.g1, pm4.g1 as g1A where pm4.g1.e1 = 'abc' and g1A.e1 = 'abc' and pm4.g1.e2 = g1A.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm4.g1.e1 from pm4.g1, pm4.g1 as g1A where pm4.g1.e1 = 'abc' and g1A.e1 = 'abc' and pm4.g1.e2 = g1A.e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g1A.e2 FROM pm4.g1 AS g1A WHERE g1A.e1 = 'abc'", "SELECT pm4.g1.e2, pm4.g1.e1 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -146,42 +146,42 @@
     }
 
     @Test public void testAccessPatternsFails() {
-        TestOptimizer.helpPlan("select pm4.g2.e1 from pm4.g2, pm4.g2 as g2A where pm4.g2.e2 = 123 and pm4.g2.e1 = g2A.e5", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select pm4.g2.e1 from pm4.g2, pm4.g2 as g2A where pm4.g2.e2 = 123 and pm4.g2.e1 = g2A.e5", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             null, null, null,
             TestOptimizer.SHOULD_FAIL);
     }
 
     @Test public void testAccessPatternsFails2() {
-        TestOptimizer.helpPlan("select pm4.g2.e1 from pm4.g2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select pm4.g2.e1 from pm4.g2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             null, null, null,
             TestOptimizer.SHOULD_FAIL);
     }
 
     @Test public void testUnionWithAccessPatternFails() {
         TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1 UNION select pm4.g1.e1 from pm4.g1 where pm4.g1.e2 = 1", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, null, null, TestOptimizer.SHOULD_FAIL);
     }
 
     @Test public void testUnionWithAccessPatternFails2() {
         TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1 UNION select pm4.g1.e1 from pm4.g1", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, null, null, TestOptimizer.SHOULD_FAIL);
     }
     
     @Test public void testUnionWithAccessPattern() {
-        TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1 UNION ALL select pm4.g1.e1 from pm4.g1 where pm4.g1.e1 = 'abc'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1 UNION ALL select pm4.g1.e1 from pm4.g1 where pm4.g1.e1 = 'abc'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm4.g1.e1 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testUnionWithAccessPattern2() {
-        TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1 UNION ALL select pm4.g1.e1 from pm4.g1 where pm4.g1.e1 = 'abc' and pm4.g1.e2 = 1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1 UNION ALL select pm4.g1.e1 from pm4.g1 where pm4.g1.e1 = 'abc' and pm4.g1.e2 = 1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm4.g1.e1 FROM pm4.g1 WHERE (pm4.g1.e1 = 'abc') AND (pm4.g1.e2 = 1)" }); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testAccessPatternPartialMatch() throws Exception {
         TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g2 where pm1.g1.e1 = pm4.g2.e1 and pm4.g2.e2 = 123", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             new String[] { "SELECT g_0.e1 FROM pm4.g2 AS g_0 WHERE (g_0.e2 = 123) AND (g_0.e1 IN (<dependent values>))", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
@@ -192,7 +192,7 @@
      */
     @Test public void testAccessPatternFails3() {
         TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g2 where pm1.g1.e1 = pm4.g2.e1 or pm4.g2.e2 = 123",             //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, null, null,
             TestOptimizer.SHOULD_FAIL);
     }
@@ -203,7 +203,7 @@
      */
     @Test public void testAccessPatternsGroupsInSameModelFails() {
         TestOptimizer.helpPlan("select pm5.g1.e1 from pm5.g1, pm5.g2 where pm5.g1.e1 = pm5.g2.e1",              //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, null, null, TestOptimizer.SHOULD_FAIL);
     }
     
@@ -212,7 +212,7 @@
     // ==================================================================================
 
     @Test public void testPushingCriteriaThroughFrameAccessPattern0() {
-        TestOptimizer.helpPlan("select * from vm1.g9 where vm1.g9.e1='abc'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select * from vm1.g9 where vm1.g9.e1='abc'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT 1 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'", //$NON-NLS-1$
                             "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'" } ); //$NON-NLS-1$
     }
@@ -221,17 +221,17 @@
      * pm4.g2.e5 or pm4.g2.e2 also need to be in criteria
      */
     @Test public void testPushingCriteriaThroughFrameAccessPattern1() { 
-        TestOptimizer.helpPlan("select * from vm1.g1, vm1.g10 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g10.e1", FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select * from vm1.g1, vm1.g10 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g10.e1", RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), //$NON-NLS-1$
             null, TestOptimizer.SHOULD_FAIL );
     }
 
     @Test public void testPushingCriteriaThroughFrameAccessPattern2() { 
-        TestOptimizer.helpPlan("select e1 from vm1.g11 where vm1.g11.e1='abc' and vm1.g11.e2=123", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select e1 from vm1.g11 where vm1.g11.e1='abc' and vm1.g11.e2=123", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm4.g2.e1 FROM pm4.g2 WHERE (pm4.g2.e1 = 'abc') AND (pm4.g2.e2 = 123)" }); //$NON-NLS-1$
     }
 
     @Test public void testPushingCriteriaThroughFrameAccessPattern3() {
-        TestOptimizer.helpPlan("select * from vm1.g1, vm1.g9 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g9.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select * from vm1.g1, vm1.g9 where vm1.g1.e1='abc' and vm1.g1.e1=vm1.g9.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT 1 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'", //$NON-NLS-1$
                           "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", //$NON-NLS-1$
                           "SELECT g1__1.e1, g1__1.e2, g1__1.e3, g1__1.e4 FROM pm1.g1 AS g1__1 WHERE g1__1.e1 = 'abc'"} ); //$NON-NLS-1$
@@ -241,7 +241,7 @@
      * pm4.g2.e5 or pm4.g2.e2 also need to be in criteria
      */
     @Test public void testPushingCriteriaThroughFrameAccessPattern4() { 
-        TestOptimizer.helpPlan("select * from vm1.g10 where vm1.g10.e1='abc'", FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), //$NON-NLS-1$
+        TestOptimizer.helpPlan("select * from vm1.g10 where vm1.g10.e1='abc'", RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), //$NON-NLS-1$
            null, TestOptimizer.SHOULD_FAIL );
     }
     
@@ -251,7 +251,7 @@
     @Test public void testCase6425() {
         String sql = "SELECT e1 FROM pm4.g1 WHERE e1 = '1' OR e1 = '2'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, new String[] {"SELECT e1 FROM pm4.g1 WHERE (e1 = '1') OR (e1 = '2')"}); //$NON-NLS-1$
         
@@ -261,7 +261,7 @@
     @Test public void testCase6425_2() {
         String sql = "SELECT e1 FROM pm4.g1 WHERE e1 = '1' OR (e1 = '2' AND e2 = 3)"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, new String[] {"SELECT e1 FROM pm4.g1 WHERE (e1 = '1') OR ((e1 = '2') AND (e2 = 3))"}); //$NON-NLS-1$
         
@@ -271,7 +271,7 @@
     @Test public void testCase6425_4() throws Exception {
         String sql = "SELECT e1 FROM pm4.g1 WHERE e1 = '1' OR e2 = '2'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         TestOptimizer.helpPlan(sql, metadata, null, TestOptimizer.ComparisonMode.FAILED_PLANNING);
     }
@@ -282,7 +282,7 @@
     @Test public void testMultiAccessPatternWithCriteria() throws Exception {
     	String sql = "SELECT pm1.g1.* FROM pm4.g1, pm5.g1, pm1.g1 where pm4.g1.e1 = pm1.g1.e1 and pm5.g1.e1 = pm1.g1.e1 and pm5.g1.e2 like '%x' "; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         TestOptimizer.helpPlan(sql, metadata,
 						new String[] {


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestAccessPatterns.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,8 +33,7 @@
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.SourceSystemFunctions;
 
 @SuppressWarnings("nls")
@@ -69,8 +68,8 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
         String sql = "SELECT a12.intkey AS REGION_NBR, SUM(a11.intnum) AS WJXBFS1 FROM bqt1.smalla AS a11 INNER JOIN bqt2.smalla AS a12 ON a11.stringkey = a12.stringkey WHERE a11.stringkey = 0 GROUP BY a12.intkey"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
-                                      new String[] {"SELECT SUM(a11.intnum) FROM bqt1.smalla AS a11 WHERE a11.stringkey = '0' HAVING COUNT(*) > 0", "SELECT a12.intkey FROM bqt2.smalla AS a12 WHERE a12.stringkey = '0' group by a12.intkey"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
+                                      new String[] {"SELECT SUM(a11.intnum) FROM bqt1.smalla AS a11 WHERE a11.stringkey = '0' HAVING COUNT(*) > 0", "SELECT a12.intkey FROM bqt2.smalla AS a12 WHERE a12.stringkey = '0'"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -105,7 +104,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
         String sql = "SELECT a12.intkey, MAX(a12.stringkey), MIN(a11.intnum+a12.intnum) FROM bqt1.smalla AS a11 INNER JOIN bqt2.smalla AS a12 ON a11.stringkey = a12.stringkey GROUP BY a12.intkey"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                       new String[] {"SELECT g_0.stringkey, g_0.intkey, g_0.intnum FROM bqt2.smalla AS g_0 GROUP BY g_0.stringkey, g_0.intkey, g_0.intnum", "SELECT g_0.stringkey, g_0.intnum FROM bqt1.smalla AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -136,7 +135,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
         String sql = "SELECT a12.intkey, MAX(a12.stringkey), SUM(a11.intnum+a12.intnum) FROM bqt1.smalla AS a11 INNER JOIN bqt2.smalla AS a12 ON a11.stringkey = a12.stringkey GROUP BY a12.intkey"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                       new String[] {"SELECT g_0.stringkey, g_0.intkey, g_0.intnum FROM bqt2.smalla AS g_0", "SELECT g_0.stringkey, g_0.intnum FROM bqt1.smalla AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -169,7 +168,7 @@
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
         String sql = "SELECT max(y.e2) from pm1.g1 x, pm2.g1 y where x.e3 = y.e3 group by y.e3"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT g_0.e3 FROM pm1.g1 AS g_0", "SELECT g_0.e3, MAX(g_0.e2) FROM pm2.g1 AS g_0 GROUP BY g_0.e3"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -203,8 +202,8 @@
         
         String sql = "select sum(a11.intnum) Profit, (sum(a11.intnum) / sum(a11.floatnum)) WJXBFS2 from bqt1.smalla a11 join bqt2.smallb a12 on a11.intkey=a12.intkey group by a12.intkey"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
-                                      new String[] {"SELECT g_0.intkey, SUM(g_0.intnum), SUM(g_0.floatnum) FROM bqt1.smalla AS g_0 GROUP BY g_0.intkey", "SELECT g_0.intkey FROM bqt2.smallb AS g_0 GROUP BY g_0.intkey"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
+                                      new String[] {"SELECT g_0.intkey, SUM(g_0.intnum), SUM(g_0.floatnum) FROM bqt1.smalla AS g_0 GROUP BY g_0.intkey", "SELECT g_0.intkey FROM bqt2.smallb AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -228,7 +227,7 @@
      * Note that until we can test the other side cardinality, we cannot fully push the group node
      */ 
     @Test public void testAggregatePushdown1() throws Exception {        
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleAggregatesCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleAggregatesCached();
         String sql = "SELECT o_dealerid, o_productid, sum(o_amount) FROM m1.order, m1.dealer, m2.product " +  //$NON-NLS-1$
             "WHERE o_dealerid=d_dealerid AND o_productid=p_productid AND d_state = 'CA' AND p_divid = 100 " +  //$NON-NLS-1$
             "GROUP BY o_dealerid, o_productid"; //$NON-NLS-1$
@@ -236,7 +235,7 @@
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
                                       metadata,
                                       null, getAggregatesFinder(),
-                                      new String[] {"SELECT g_0.p_productid AS c_0 FROM m2.product AS g_0 WHERE g_0.p_divid = 100 ORDER BY c_0", "SELECT g_0.o_productid AS c_0, g_0.o_dealerid AS c_1, SUM(g_0.o_amount) AS c_2 FROM m1.\"order\" AS g_0, m1.dealer AS g_1 WHERE (g_0.o_dealerid = g_1.d_dealerid) AND (g_1.d_state = 'CA') AND (g_0.o_productid IN (<dependent values>)) GROUP BY g_0.o_productid, g_0.o_dealerid ORDER BY c_0"},  //$NON-NLS-1$ //$NON-NLS-2$
+                                      new String[] {"SELECT g_0.p_productid AS c_0 FROM m2.product AS g_0 WHERE g_0.p_divid = 100 ORDER BY c_0", "SELECT g_0.o_productid, g_0.o_dealerid, SUM(g_0.o_amount) FROM m1.\"order\" AS g_0, m1.dealer AS g_1 WHERE (g_0.o_dealerid = g_1.d_dealerid) AND (g_1.d_state = 'CA') AND (g_0.o_productid IN (<dependent values>)) GROUP BY g_0.o_productid, g_0.o_dealerid"},  //$NON-NLS-1$ //$NON-NLS-2$
                                                     TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -258,7 +257,7 @@
     }
 
     @Test public void testAggregatePushdown2() throws Exception {        
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleAggregatesCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleAggregatesCached();
         String sql = "SELECT o_dealerid, o_productid, sum(o_amount) FROM m1.order, m1.dealer, m2.product " +  //$NON-NLS-1$
             "WHERE o_dealerid=d_dealerid AND o_productid=p_productid AND d_state = 'CA' AND p_divid = 100 " +  //$NON-NLS-1$
             "GROUP BY o_dealerid, o_productid having max(o_amount) < 100"; //$NON-NLS-1$
@@ -266,7 +265,7 @@
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
                                       metadata,
                                       null, getAggregatesFinder(),
-                                      new String[] {"SELECT g_0.p_productid AS c_0 FROM m2.product AS g_0 WHERE g_0.p_divid = 100 ORDER BY c_0", "SELECT g_0.o_productid AS c_0, g_0.o_dealerid AS c_1, MAX(g_0.o_amount) AS c_2, SUM(g_0.o_amount) AS c_3 FROM m1.\"order\" AS g_0, m1.dealer AS g_1 WHERE (g_0.o_dealerid = g_1.d_dealerid) AND (g_1.d_state = 'CA') AND (g_0.o_productid IN (<dependent values>)) GROUP BY g_0.o_productid, g_0.o_dealerid ORDER BY c_0"},  //$NON-NLS-1$ //$NON-NLS-2$
+                                      new String[] {"SELECT g_0.p_productid AS c_0 FROM m2.product AS g_0 WHERE g_0.p_divid = 100 ORDER BY c_0", "SELECT g_0.o_productid, g_0.o_dealerid, MAX(g_0.o_amount), SUM(g_0.o_amount) FROM m1.\"order\" AS g_0, m1.dealer AS g_1 WHERE (g_0.o_dealerid = g_1.d_dealerid) AND (g_1.d_state = 'CA') AND (g_0.o_productid IN (<dependent values>)) GROUP BY g_0.o_productid, g_0.o_dealerid"},  //$NON-NLS-1$ //$NON-NLS-2$
                                                     TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -298,8 +297,8 @@
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
         String sql = "SELECT avg(y.e2) from pm1.g1 x, pm2.g1 y where x.e3 = y.e3 group by x.e2, y.e1"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
-                                      new String[] {"SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0 GROUP BY g_0.e3, g_0.e2", "SELECT g_0.e3, g_0.e1, SUM(g_0.e2), COUNT(g_0.e2) FROM pm2.g1 AS g_0 GROUP BY g_0.e3, g_0.e1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
+                                      new String[] {"SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0", "SELECT g_0.e3, g_0.e1, SUM(g_0.e2), COUNT(g_0.e2) FROM pm2.g1 AS g_0 GROUP BY g_0.e3, g_0.e1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -318,7 +317,71 @@
             0       // UnionAll
         }); 
     }
+
+    @Test public void testAvgAggregateFiltered() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = getAggregateCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+        
+        String sql = "SELECT avg(y.e2) filter (where y.e1 = 1) from pm1.g1 x, pm2.g1 y where x.e3 = y.e3 group by x.e2, y.e1"; //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
+                                      new String[] {"SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0", 
+        	"SELECT g_0.e3, g_0.e1, g_0.e2 FROM pm2.g1 AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            2,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+    }
     
+    /**
+     * Agg can only be computed after the join
+     */
+    @Test public void testAvgAggregateFiltered1() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = getAggregateCapabilities();
+        caps.setCapabilitySupport(Capability.ADVANCED_OLAP, true);
+        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
+        
+        String sql = "SELECT avg(y.e2) filter (where x.e1 = 1) from pm1.g1 x, pm2.g1 y where x.e3 = y.e3 group by x.e2, y.e1"; //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
+        		new String[] {"SELECT g_0.e3, g_0.e2, g_0.e1 FROM pm1.g1 AS g_0", 
+    	"SELECT g_0.e3, g_0.e1, g_0.e2 FROM pm2.g1 AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            1,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            1,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            0       // UnionAll
+        }); 
+    }
+    
     @Test public void testStddevAggregate() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = getAggregateCapabilities();
@@ -328,8 +391,8 @@
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
         String sql = "SELECT stddev_pop(y.e2) from pm1.g1 x, pm2.g1 y where x.e3 = y.e3 group by x.e2, y.e1"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
-                                      new String[] {"SELECT g_0.e3 AS c_0, g_0.e1 AS c_1, COUNT(g_0.e2) AS c_2, SUM(power(g_0.e2, 2)) AS c_3, SUM(g_0.e2) AS c_4 FROM pm2.g1 AS g_0 GROUP BY g_0.e3, g_0.e1 ORDER BY c_0", "SELECT g_0.e3 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 GROUP BY g_0.e3, g_0.e2 ORDER BY c_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
+                                      new String[] {"SELECT g_0.e3 AS c_0, g_0.e1 AS c_1, COUNT(g_0.e2) AS c_2, SUM(power(g_0.e2, 2)) AS c_3, SUM(g_0.e2) AS c_4 FROM pm2.g1 AS g_0 GROUP BY g_0.e3, g_0.e1 ORDER BY c_0", "SELECT g_0.e3 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -357,8 +420,8 @@
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
         String sql = "SELECT count(y.e2) from pm1.g1 x, pm2.g1 y where x.e3 = y.e3 group by x.e2, y.e1"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
-                                      new String[] {"SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0 GROUP BY g_0.e3, g_0.e2", "SELECT g_0.e3, g_0.e1, COUNT(g_0.e2) FROM pm2.g1 AS g_0 GROUP BY g_0.e3, g_0.e1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
+                                      new String[] {"SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0", "SELECT g_0.e3, g_0.e1, COUNT(g_0.e2) FROM pm2.g1 AS g_0 GROUP BY g_0.e3, g_0.e1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -386,7 +449,7 @@
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
         String sql = "SELECT count(y.e2) from pm1.g1 x left outer join pm2.g1 y on x.e3 = y.e3 group by x.e2, y.e1"; //$NON-NLS-1$
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0", "SELECT g_0.e3, g_0.e1, g_0.e2 FROM pm2.g1 AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -416,7 +479,7 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(
               "select count(*), a.intnum from bqt1.smalla as a, bqt2.smallb as b where a.intkey = b.intkey group by a.intnum",  //$NON-NLS-1$
@@ -456,7 +519,7 @@
         
         String sql = "select a11.intkey ITEM_ID, sum(a11.intnum) WJXBFS1 from bqt1.smalla a11 join bqt2.smalla a12 on (a11.stringkey = a12.stringkey) join bqt2.smallb a13 on (a11.intkey = a13.intkey) where a13.intnum in (10) group by a11.intkey"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                       new String[] {"SELECT g_0.stringkey FROM bqt2.smalla AS g_0", "SELECT g_0.stringkey, g_0.intkey, SUM(g_0.intnum) FROM bqt1.smalla AS g_0 GROUP BY g_0.stringkey, g_0.intkey", "SELECT g_0.intkey FROM bqt2.smallb AS g_0 WHERE g_0.intnum = 10"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -485,7 +548,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(
               "select count(*) from bqt1.smalla",  //$NON-NLS-1$
@@ -504,7 +567,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(
               "select stringkey, max(intkey) from bqt1.smalla group by stringkey having count(intkey) = 1",  //$NON-NLS-1$
@@ -537,7 +600,7 @@
         caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("select X.e1 FROM vm1.g1 X group by X.e1 having X.e1 = 1 and sum(X.e2) = 2", FakeMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select X.e1 FROM vm1.g1 X group by X.e1 having X.e1 = 1 and sum(X.e2) = 2", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
             new String[]{"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 WHERE pm1.g1.e1 = '1'"}, true); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -571,7 +634,7 @@
         capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
         capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleBusObj();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBusObj();
 
         String sql = "SELECT Q1.S, Q2.C, Q1.PRODUCT, Q1.REGION AS Q1R, Q2.REGION AS Q2R FROM " + //$NON-NLS-1$
             "(SELECT SUM(SALES) AS S, REGION, PRODUCT FROM DB2_TABLE WHERE PRODUCT IN ('GUNS', 'TOYS', 'VIDEOTAPES') GROUP BY REGION, PRODUCT) Q1 " + //$NON-NLS-1$
@@ -618,7 +681,7 @@
         capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
         capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleBusObj();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBusObj();
 
         String sql = "SELECT SUM(F.SALES), G.REGION, T.YEAR " +  //$NON-NLS-1$
             "FROM SALES F, GEOGRAPHY G, msModel.TIME T " + //$NON-NLS-1$
@@ -666,7 +729,7 @@
         capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
         capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleBusObj();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBusObj();
 
         String sql = "SELECT SUM(F.SALES), G.REGION, T.YEAR " +  //$NON-NLS-1$
             "FROM SALES F MAKEDEP, GEOGRAPHY G, msModel.TIME T " + //$NON-NLS-1$
@@ -714,7 +777,7 @@
         capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
         capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleBusObj();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBusObj();
 
         String sql = "SELECT SUM(F.SALES), G.REGION, T.YEAR " +  //$NON-NLS-1$
             "FROM SALES F MAKEDEP, GEOGRAPHY2 G, msModel.TIME T " + //$NON-NLS-1$
@@ -761,15 +824,15 @@
         capFinder.addCapabilities("oraclemodel", caps); //$NON-NLS-1$
         capFinder.addCapabilities("msmodel", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleBusObj();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBusObj();
 
         String sql = "select sum(c0), sum(b0), c1, b2 FROM db2Table, OraTable where c2=b2 group by c1, b2"; //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
                                       metadata,
                                       null, capFinder,
-                                      new String[] {"SELECT c2, c1, c0 FROM db2model.DB2TABLE", //$NON-NLS-1$
-                                                    "SELECT DISTINCT b2, sum(b0) FROM oraclemodel.OraTable GROUP BY b2 ORDER BY b2"},  //$NON-NLS-1$
+                                      new String[] {"SELECT g_0.c2, g_0.c1, g_0.c0 FROM db2model.DB2TABLE AS g_0", //$NON-NLS-1$
+                                                    "SELECT g_0.b2 AS c_0, g_0.b0 AS c_1 FROM oraclemodel.OraTable AS g_0 ORDER BY c_0"},  //$NON-NLS-1$
                                       SHOULD_SUCCEED );
 
         checkNodeTypes(plan, new int[] {
@@ -778,12 +841,12 @@
                                         0,      // DependentSelect
                                         0,      // DependentProject
                                         0,      // DupRemove
-                                        1,      // Grouping
+                                        2,      // Grouping
                                         0,      // NestedLoopJoinStrategy
                                         1,      // MergeJoinStrategy
                                         0,      // Null
                                         0,      // PlanExecution
-                                        2,      // Project
+                                        1,      // Project
                                         0,      // Select
                                         0,      // Sort
                                         0       // UnionAll
@@ -795,7 +858,7 @@
         BasicSourceCapabilities caps = getAggregateCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("select e1, max(e2) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm1.g2) y group by e1", FakeMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select e1, max(e2) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm1.g2) y group by e1", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
             new String[]{"SELECT v_0.c_0, MAX(v_0.c_1) FROM (SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0) AS v_0 GROUP BY v_0.c_0", //$NON-NLS-1$
         	"SELECT v_0.c_0, MAX(v_0.c_1) FROM (SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g2 AS g_0) AS v_0 GROUP BY v_0.c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -816,12 +879,96 @@
         }); 
     }
     
+    /**
+     * olap not supported
+     */
+    @Test public void testPushDownOverUnionFiltered() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = getAggregateCapabilities();
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select e1, count(*) filter (where e3) from (select e1, e2, e3 from pm1.g1 union all select e1, e2, e3 from pm1.g2) y group by e1", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+            new String[]{"SELECT g_0.e1, g_0.e3 FROM pm1.g1 AS g_0", "SELECT g_0.e1, g_0.e3 FROM pm1.g2 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            1,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            0,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            1       // UnionAll
+        }); 
+    }
+    
+    @Test public void testPushDownOverUnionFiltered1() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = getAggregateCapabilities();
+        caps.setCapabilitySupport(Capability.ADVANCED_OLAP, true);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select e1, count(*) filter (where e3) from (select e1, e2, e3 from pm1.g1 union all select e1, e2, e3 from pm1.g2) y group by e1", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+            new String[]{"SELECT v_0.c_0, COUNT(*) FILTER(WHERE v_0.c_1) FROM (SELECT g_0.e1 AS c_0, g_0.e3 AS c_1 FROM pm1.g1 AS g_0) AS v_0 GROUP BY v_0.c_0",
+        	"SELECT v_0.c_0, COUNT(*) FILTER(WHERE v_0.c_1) FROM (SELECT g_0.e1 AS c_0, g_0.e3 AS c_1 FROM pm1.g2 AS g_0) AS v_0 GROUP BY v_0.c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            1,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            0,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            1       // UnionAll
+        }); 
+    }
+    
+    /**
+     * rand pushdown not supported
+     */
+    @Test public void testPushDownOverUnionFiltered3() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = getAggregateCapabilities();
+        caps.setCapabilitySupport(Capability.ADVANCED_OLAP, true);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select e1, count(*) filter (where e3 > rand()) from (select e1, e2, e3 from pm1.g1 union all select e1, e2, e3 from pm1.g2) y group by e1", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+        		new String[]{"SELECT g_0.e1, g_0.e3 FROM pm1.g1 AS g_0", "SELECT g_0.e1, g_0.e3 FROM pm1.g2 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            1,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            0,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            1       // UnionAll
+        }); 
+    }
+    
     @Test public void testPushDownOverUnion1() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = getAggregateCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e2) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm1.g2) z", FakeMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e2) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm1.g2) z", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
             new String[]{"SELECT MAX(v_0.c_0) FROM (SELECT g_0.e2 AS c_0 FROM pm1.g2 AS g_0) AS v_0 HAVING COUNT(*) > 0", //$NON-NLS-1$
         	"SELECT MAX(v_0.c_0) FROM (SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0) AS v_0 HAVING COUNT(*) > 0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -850,7 +997,7 @@
         BasicSourceCapabilities caps = getAggregateCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("select count(e2) from (select e1, e2 from pm1.g1 union select e1, e2 from pm1.g2) z", FakeMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select count(e2) from (select e1, e2 from pm1.g1 union select e1, e2 from pm1.g2) z", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
             new String[]{"SELECT g_0.e1, g_0.e2 FROM pm1.g2 AS g_0", //$NON-NLS-1$
         	"SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -877,7 +1024,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e2), count(*) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm2.g2) z", FakeMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e2), count(*) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm2.g2) z", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
             new String[]{"SELECT MAX(v_0.c_0), COUNT(*) FROM (SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0) AS v_0 HAVING COUNT(*) > 0", //$NON-NLS-1$
         	"SELECT g_0.e2 FROM pm2.g2 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -899,6 +1046,64 @@
     }
     
     /**
+     * pushdown won't happen since searched case is not supported
+     */
+    @Test public void testPushDownOverUnionGroupingExpression() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = getAggregateCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm2", getAggregateCapabilities()); //$NON-NLS-1$
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e2), case when e1 is null then 0 else 1 end from (select e1, e2 from pm1.g1 union all select e1, e2 from pm2.g2) z group by case when e1 is null then 0 else 1 end", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+            new String[]{"SELECT v_1.c_1, MAX(v_1.c_0) FROM (SELECT v_0.c_1 AS c_0, CASE WHEN v_0.c_0 IS NULL THEN 0 ELSE 1 END AS c_1 FROM (SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0) AS v_0) AS v_1 GROUP BY v_1.c_1", //$NON-NLS-1$
+        	"SELECT g_0.e1, g_0.e2 FROM pm2.g2 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            1,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            0,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            2,      // Project
+            0,      // Select
+            0,      // Sort
+            1       // UnionAll
+        }); 
+    }
+    
+    @Test public void testPushDownOverUnionGroupingExpressionPartitioned() throws Exception {
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = getAggregateCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        
+        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e2), case when e1 is null then 0 else 1 end from (select e1, e2, 1 as part from pm1.g1 union all select e1, e2, 2 as part from pm1.g2) z group by case when e1 is null then 0 else 1 end, part", RealMetadataFactory.example1Cached(), null, capFinder,  //$NON-NLS-1$
+            new String[]{"SELECT MAX(v_1.c_0), v_1.c_1 FROM (SELECT v_0.c_2 AS c_0, CASE WHEN v_0.c_0 IS NULL THEN 0 ELSE 1 END AS c_1, v_0.c_1 AS c_2 FROM (SELECT g_0.e1 AS c_0, 1 AS c_1, g_0.e2 AS c_2 FROM pm1.g1 AS g_0) AS v_0) AS v_1 GROUP BY v_1.c_1, v_1.c_2", 
+        "SELECT MAX(v_1.c_0), v_1.c_1 FROM (SELECT v_0.c_2 AS c_0, CASE WHEN v_0.c_0 IS NULL THEN 0 ELSE 1 END AS c_1, v_0.c_1 AS c_2 FROM (SELECT g_0.e1 AS c_0, 2 AS c_1, g_0.e2 AS c_2 FROM pm1.g2 AS g_0) AS v_0) AS v_1 GROUP BY v_1.c_1, v_1.c_2"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // NestedLoopJoinStrategy
+            0,      // MergeJoinStrategy
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            1       // UnionAll
+        }); 
+    }
+    
+    /**
      * Ensures that we do not raise criteria over a group by
      * TODO: check if the criteria only depends on grouping columns
      */
@@ -907,7 +1112,7 @@
         
         // Plan query
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
-                FakeMetadataFactory.exampleBQTCached(),
+                RealMetadataFactory.exampleBQTCached(),
                 null, getAggregatesFinder(),
                 new String[] {"SELECT g_0.DateValue FROM bqt1.smallb AS g_0"},  
                               TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING );


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java:3149-3217,3220-3275
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestAggregatePushdown.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,7 +28,7 @@
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TestAnsiJoinPushdown {
@@ -46,7 +46,7 @@
     	
         ProcessorPlan plan = TestOptimizer.helpPlan(
         		"select pm2.g1.e1 from pm2.g1, pm2.g2 where pm2.g1.e1 = pm2.g2.e1 and (pm2.g1.e2 = 1 OR pm2.g2.e2 = 2) and pm2.g2.e3 = 1", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), 
+        		RealMetadataFactory.example1Cached(), 
         		null,
         		capFinder,
         		new String[] { "SELECT g_0.e1 FROM pm2.g1 AS g_0 INNER JOIN pm2.g2 AS g_1 ON g_0.e1 = g_1.e1 AND ((g_0.e2 = 1) OR (g_1.e2 = 2)) WHERE g_1.e3 = TRUE" }, //$NON-NLS-1$


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestAnsiJoinPushdown.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -49,7 +49,7 @@
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.BatchedUpdateCommand;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.validator.Validator;
 import org.teiid.query.validator.ValidatorReport;
 
@@ -156,7 +156,7 @@
     }
     
     private void helpTestPlanner(String[] sql, boolean[] expectedBatching) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-        BatchedUpdatePlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached());
+        BatchedUpdatePlan plan = helpPlan(sql, RealMetadataFactory.example1Cached());
         List plans = plan.getUpdatePlans();
         assertEquals("Number of child plans did not match expected", expectedBatching.length, plans.size()); //$NON-NLS-1$
         for (int i = 0; i < expectedBatching.length; i++) {
@@ -165,7 +165,7 @@
     }    
     
     private void helpTestPlanner(String[] sql, boolean[] expectedBatching, CapabilitiesFinder capFinder) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-        BatchedUpdatePlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), capFinder, true);
+        BatchedUpdatePlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), capFinder, true);
         List plans = plan.getUpdatePlans();
         assertEquals("Number of child plans did not match expected", expectedBatching.length, plans.size()); //$NON-NLS-1$
         for (int i = 0; i < expectedBatching.length; i++) {


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestBatchedUpdatePlanner.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -45,9 +45,7 @@
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestDependentJoins {
@@ -122,7 +120,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm2.g1 where pm1.g1.e1 = pm2.g1.e1 option makedep pm2.g1", FakeMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm2.g1 where pm1.g1.e1 = pm2.g1.e1 option makedep pm2.g1", RealMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
 
         checkDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$
@@ -152,7 +150,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1, pm2.g1.e1 from pm1.g1 MAKEDEP INNER JOIN pm2.g1 MAKENOTDEP ON pm1.g1.e1 = pm2.g1.e1", FakeMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1, pm2.g1.e1 from pm1.g1 MAKEDEP INNER JOIN pm2.g1 MAKENOTDEP ON pm1.g1.e1 = pm2.g1.e1", RealMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$
                 new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm2.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
 
         checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$
@@ -339,7 +337,7 @@
      * Test that access node with unsatisfied access pattern is made dependent
      */
     @Test public void testMakeDependentAccessPattern1() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm1.g1.e1 = pm4.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm1.g1.e1 = pm4.g1.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
     }
@@ -349,7 +347,7 @@
      * (Same query written slightly different way)
      */
     @Test public void testMakeDependentAccessPattern1a() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e1 = pm1.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e1 = pm1.g1.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
     }
@@ -358,7 +356,7 @@
      * Test that access node with unsatisfied access pattern is made dependent
      */
     @Test public void testMakeDependentAccessPattern2() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e2 = 1 and pm1.g1.e1 = pm4.g1.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e2 = 1 and pm1.g1.e1 = pm4.g1.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE (g_0.e2 = 1) AND (g_0.e1 IN (<dependent values>))", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$
     }
@@ -368,7 +366,7 @@
      * dependent with
      */
     @Test public void testMakeDependentAccessPattern3() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g2 where pm1.g1.e1 = pm4.g2.e5", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g2 where pm1.g1.e1 = pm4.g2.e5", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e5 FROM pm4.g2 AS g_0 WHERE g_0.e5 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         checkDependentGroups(plan, new String[] {"pm4.g2"}); //$NON-NLS-1$
     }
@@ -379,7 +377,7 @@
      * needs to be fulfilled and there is no cost info available for either source
      */
     @Test public void testPushSelectAndMakeDependentAccessPattern1() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         checkDependentGroups(plan, new String[0]); 
 
@@ -408,7 +406,7 @@
      * (Same query written slightly different)
      */
     @Test public void testPushSelectAndMakeDependentAccessPattern1a() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e2 = pm1.g1.e2 and pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e2 = pm1.g1.e2 and pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         checkDependentGroups(plan, new String[0]); 
     
@@ -435,7 +433,7 @@
      * because of it's (already-satisfied) access pattern - merge join is used
      */
     @Test public void testPushSelectAndMakeDependentAccessPattern2() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         checkDependentGroups(plan, new String[0] ); 
 
@@ -471,10 +469,9 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(10));
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject obj = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        obj.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-    
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata);
+            
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
             null, capFinder,
             new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
@@ -507,9 +504,8 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject obj = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        obj.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata);
     
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
             null, capFinder,
@@ -546,13 +542,10 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1 ));
-        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata);
+        RealMetadataFactory.setCardinality("pm1.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
             null, capFinder,
@@ -587,13 +580,10 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
+        RealMetadataFactory.setCardinality("pm1.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
             null, capFinder,
@@ -636,14 +626,11 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-    
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
+        RealMetadataFactory.setCardinality("pm1.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
+        
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
             null, capFinder,
             new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g3 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
@@ -679,11 +666,9 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,  
             null, capFinder,
@@ -720,9 +705,9 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQT();
+        RealMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
+        RealMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan(
             "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey",  //$NON-NLS-1$
@@ -764,9 +749,9 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
 
-        TransformationMetadata metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.exampleBQT();
+        RealMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
+        RealMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan(
             "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey AND table1comp.key1 = BQT1.SmallA.StringNum",  //$NON-NLS-1$
@@ -805,12 +790,12 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
 
-        TransformationMetadata metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.smalla", 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt2.smalla", 10000, metadata); //$NON-NLS-1$
-        Column fmo = (Column)metadata.getElementID("bqt1.smalla.intnum");
+        TransformationMetadata metadata = RealMetadataFactory.exampleBQT();
+        RealMetadataFactory.setCardinality("bqt1.smalla", 1000, metadata); //$NON-NLS-1$
+        RealMetadataFactory.setCardinality("bqt2.smalla", 10000, metadata); //$NON-NLS-1$
+        Column fmo = metadata.getElementID("bqt1.smalla.intnum");
 		fmo.setDistinctValues(1000);
-        Column floatnum = (Column)metadata.getElementID("bqt1.smalla.floatnum");
+        Column floatnum = metadata.getElementID("bqt1.smalla.floatnum");
         floatnum.setDistinctValues(800);
 
         ProcessorPlan plan = TestOptimizer.helpPlan(


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java:3149-3217,3220-3275
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,14 +28,11 @@
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 /**
- * expressions in group use lacks robust support in MySQL, PostGres, and Derby Expressions and it's nothing more than syntactic sugar for an inline view,
- * a new approach was taken to use inline views rather than a non ANSI group by construct.
- * 
- * Later we can add a connector binding property to support non-select expressions in group by.
+ * expressions in group use lacks robust support in MySQL, PostGres, and Derby, so a compensation step must be taken to create an inline view
  */
 public class TestExpressionsInGroupBy {
 
@@ -55,9 +52,9 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
             null, capFinder,
-            new String[] { "SELECT convert(TimestampValue, date), COUNT(*) FROM bqt1.smalla GROUP BY convert(TimestampValue, date)" },  //$NON-NLS-1$
+            new String[] { "SELECT v_0.c_0, COUNT(*) FROM (SELECT convert(g_0.TimestampValue, date) AS c_0 FROM bqt1.smalla AS g_0) AS v_0 GROUP BY v_0.c_0" },  //$NON-NLS-1$
             true);
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);         
     }   
@@ -79,9 +76,9 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
             null, capFinder,
-            new String[] { "SELECT convert(TimestampValue, date), COUNT(*) FROM bqt1.smalla GROUP BY convert(TimestampValue, date)" },  //$NON-NLS-1$
+            new String[] { "SELECT v_0.c_0, COUNT(*) FROM (SELECT convert(g_0.TimestampValue, date) AS c_0 FROM bqt1.smalla AS g_0) AS v_0 GROUP BY v_0.c_0" },  //$NON-NLS-1$
             true);
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);         
     }   
@@ -90,7 +87,7 @@
     @Test public void testCase1565_3() throws Exception {
         String sql = "SELECT x, COUNT(*) FROM (SELECT convert(TimestampValue, date) AS x FROM (SELECT TimestampValue from bqt1.smalla) as z) as y GROUP BY x"; //$NON-NLS-1$
 
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
             null, TestOptimizer.getGenericFinder(),
             new String[] { "SELECT TimestampValue FROM bqt1.smalla" },  //$NON-NLS-1$
             true);
@@ -105,7 +102,7 @@
             0,      // MergeJoinStrategy
             0,      // Null
             0,      // PlanExecution
-            2,      // Project
+            1,      // Project
             0,      // Select
             0,      // Sort
             0       // UnionAll
@@ -128,7 +125,7 @@
         caps.setFunctionSupport("convert", true); //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
             null, capFinder,
             new String[] { "SELECT TimestampValue, stringkey FROM bqt1.smalla" },  //$NON-NLS-1$
             true);
@@ -143,7 +140,7 @@
             0,      // MergeJoinStrategy
             0,      // Null
             0,      // PlanExecution
-            2,      // Project
+            1,      // Project
             0,      // Select
             0,      // Sort
             0       // UnionAll
@@ -166,7 +163,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
             null, capFinder,
             new String[] { "SELECT intkey FROM bqt1.smalla" },  //$NON-NLS-1$
             true);
@@ -181,7 +178,7 @@
             0,      // MergeJoinStrategy
             0,      // Null
             0,      // PlanExecution
-            2,      // Project
+            1,      // Project
             0,      // Select
             0,      // Sort
             0       // UnionAll
@@ -191,7 +188,7 @@
     
     // SELECT SUM(x) FROM (SELECT IntKey+1 AS x FROM BQT1.SmallA) AS g
     @Test public void testAggregateNoGroupByWithNestedFunction() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT SUM(x) FROM (SELECT IntKey+1 AS x FROM BQT1.SmallA) AS g", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT SUM(x) FROM (SELECT IntKey+1 AS x FROM BQT1.SmallA) AS g", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
             new String[] { "SELECT IntKey FROM BQT1.SmallA"  }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -213,7 +210,7 @@
     }     
     
     /**
-     * Without inline view support the agg is not pushed down
+     * Without inline view support or functions in group by the agg is not pushed down
      */
     @Test public void testFunctionInGroupBy() {
         String sql = "SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
@@ -226,14 +223,15 @@
         caps.setCapabilitySupport(Capability.QUERY_CASE, true);
         caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+        caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
-                                      new String[] {"SELECT CASE WHEN BQT1.SmallA.IntKey >= 5000 THEN '5000 +' ELSE '0-999' END, BQT1.SmallA.IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
+                                      new String[] {"SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
                                       TestOptimizer.SHOULD_SUCCEED );
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -254,6 +252,60 @@
         });        
     }
     
+    @Test public void testFunctionInGroupBy1() {
+        String sql = "SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
+            "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end"; //$NON-NLS-1$
+
+        // Plan query
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+        caps.setCapabilitySupport(Capability.QUERY_CASE, true);
+        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+        caps.setCapabilitySupport(Capability.QUERY_FUNCTIONS_IN_GROUP_BY, true);
+        caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
+                                      RealMetadataFactory.exampleBQTCached(),
+                                      null, capFinder,
+                                      new String[] {"SELECT SUM(BQT1.SmallA.IntKey), CASE WHEN BQT1.SmallA.IntKey >= 5000 THEN '5000 +' ELSE '0-999' END FROM BQT1.SmallA GROUP BY CASE WHEN BQT1.SmallA.IntKey >= 5000 THEN '5000 +' ELSE '0-999' END"}, //$NON-NLS-1$ 
+                                      TestOptimizer.SHOULD_SUCCEED );
+
+        TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);        
+    }
+    
+    @Test public void testFunctionInGroupBy2() {
+        String sql = "SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
+            "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end"; //$NON-NLS-1$
+
+        // Plan query
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
+        caps.setCapabilitySupport(Capability.QUERY_CASE, true);
+        caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
+        caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+        caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
+        caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
+        capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
+
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
+                                      RealMetadataFactory.exampleBQTCached(),
+                                      null, capFinder,
+                                      new String[] {"SELECT SUM(v_0.c_1), v_0.c_0 FROM (SELECT CASE WHEN g_0.IntKey >= 5000 THEN '5000 +' ELSE '0-999' END AS c_0, g_0.IntKey AS c_1 FROM BQT1.SmallA AS g_0) AS v_0 GROUP BY v_0.c_0"}, //$NON-NLS-1$ 
+                                      TestOptimizer.SHOULD_SUCCEED );
+
+        TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);        
+    }
+
+    
     /**
      * Test what happens when we have a CASE in the GROUP BY and source has aggregate capability but 
      * does not have CASE capability.  Should not be able to push down GROUP BY.  
@@ -275,7 +327,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
                                       TestOptimizer.SHOULD_SUCCEED );
@@ -291,7 +343,7 @@
                                         0,      // MergeJoinStrategy
                                         0,      // Null
                                         0,      // PlanExecution
-                                        2,      // Project
+                                        1,      // Project
                                         0,      // Select
                                         0,      // Sort
                                         0       // UnionAll
@@ -320,7 +372,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
                                       TestOptimizer.SHOULD_SUCCEED );
@@ -336,7 +388,7 @@
                                         0,      // MergeJoinStrategy
                                         0,      // Null
                                         0,      // PlanExecution
-                                        2,      // Project
+                                        1,      // Project
                                         1,      // Select
                                         0,      // Sort
                                         0       // UnionAll
@@ -362,7 +414,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
                                       TestOptimizer.SHOULD_SUCCEED );
@@ -378,7 +430,7 @@
                                         0,      // MergeJoinStrategy
                                         0,      // Null
                                         0,      // PlanExecution
-                                        2,      // Project
+                                        1,      // Project
                                         0,      // Select
                                         0,      // Sort
                                         0       // UnionAll
@@ -394,7 +446,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT StringKey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
                                       TestOptimizer.SHOULD_SUCCEED );
@@ -410,7 +462,7 @@
                                         0,      // MergeJoinStrategy
                                         0,      // Null
                                         0,      // PlanExecution
-                                        2,      // Project
+                                        1,      // Project
                                         1,      // Select
                                         0,      // Sort
                                         0       // UnionAll
@@ -426,7 +478,7 @@
          
         ProcessorPlan plan = TestOptimizer.helpPlan(
             "SELECT e2 as x FROM pm1.g1 GROUP BY upper(e1), e2",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, //$NON-NLS-1$
             ComparisonMode.EXACT_COMMAND_STRING );
@@ -442,7 +494,7 @@
             0,      // MergeJoinStrategy
             0,      // Null
             0,      // PlanExecution
-            2,      // Project
+            1,      // Project
             0,      // Select
             0,      // Sort
             0       // UnionAll


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestExpressionsInGroupBy.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,6 +25,7 @@
 import static org.teiid.query.optimizer.TestOptimizer.*;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
@@ -36,7 +37,7 @@
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TestInlineView  {
@@ -94,10 +95,8 @@
 		String userQuery = "select q1.a from (select count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey) q1 left outer join bqt1.smallb on q1.a = bqt1.smallb.intkey where q1.intkey = 1"; //$NON-NLS-1$
 		String optimizedQuery = "SELECT v_0.c_0 FROM (SELECT COUNT(g_0.intkey) AS c_0 FROM bqt1.smalla AS g_0 WHERE g_0.intkey = 1 GROUP BY g_0.intkey) AS v_0 LEFT OUTER JOIN bqt1.smallb AS g_1 ON v_0.c_0 = g_1.intkey"; //$NON-NLS-1$
 		
-		List expectedResults = new ArrayList();
-		List row1 = new ArrayList();
-        row1.add(new Integer(1)); 
-		expectedResults.add(row1);
+		List<List<?>> expectedResults = new ArrayList<List<?>>();
+		expectedResults.add(Arrays.asList(1));
 				
 		Set<String> sourceQueries = new HashSet<String>();
         sourceQueries.add("oracle"); //$NON-NLS-1$ 
@@ -116,10 +115,8 @@
 				"where bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.intkey = 1 and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = bqt1.smallb.intkey"; //$NON-NLS-1$
 		String optimizedQuery = "SELECT v_0.c_0 FROM (SELECT COUNT(g_0.intkey) AS c_0 FROM bqt1.smalla AS g_0 WHERE g_0.intkey = 1 GROUP BY g_0.intkey) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey"; //$NON-NLS-1$
 		
-		List expectedResults = new ArrayList();
-		List row1 = new ArrayList();
-        row1.add(new Integer(1)); 
-		expectedResults.add(row1);
+		List<List<?>> expectedResults = new ArrayList<List<?>>();
+		expectedResults.add(Arrays.asList(1));
 				
 		Set<String> sourceQueries = new HashSet<String>();
         sourceQueries.add("oracle"); //$NON-NLS-1$ 
@@ -134,12 +131,10 @@
 	
 	public static InlineViewCase createInlineViewWithDistinctAndOrderBy() throws Exception {
 		String userQuery = "select Q1.a from (select distinct count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey order by bqt1.smalla.intkey) q1 inner join bqt1.smallb as q2 on q1.intkey = q2.intkey where q1.a = 1 and q1.a + q1.intkey = 2"; //$NON-NLS-1$
-        String optimizedQuery = "SELECT v_0.c_1 FROM (SELECT g_0.intkey AS c_0, COUNT(g_0.intkey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.intkey HAVING ((COUNT(g_0.intkey) + g_0.intkey) = 2) AND (COUNT(g_0.intkey) = 1)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey"; //$NON-NLS-1$
+        String optimizedQuery = "SELECT v_0.c_1 FROM (SELECT g_0.intkey AS c_0, COUNT(g_0.intkey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.intkey HAVING (COUNT(g_0.intkey) = 1) AND ((COUNT(g_0.intkey) + g_0.intkey) = 2)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey"; //$NON-NLS-1$
 
-		List expectedResults = new ArrayList();
-		List row1 = new ArrayList();
-        row1.add(new Integer(1)); 
-		expectedResults.add(row1);
+        List<List<?>> expectedResults = new ArrayList<List<?>>();
+		expectedResults.add(Arrays.asList(1));
 				
         Set<String> sourceQueries = new HashSet<String>();
         sourceQueries.add("oracle"); //$NON-NLS-1$ 
@@ -157,7 +152,7 @@
 		String userQuery = "select q1.A from (select count(intkey) as a, intkey, stringkey from vqt.smalla group by intkey, stringkey) q1 inner join vqt.smallb as q2 on q1.intkey = q2.a12345 where q1.a = 2"; //$NON-NLS-1$
 		String optimizedQuery = "SELECT v_0.c_1 FROM (SELECT g_0.IntKey AS c_0, COUNT(g_0.IntKey) AS c_1 FROM BQT1.SmallA AS g_0 GROUP BY g_0.IntKey, g_0.StringKey HAVING COUNT(g_0.IntKey) = 2) AS v_0, BQT1.SmallA AS g_1 WHERE v_0.c_0 = Concat(g_1.StringKey, g_1.StringNum)"; //$NON-NLS-1$
 
-		List expectedResults = new ArrayList();
+		List<List<?>> expectedResults = new ArrayList<List<?>>();
 				
         Set<String> sourceQueries = new HashSet<String>();
         sourceQueries.add("oracle"); //$NON-NLS-1$ 
@@ -172,12 +167,10 @@
 	
 	public static InlineViewCase createInlineViewWithOuterOrderAndGroup() throws Exception {
 		String userQuery = "select count(Q1.a) b from (select distinct count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey order by bqt1.smalla.intkey) q1 inner join bqt1.smallb as q2 on q1.intkey = q2.intkey where q1.a = 1 and q1.a + q1.intkey = 2 group by Q1.a order by b"; //$NON-NLS-1$
-		String optimizedQuery = "SELECT COUNT(v_0.c_1) AS c_0 FROM (SELECT g_0.intkey AS c_0, COUNT(g_0.intkey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.intkey HAVING ((COUNT(g_0.intkey) + g_0.intkey) = 2) AND (COUNT(g_0.intkey) = 1)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey GROUP BY v_0.c_1 ORDER BY c_0"; //$NON-NLS-1$
+		String optimizedQuery = "SELECT COUNT(v_0.c_1) AS c_0 FROM (SELECT g_0.intkey AS c_0, COUNT(g_0.intkey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.intkey HAVING (COUNT(g_0.intkey) = 1) AND ((COUNT(g_0.intkey) + g_0.intkey) = 2)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey GROUP BY v_0.c_1 ORDER BY c_0"; //$NON-NLS-1$
 
-		List expectedResults = new ArrayList();
-		List row1 = new ArrayList();
-        row1.add(new Integer(1));
-		expectedResults.add(row1);
+		List<List<?>> expectedResults = new ArrayList<List<?>>();
+		expectedResults.add(Arrays.asList(1));
 				
         Set<String> sourceQueries = new HashSet<String>();
         sourceQueries.add("oracle"); //$NON-NLS-1$ 
@@ -192,15 +185,11 @@
 	
 	public static InlineViewCase crateInlineViewsInUnions() throws Exception {
 		String userQuery = "select q1.a from (select count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey) q1 left outer join bqt1.smallb on q1.a = bqt1.smallb.intkey where q1.intkey = 1 union all (select count(Q1.a) b from (select distinct count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey order by bqt1.smalla.intkey) q1 inner join bqt1.smallb as q2 on q1.intkey = q2.intkey where q1.a = 1 and q1.a + q1.intkey = 2 group by Q1.a order by b)"; //$NON-NLS-1$
-		String optimizedQuery = "SELECT v_1.c_0 FROM (SELECT COUNT(g_2.intkey) AS c_0 FROM bqt1.smalla AS g_2 WHERE g_2.intkey = 1 GROUP BY g_2.intkey) AS v_1 LEFT OUTER JOIN bqt1.smallb AS g_3 ON v_1.c_0 = g_3.intkey UNION ALL SELECT COUNT(v_0.c_1) AS c_0 FROM (SELECT g_0.IntKey AS c_0, COUNT(g_0.IntKey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.IntKey HAVING ((COUNT(g_0.IntKey) + g_0.IntKey) = 2) AND (COUNT(g_0.IntKey) = 1)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey GROUP BY v_0.c_1"; //$NON-NLS-1$
+		String optimizedQuery = "SELECT v_1.c_0 FROM (SELECT COUNT(g_2.intkey) AS c_0 FROM bqt1.smalla AS g_2 WHERE g_2.intkey = 1 GROUP BY g_2.intkey) AS v_1 LEFT OUTER JOIN bqt1.smallb AS g_3 ON v_1.c_0 = g_3.intkey UNION ALL SELECT COUNT(v_0.c_1) AS c_0 FROM (SELECT g_0.IntKey AS c_0, COUNT(g_0.IntKey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.IntKey HAVING (COUNT(g_0.IntKey) = 1) AND ((COUNT(g_0.IntKey) + g_0.IntKey) = 2)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey GROUP BY v_0.c_1"; //$NON-NLS-1$
 
-		List expectedResults = new ArrayList();
-		List row1 = new ArrayList();
-        row1.add(new Integer(1)); 
-		expectedResults.add(row1);
-		List row2 = new ArrayList();
-        row2.add(new Integer(1)); 
-        expectedResults.add(row2);
+		List<List<?>> expectedResults = new ArrayList<List<?>>();
+		expectedResults.add(Arrays.asList(1));
+        expectedResults.add(Arrays.asList(2));
 				
         Set<String> sourceQueries = new HashSet<String>();
         sourceQueries.add("oracle"); //$NON-NLS-1$ 
@@ -217,15 +206,11 @@
 	public static InlineViewCase createUnionInInlineView() throws Exception{
 		
 	    String userQuery = "select t1.intkey from (select case when q1.a=1 then 2 else 1 end as a from (select count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey) q1 left outer join bqt1.smallb on q1.a = bqt1.smallb.intkey where q1.intkey = 1 union all (select count(Q1.a) b from (select distinct count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey order by bqt1.smalla.intkey) q1 inner join bqt1.smallb as q2 on q1.intkey = q2.intkey where q1.a = 1 and q1.a + q1.intkey = 2 group by Q1.a order by b)) as q3, bqt1.smallb as t1 where q3.a = t1.intkey order by t1.intkey"; //$NON-NLS-1$
-		String optimizedQuery = "SELECT g_4.intkey AS c_0 FROM (SELECT CASE WHEN v_1.c_0 = 1 THEN 2 ELSE 1 END AS c_0 FROM (SELECT COUNT(g_2.intkey) AS c_0 FROM bqt1.smalla AS g_2 WHERE g_2.intkey = 1 GROUP BY g_2.intkey) AS v_1 LEFT OUTER JOIN bqt1.smallb AS g_3 ON v_1.c_0 = g_3.intkey UNION ALL SELECT COUNT(v_0.c_1) AS c_0 FROM (SELECT g_0.IntKey AS c_0, COUNT(g_0.IntKey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.IntKey HAVING ((COUNT(g_0.IntKey) + g_0.IntKey) = 2) AND (COUNT(g_0.IntKey) = 1)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey GROUP BY v_0.c_1) AS v_2, bqt1.smallb AS g_4 WHERE v_2.c_0 = g_4.intkey ORDER BY c_0"; //$NON-NLS-1$
+		String optimizedQuery = "SELECT g_4.intkey AS c_0 FROM (SELECT CASE WHEN v_1.c_0 = 1 THEN 2 ELSE 1 END AS c_0 FROM (SELECT COUNT(g_2.intkey) AS c_0 FROM bqt1.smalla AS g_2 WHERE g_2.intkey = 1 GROUP BY g_2.intkey) AS v_1 LEFT OUTER JOIN bqt1.smallb AS g_3 ON v_1.c_0 = g_3.intkey UNION ALL SELECT COUNT(v_0.c_1) AS c_0 FROM (SELECT g_0.IntKey AS c_0, COUNT(g_0.IntKey) AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.IntKey HAVING (COUNT(g_0.IntKey) = 1) AND ((COUNT(g_0.IntKey) + g_0.IntKey) = 2)) AS v_0, bqt1.smallb AS g_1 WHERE v_0.c_0 = g_1.intkey GROUP BY v_0.c_1) AS v_2, bqt1.smallb AS g_4 WHERE v_2.c_0 = g_4.intkey ORDER BY c_0"; //$NON-NLS-1$
 
-		List expectedResults = new ArrayList();
-		List row1 = new ArrayList();
-        row1.add(new Integer(1)); 
-		expectedResults.add(row1);
-		List row2 = new ArrayList();
-        row2.add(new Integer(2)); 
-        expectedResults.add(row2);
+		List<List<?>> expectedResults = new ArrayList<List<?>>();
+		expectedResults.add(Arrays.asList(1));
+        expectedResults.add(Arrays.asList(2));
 				
         Set<String> sourceQueries = new HashSet<String>();
         sourceQueries.add("oracle"); //$NON-NLS-1$ 
@@ -244,7 +229,7 @@
 	
 	protected void runTest(InlineViewCase testCase) throws Exception {
 		FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	
 		ProcessorPlan plan = TestOptimizer.helpPlan(testCase.userQuery, metadata, null, capFinder, new String[] {testCase.optimizedQuery}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); 
 
@@ -253,7 +238,7 @@
 	
     @Test public void testAliasCreationWithInlineView() {
         FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan("select a, b from (select distinct count(intNum) a, count(stringKey), bqt1.smalla.intkey as b from bqt1.smalla group by bqt1.smalla.intkey) q1 order by q1.a", //$NON-NLS-1$
                 metadata, null, capFinder, new String[] {"SELECT COUNT(g_0.intNum) AS c_0, g_0.intkey AS c_1 FROM bqt1.smalla AS g_0 GROUP BY g_0.intkey ORDER BY c_0"}, true); //$NON-NLS-1$
@@ -263,7 +248,7 @@
     
     @Test public void testAliasPreservationWithInlineView() {
         FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan("select q1.a + 1, q1.b from (select count(bqt1.smalla.intNum) as a, bqt1.smalla.intkey as b from bqt1.smalla group by bqt1.smalla.intNum, bqt1.smalla.intkey order by b) q1 where q1.a = 1", //$NON-NLS-1$
                 metadata, null, capFinder, new String[] {"SELECT (q1.a + 1), q1.b FROM (SELECT COUNT(bqt1.smalla.intNum) AS a, bqt1.smalla.intkey AS b FROM bqt1.smalla GROUP BY bqt1.smalla.intNum, bqt1.smalla.intkey HAVING COUNT(bqt1.smalla.intNum) = 1) AS q1"}, true); //$NON-NLS-1$
@@ -276,7 +261,7 @@
      */
     @Test public void testCrossSourceInlineView() throws Exception {
         FakeCapabilitiesFinder capFinder = getInliveViewCapabilitiesFinder();
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan("select * from (select count(bqt1.smalla.intkey) as a, bqt1.smalla.intkey from bqt1.smalla group by bqt1.smalla.intkey) q1 inner join (select count(bqt2.smallb.intkey) as a, bqt2.smallb.intkey from bqt2.smallb group by bqt2.smallb.intkey) as q2 on q1.intkey = q2.intkey where q1.a = 1", //$NON-NLS-1$
                 metadata, null, capFinder, new String[] {"SELECT v_0.c_0, v_0.c_1 FROM (SELECT g_0.intkey AS c_0, COUNT(g_0.intkey) AS c_1 FROM bqt2.smallb AS g_0 GROUP BY g_0.intkey) AS v_0 ORDER BY c_0", //$NON-NLS-1$


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestInlineView.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,7 +32,11 @@
 import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.KeyRecord.Type;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
@@ -45,10 +49,7 @@
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.SourceSystemFunctions;
 
 @SuppressWarnings("nls")
@@ -61,7 +62,7 @@
         String sql = "select bqt1.smalla.intkey, bqt2.smalla.intkey from bqt1.smalla inner join bqt2.smalla on (bqt1.smalla.intkey = bqt2.smalla.intkey and bqt2.smalla.intkey = 1)"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla WHERE bqt1.smalla.intkey = 1", "SELECT bqt2.smalla.intkey FROM bqt2.smalla WHERE bqt2.smalla.intkey = 1"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla WHERE bqt1.smalla.intkey = 1", "SELECT bqt2.smalla.intkey FROM bqt2.smalla WHERE bqt2.smalla.intkey = 1"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -88,7 +89,7 @@
         String sql = "select bqt1.smalla.intkey from bqt1.smalla left outer join bqt2.smalla on (bqt1.smalla.intkey = bqt2.smalla.intkey and bqt2.smalla.stringkey = 1)"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0 ORDER BY c_0", "SELECT g_0.intkey AS c_0 FROM bqt2.smalla AS g_0 WHERE g_0.stringkey = '1' ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0 ORDER BY c_0", "SELECT g_0.intkey AS c_0 FROM bqt2.smalla AS g_0 WHERE g_0.stringkey = '1' ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -115,7 +116,7 @@
         String sql = "select bqt1.smalla.intkey from bqt1.smalla left outer join bqt2.smalla on (bqt1.smalla.intkey = bqt2.smalla.intkey and bqt1.smalla.stringkey = 1)"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt2.smalla AS g_0 ORDER BY c_0", "SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt2.smalla AS g_0 ORDER BY c_0", "SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -147,7 +148,7 @@
         capFinder.addCapabilities(BQT1, caps); 
         capFinder.addCapabilities(BQT2, caps); 
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         // Plan query
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, 
@@ -184,7 +185,7 @@
         String sql = "select bqt1.smalla.intkey, bqt2.smalla.intkey from bqt1.smalla full outer join bqt2.smalla on (bqt1.smalla.intkey = bqt2.smalla.intkey and bqt1.smalla.stringkey = 1 and bqt2.smalla.stringkey = 1)"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM bqt2.smalla AS g_0 ORDER BY c_0", "SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM bqt2.smalla AS g_0 ORDER BY c_0", "SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -212,7 +213,7 @@
         String sql = "select bqt1.smalla.intkey, bqt2.smalla.intkey from bqt1.smalla, bqt2.smalla where bqt1.smalla.stringkey = bqt2.smalla.intkey and bqt2.smalla.intkey = 1"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla WHERE bqt1.smalla.stringkey = '1'", "SELECT bqt2.smalla.intkey FROM bqt2.smalla WHERE bqt2.smalla.intkey = 1"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla WHERE bqt1.smalla.stringkey = '1'", "SELECT bqt2.smalla.intkey FROM bqt2.smalla WHERE bqt2.smalla.intkey = 1"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -239,7 +240,7 @@
         String sql = "select bqt1.smalla.intkey, bqt2.smalla.intkey from bqt1.smalla, bqt2.smalla where bqt1.smalla.stringkey = bqt2.smalla.intkey and bqt2.smalla.intkey <> 1"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey FROM bqt2.smalla AS g_0 WHERE g_0.intkey <> 1", "SELECT g_0.stringkey AS c_0, g_0.intkey AS c_1 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey FROM bqt2.smalla AS g_0 WHERE g_0.intkey <> 1", "SELECT g_0.stringkey AS c_0, g_0.intkey AS c_1 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -266,7 +267,7 @@
         String sql = "select bqt1.smalla.intkey from bqt1.smalla inner join (select bqt3.smalla.intkey from bqt2.smalla left outer join bqt3.smalla on bqt2.smalla.intkey = bqt3.smalla.intkey and bqt3.smalla.intkey = 1) foo on bqt1.smalla.intkey = foo.intkey"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey FROM bqt3.smalla AS g_0 WHERE g_0.intkey = 1", "SELECT 1 FROM bqt2.smalla AS g_0", "SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey FROM bqt3.smalla AS g_0 WHERE g_0.intkey = 1", "SELECT 1 FROM bqt2.smalla AS g_0", "SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             3,      // Access
@@ -293,7 +294,7 @@
         String sql = "select bqt1.smalla.intkey from bqt1.smalla left outer join (select bqt3.smalla.intkey from bqt3.smalla where bqt3.smalla.intkey = 1) foo on bqt1.smalla.intkey = foo.intkey"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT 1 FROM bqt3.smalla AS g_0 WHERE g_0.intkey = 1", "SELECT g_0.intkey FROM bqt1.smalla AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT 1 FROM bqt3.smalla AS g_0 WHERE g_0.intkey = 1", "SELECT g_0.intkey FROM bqt1.smalla AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ 
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -320,7 +321,7 @@
         String sql = "select bqt2.mediumb.intkey from bqt2.mediumb full outer join (select bqt2.smallb.intkey from bqt2.smalla left outer join bqt2.smallb on bqt2.smalla.intkey = bqt2.smallb.intkey where bqt2.smalla.stringkey = 1) foo on bqt2.mediumb.intkey = foo.intkey"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
                                                     new String[] {"SELECT g_1.intkey FROM bqt2.smalla AS g_0 LEFT OUTER JOIN bqt2.smallb AS g_1 ON g_0.intkey = g_1.intkey WHERE g_0.stringkey = '1'", "SELECT g_0.intkey AS c_0 FROM bqt2.mediumb AS g_0 ORDER BY c_0"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -348,7 +349,7 @@
         String sql = "select bqt2.mediumb.intkey from bqt2.mediumb full outer join (select bqt2.smallb.intkey from bqt2.smalla inner join bqt2.smallb on bqt2.smalla.intkey = bqt2.smallb.intkey where ? = 1) foo on bqt2.mediumb.intkey = foo.intkey"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt2.mediumb AS g_0 ORDER BY c_0", "SELECT g_1.intkey FROM bqt2.smalla AS g_0, bqt2.smallb AS g_1 WHERE (g_0.intkey = g_1.intkey) AND (? = 1)"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt2.mediumb AS g_0 ORDER BY c_0", "SELECT g_1.intkey FROM bqt2.smalla AS g_0, bqt2.smallb AS g_1 WHERE (g_0.intkey = g_1.intkey) AND (? = 1)"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -375,7 +376,7 @@
         String sql = "select bqt2.mediumb.intkey from bqt2.mediumb left outer join (select bqt2.smallb.intkey from bqt2.smalla inner join bqt2.smallb on bqt2.smalla.intkey = bqt2.smallb.intkey where ? = 1) foo on bqt2.mediumb.intkey = foo.intkey"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt2.mediumb AS g_0 ORDER BY c_0", "SELECT g_1.intkey FROM bqt2.smalla AS g_0, bqt2.smallb AS g_1 WHERE (g_0.intkey = g_1.intkey) AND (? = 1)"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt2.mediumb AS g_0 ORDER BY c_0", "SELECT g_1.intkey FROM bqt2.smalla AS g_0, bqt2.smallb AS g_1 WHERE (g_0.intkey = g_1.intkey) AND (? = 1)"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -399,7 +400,7 @@
         String sql = "select bqt1.smalla.intkey, bqt2.smalla.intkey from bqt1.smalla, bqt2.smalla where bqt1.smalla.stringkey = bqt2.smalla.intkey and bqt2.smalla.intkey = 1 and bqt1.smalla.stringkey = '2'"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {});
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {});
 
         TestOptimizer.checkNodeTypes(plan, TestRuleRaiseNull.FULLY_NULL);        
     }
@@ -408,7 +409,7 @@
         String sql = "select bqt1.smalla.intkey, bqt2.smalla.intkey from bqt1.smalla left outer join bqt2.smalla on (bqt1.smalla.stringkey = bqt2.smalla.intkey and bqt2.smalla.intkey = null)"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.intkey, null FROM bqt1.smalla"}); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.intkey FROM bqt1.smalla"}); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);        
     }
@@ -423,7 +424,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                                     new String[] {"SELECT g_3.intkey, g_0.intkey FROM ((bqt1.smallb AS g_0 CROSS JOIN bqt1.mediuma AS g_1) INNER JOIN bqt1.mediumb AS g_2 ON ((g_0.intkey + g_1.intkey) + g_2.intkey) = 1) LEFT OUTER JOIN bqt1.smalla AS g_3 ON g_3.stringkey = g_0.stringkey"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);        
@@ -442,7 +443,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                                     new String[] {"SELECT g_3.intkey, g_0.intkey FROM ((bqt1.smallb AS g_0 CROSS JOIN bqt1.mediuma AS g_1) CROSS JOIN bqt1.mediumb AS g_2) LEFT OUTER JOIN bqt1.smalla AS g_3 ON g_3.stringkey = g_0.stringkey WHERE ((g_3.intkey + g_1.intkey) + g_2.intkey) IS NULL"}, true); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);        
@@ -461,7 +462,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                                     new String[] {"SELECT g_3.intkey, g_2.intkey FROM bqt1.mediuma AS g_0, bqt1.mediumb AS g_1, bqt1.smallb AS g_2, bqt1.smalla AS g_3 WHERE (g_3.stringkey = g_2.stringkey) AND (((g_3.intkey + g_0.intkey) + g_1.intkey) = 1)"}, true); //$NON-NLS-1$ 
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);        
@@ -482,7 +483,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                                     new String[] {"SELECT bqt1.smalla.intkey, MAX(bqt1.smallb.intkey) FROM bqt1.smalla, bqt1.smallb WHERE bqt1.smalla.intkey = bqt1.smallb.intnum GROUP BY bqt1.smallb.intkey, bqt1.smalla.intkey HAVING MAX(bqt1.smallb.intkey) = bqt1.smalla.intkey"}, true); //$NON-NLS-1$ 
                 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);  
@@ -503,7 +504,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan("select Y.e1, Y.e2 FROM vm1.g1 X left outer join vm1.g1 Y on Y.e1 = X.e1 where Y.e3 in (select e3 FROM vm1.g1) or Y.e3 IS NULL", metadata, null, capFinder,  //$NON-NLS-1$
             new String[]{"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 AS g1__1 LEFT OUTER JOIN pm1.g1 ON pm1.g1.e1 = g1__1.e1 WHERE (pm1.g1.e3 IN (SELECT pm1.g1.e3 FROM pm1.g1)) OR (pm1.g1.e3 IS NULL)"}, true); //$NON-NLS-1$ 
@@ -511,7 +512,7 @@
     }
     
     @Test public void testRulePushNonJoinCriteriaPreservesOuterJoin() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         String sql = "select b.intkey from (select intkey from bqt1.smalla) a left outer join (select intkey from bqt1.smallb) b on (1 = 1)"; //$NON-NLS-1$
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, 
@@ -521,7 +522,7 @@
     }
     
     @Test public void testOuterToInnerJoinConversion() {
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         String sql = "select bqt1.smalla.intkey from bqt1.smalla left outer join bqt1.smallb on (bqt1.smalla.intkey = bqt1.smallb.intkey) where bqt1.smallb.intnum = 1"; //$NON-NLS-1$
         
         TestOptimizer.helpPlan(sql, metadata, new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smalla, bqt1.smallb WHERE (bqt1.smalla.intkey = bqt1.smallb.intkey) AND (bqt1.smallb.intnum = 1)"}); //$NON-NLS-1$
@@ -529,21 +530,21 @@
     
     //same as above, but with a right outer join
     @Test public void testOuterToInnerJoinConversion1() {
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         String sql = "select bqt1.smalla.intkey from bqt1.smalla right outer join bqt1.smallb on (bqt1.smalla.intkey = bqt1.smallb.intkey) where bqt1.smalla.intnum = 1"; //$NON-NLS-1$
         
         TestOptimizer.helpPlan(sql, metadata, new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smallb, bqt1.smalla WHERE (bqt1.smalla.intkey = bqt1.smallb.intkey) AND (bqt1.smalla.intnum = 1)"}); //$NON-NLS-1$
     }
     
     @Test public void testOuterToInnerJoinConversion2() {
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         String sql = "select bqt1.smalla.intkey from bqt1.smalla full outer join bqt1.smallb on (bqt1.smalla.intkey = bqt1.smallb.intkey) where bqt1.smallb.intnum = 1"; //$NON-NLS-1$
         
         TestOptimizer.helpPlan(sql, metadata, new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smallb LEFT OUTER JOIN bqt1.smalla ON bqt1.smalla.intkey = bqt1.smallb.intkey WHERE bqt1.smallb.intnum = 1"}); //$NON-NLS-1$
     }    
     
     @Test public void testOuterToInnerJoinConversion3() {
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         String sql = "select bqt1.smalla.intkey from bqt1.smalla full outer join bqt1.smallb on (bqt1.smalla.intkey = bqt1.smallb.intkey) where bqt1.smalla.intnum = 1"; //$NON-NLS-1$
         
         TestOptimizer.helpPlan(sql, metadata, new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smalla LEFT OUTER JOIN bqt1.smallb ON bqt1.smalla.intkey = bqt1.smallb.intkey WHERE bqt1.smalla.intnum = 1"}); //$NON-NLS-1$
@@ -553,7 +554,7 @@
      * non-dependent criteria on each side of a full outer creates an inner join  
      */
     @Test public void testOuterToInnerJoinConversion4() {
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         String sql = "select bqt1.smalla.intkey from bqt1.smalla full outer join bqt1.smallb on (bqt1.smalla.intkey = bqt1.smallb.intkey) where bqt1.smalla.intnum = bqt1.smallb.intnum"; //$NON-NLS-1$
         
         TestOptimizer.helpPlan(sql, metadata, new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smalla, bqt1.smallb WHERE (bqt1.smalla.intkey = bqt1.smallb.intkey) AND (bqt1.smalla.intnum = bqt1.smallb.intnum)"}); //$NON-NLS-1$
@@ -572,7 +573,7 @@
         caps.setFunctionSupport("concat2", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         String sql = "select bqt1.smalla.intkey from bqt1.smalla left outer join bqt1.smallb on (bqt1.smalla.intkey = bqt1.smallb.intkey) where concat2(bqt1.smallb.intnum, '1') = 1"; //$NON-NLS-1$
         
         TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[]{"SELECT bqt1.smallb.intnum, bqt1.smalla.intkey FROM bqt1.smalla LEFT OUTER JOIN bqt1.smallb ON bqt1.smalla.intkey = bqt1.smallb.intkey"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
@@ -588,7 +589,7 @@
         
         String sql = "select x.y, x.intkey from (select max(intnum) y, intkey from bqt1.smalla group by intkey) x where x.y = 1"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                new String[]{"SELECT MAX(intnum), intkey FROM bqt1.smalla GROUP BY intkey HAVING MAX(intnum) = 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
         
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
@@ -620,15 +621,13 @@
      * This tests now passes with RulePlanJoins
      */
     @Test public void testPathologicalAccessPatternCaseCase2976Defect19018() throws Exception{
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
         // add single access pattern to pm1.g4 containing elements e1, e2, and e3
-        FakeMetadataStore store = metadata.getStore();
-        FakeMetadataObject pm4g1 = store.findObject("pm4.g1", FakeMetadataObject.GROUP);//$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(pm4g1);
-        elementIDs.remove(2);
-        FakeMetadataObject pm4g1ap1 = FakeMetadataFactory.createAccessPattern("pm4.g1.ap1", pm4g1, elementIDs); //e1,e2,e4 //$NON-NLS-1$
-        store.addObject(pm4g1ap1);
+        Table pm4g1 = metadata.getGroupID("pm4.g1");
+        List<Column> cols = new ArrayList<Column>(pm4g1.getColumns());
+        cols.remove(2);
+        RealMetadataFactory.createKey(Type.AccessPattern, "pm4.g1.ap1", pm4g1, cols);
 
         String sql = "SELECT pm1.g1.e1, pm2.g1.e1, pm4.g1.e1 " +//$NON-NLS-1$
         "FROM pm1.g1, pm2.g1, pm4.g1 WHERE " +//$NON-NLS-1$
@@ -680,7 +679,7 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder, 
                                       new String[] { 
                                           "SELECT m.intkey, m.intnum, s.intkey, s.intnum FROM BQT2.mediuma AS m, BQT2.smalla AS s WHERE (m.intkey = s.intkey) AND (NOT ((m.intkey + s.intnum) = 26))" }, //$NON-NLS-1$
@@ -703,9 +702,9 @@
         
         Criteria crit = QueryParser.getQueryParser().parseCriteria(critSQL);
         
-        QueryResolver.resolveCriteria(crit, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCriteria(crit, RealMetadataFactory.example1Cached());
         
-        assertEquals(dependent, JoinUtil.isNullDependent(FakeMetadataFactory.example1Cached(), innerGroups, crit));
+        assertEquals(dependent, JoinUtil.isNullDependent(RealMetadataFactory.example1Cached(), innerGroups, crit));
     }
     
     private void helpTestNullDependent(String expressionSQL,
@@ -718,9 +717,9 @@
         
         Expression expr = QueryParser.getQueryParser().parseExpression(expressionSQL);
         
-        ResolverVisitor.resolveLanguageObject(expr, FakeMetadataFactory.example1Cached());
+        ResolverVisitor.resolveLanguageObject(expr, RealMetadataFactory.example1Cached());
         
-        assertEquals(dependent, JoinUtil.isNullDependent(FakeMetadataFactory.example1Cached(), innerGroups, expr));
+        assertEquals(dependent, JoinUtil.isNullDependent(RealMetadataFactory.example1Cached(), innerGroups, expr));
     }
     
     @Test public void testNullDependentVisitor() throws Exception {
@@ -794,7 +793,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),
                                       null, capFinder, 
                                       new String[] { 
                                           "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE pm1.g1.e1 = '1'" }, //$NON-NLS-1$ 
@@ -835,7 +834,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
                                       null, capFinder, 
@@ -881,7 +880,7 @@
         caps.setFunctionSupport(SourceSystemFunctions.IFNULL, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata,
                                       null, capFinder, 
@@ -900,7 +899,7 @@
     @Test public void testCopyCriteriaJoinPushed() throws Exception {
     	String sql = "select pm1.g1.e1 from pm1.g1, pm1.g2 where pm1.g1.e1 = pm1.g2.e1 and pm1.g1.e1 = 5 and pm1.g1.e2 * 5 = pm1.g2.e2"; //$NON-NLS-1$
     	
-    	FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     	
     	ProcessorPlan plan = TestOptimizer.helpPlan(sql,metadata, 
     			new String[] { "SELECT g_0.e2, g_1.e2, g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e1 = '5') AND (g_1.e1 = '5')" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
@@ -931,7 +930,7 @@
         String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla, bqt1.smallb WHERE formatdate(bqt1.smalla.DateValue,'yyyyMM') = '200309' AND bqt1.smalla.intkey = bqt1.smallb.intkey"; //$NON-NLS-1$
              
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.DateValue, bqt1.smalla.intkey, bqt1.smallb.intkey FROM bqt1.smalla, bqt1.smallb WHERE bqt1.smalla.intkey = bqt1.smallb.intkey"}); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.DateValue, bqt1.smalla.intkey, bqt1.smallb.intkey FROM bqt1.smalla, bqt1.smallb WHERE bqt1.smalla.intkey = bqt1.smallb.intkey"}); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -955,7 +954,7 @@
         String sql = "select bqt1.smalla.intkey, bqt1.smallb.intkey from bqt1.smalla left outer join bqt1.smallb on bqt1.smalla.intkey = bqt1.smallb.intkey WHERE formatdate(bqt1.smalla.DateValue,'yyyyMM') = '200309'"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.DateValue, bqt1.smalla.intkey, bqt1.smallb.intkey FROM bqt1.smalla LEFT OUTER JOIN bqt1.smallb ON bqt1.smalla.intkey = bqt1.smallb.intkey"}); //$NON-NLS-1$ 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT bqt1.smalla.DateValue, bqt1.smalla.intkey, bqt1.smallb.intkey FROM bqt1.smalla LEFT OUTER JOIN bqt1.smallb ON bqt1.smalla.intkey = bqt1.smallb.intkey"}); //$NON-NLS-1$ 
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -982,7 +981,7 @@
         String sql = "select bqt1.smalla.intkey, b.intkey from bqt1.smalla left outer join (select * from bqt1.smallb where formatdate(bqt1.smallb.DateValue,'yyyyMM') = '200309') b on bqt1.smalla.intkey = b.intkey"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0 ORDER BY c_0", "SELECT g_0.DateValue AS c_0, g_0.IntKey AS c_1 FROM bqt1.smallb AS g_0 ORDER BY c_1"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {"SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0 ORDER BY c_0", "SELECT g_0.DateValue AS c_0, g_0.IntKey AS c_1 FROM bqt1.smallb AS g_0 ORDER BY c_1"}); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -1006,7 +1005,7 @@
         String sql = "select b.intkey from bqt1.smalla a, bqt2.smallb b, bqt2.smalla b1 where a.intkey = b.intkey and a.intkey = b1.intkey"; //$NON-NLS-1$
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {
         	"SELECT g_1.intkey AS c_0, g_0.intkey AS c_1 FROM bqt2.smallb AS g_0, bqt2.smalla AS g_1 WHERE g_1.intkey = g_0.intkey ORDER BY c_0, c_1", 
         	"SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0 ORDER BY c_0"}); 
 


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestJoinOptimization.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,7 +26,7 @@
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.ExecutionFactory.SupportedJoinCriteria;
 
 
@@ -42,12 +42,12 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2 FROM pm1.g2 AS g_0", "SELECT g_0.e2 FROM pm1.g1 AS g_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$   
         
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.ANY);
         
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2, g_1.e2 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE (g_0.e2 + g_1.e2) = 5"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  
 	}
 	
@@ -60,12 +60,12 @@
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.EQUI);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2 FROM pm1.g2 AS g_0", "SELECT g_0.e2 FROM pm1.g1 AS g_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$   
         
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
         
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2, g_1.e2 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE g_0.e2 < g_1.e2"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  
 	}
 	
@@ -78,12 +78,12 @@
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e2 AS c_0 FROM pm1.g2 AS g_0 ORDER BY c_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$   
         
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.EQUI);
         
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2, g_1.e2 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE g_0.e2 = g_1.e2"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  
 	}
 	
@@ -96,7 +96,7 @@
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
         capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example4(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example4(),  
         		new String[] {"SELECT g_1.e1 AS c_0, g_1.e2 AS c_1, g_0.e1 AS c_2 FROM pm4.g1 AS g_0, pm4.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e2 = g_1.e2) ORDER BY c_0, c_1", "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm4.g1 AS g_0 ORDER BY c_0, c_1"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$   
 	}
 	
@@ -109,7 +109,7 @@
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.KEY);
         capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example4(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example4(),  
         		new String[] {"SELECT g_0.e1, g_1.e1 FROM pm4.g1 AS g_0, pm4.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e2 = g_1.e2)"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$   
 	}
 	
@@ -122,7 +122,7 @@
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2 FROM pm1.g2 AS g_0", "SELECT g_0.e2 FROM pm1.g1 AS g_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$   
 	}
 	
@@ -136,7 +136,7 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2 FROM pm1.g2 AS g_0", "SELECT g_0.e2 FROM pm1.g1 AS g_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$   
 	}
 	
@@ -149,7 +149,7 @@
         caps.setSourceProperty(Capability.JOIN_CRITERIA_ALLOWED, SupportedJoinCriteria.THETA);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e2 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 = 'hello' ORDER BY c_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$   
 	}
 	


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestJoinPushdownRestrictions.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,8 +25,14 @@
 import java.util.Arrays;
 import java.util.List;
 
+import org.junit.Test;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.TestOptimizer.DependentProjectNode;
 import org.teiid.query.optimizer.TestOptimizer.DependentSelectNode;
 import org.teiid.query.optimizer.TestOptimizer.DupRemoveNode;
@@ -49,15 +55,10 @@
 import org.teiid.query.processor.relational.SelectNode;
 import org.teiid.query.processor.relational.SortNode;
 import org.teiid.query.processor.relational.UnionAllNode;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 
-import junit.framework.TestCase;
-
 @SuppressWarnings("nls")
-public class TestLimit extends TestCase {
+public class TestLimit {
 
     private static final int[] FULL_PUSHDOWN = new int[] {
                 1,      // Access
@@ -95,89 +96,63 @@
         UnionAllNode.class
     };
     
-    public TestLimit(String name) {
-        super(name);
-    }
-
-    private static FakeMetadataFacade exampleMetadata() {
+    private static TransformationMetadata exampleMetadata() {
+    	MetadataStore metadataStore = new MetadataStore();
         // Create models
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject vm1 = FakeMetadataFactory.createVirtualModel("vm1");  //$NON-NLS-1$
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        Schema vm1 = RealMetadataFactory.createVirtualModel("vm1", metadataStore);  //$NON-NLS-1$
 
         // Create physical groups
-        FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g2 = FakeMetadataFactory.createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g3 = FakeMetadataFactory.createPhysicalGroup("pm1.g3", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g4 = FakeMetadataFactory.createPhysicalGroup("pm1.g4", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g5 = FakeMetadataFactory.createPhysicalGroup("pm1.g5", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g6 = FakeMetadataFactory.createPhysicalGroup("pm1.g6", pm1); //$NON-NLS-1$
+        Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+        Table pm1g2 = RealMetadataFactory.createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+        Table pm1g3 = RealMetadataFactory.createPhysicalGroup("g3", pm1); //$NON-NLS-1$
+        Table pm1g4 = RealMetadataFactory.createPhysicalGroup("g4", pm1); //$NON-NLS-1$
+        Table pm1g5 = RealMetadataFactory.createPhysicalGroup("g5", pm1); //$NON-NLS-1$
+        Table pm1g6 = RealMetadataFactory.createPhysicalGroup("g6", pm1); //$NON-NLS-1$
                 
         // Create physical elements
-        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
+        RealMetadataFactory.createElements(pm1g1, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g2e = FakeMetadataFactory.createElements(pm1g2, 
+        RealMetadataFactory.createElements(pm1g2, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g3e = FakeMetadataFactory.createElements(pm1g3, 
+        RealMetadataFactory.createElements(pm1g3, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g4e = FakeMetadataFactory.createElements(pm1g4,
+        List<Column> pm1g4e = RealMetadataFactory.createElements(pm1g4,
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        ((FakeMetadataObject)pm1g4e.get(1)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        ((FakeMetadataObject)pm1g4e.get(3)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        List pm1g5e = FakeMetadataFactory.createElements(pm1g5,
+        pm1g4e.get(1).setSelectable(false);
+        pm1g4e.get(3).setSelectable(false);
+        List<Column> pm1g5e = RealMetadataFactory.createElements(pm1g5,
             new String[] { "e1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        ((FakeMetadataObject)pm1g5e.get(0)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        List pm1g6e = FakeMetadataFactory.createElements(pm1g6,
+        pm1g5e.get(0).setSelectable(false);
+        RealMetadataFactory.createElements(pm1g6,
             new String[] { "in", "in3" }, //$NON-NLS-1$ //$NON-NLS-2$ 
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
          
         // Create virtual groups
         QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1 LIMIT 100"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g1 = FakeMetadataFactory.createVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
+        Table vm1g1 = RealMetadataFactory.createVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
 
         // Create virtual elements
-        List vm1g1e = FakeMetadataFactory.createElements(vm1g1, 
+        RealMetadataFactory.createElements(vm1g1, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
 
         QueryNode vm1g2n1 = new QueryNode("SELECT * FROM vm1.g1 ORDER BY e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g2 = FakeMetadataFactory.createVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
+        Table vm1g2 = RealMetadataFactory.createVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
 
         // Create virtual elements
-        List vm1g2e = FakeMetadataFactory.createElements(vm1g2, 
+        RealMetadataFactory.createElements(vm1g2, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
 
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
-        store.addObject(pm1g2);     
-        store.addObjects(pm1g2e);
-        store.addObject(pm1g3); 
-        store.addObjects(pm1g3e);
-        store.addObject(pm1g4);
-        store.addObjects(pm1g4e);
-        store.addObject(pm1g5);
-        store.addObjects(pm1g5e);
-        store.addObject(pm1g6);
-        store.addObjects(pm1g6e);
-        
-        store.addObject(vm1);
-        store.addObject(vm1g1);
-        store.addObjects(vm1g1e);
-        store.addObject(vm1g2);
-        store.addObjects(vm1g2e);
-
-        // Create the facade from the store
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
     }
-    public void testLimit() {
+    @Test public void testLimit() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
@@ -186,7 +161,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -209,7 +184,7 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitPushdown() {
+    @Test public void testLimitPushdown() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true); 
@@ -219,13 +194,13 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 100" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
     }
 
-    public void testLimitWithOffset() {
+    @Test public void testLimitWithOffset() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
@@ -234,7 +209,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -256,7 +231,7 @@
         }, NODE_TYPES);
     }
     
-    public void testPushedLimitWithOffset() throws Exception {
+    @Test public void testPushedLimitWithOffset() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true); 
@@ -266,7 +241,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 150" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -288,7 +263,7 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitWithOffsetFullyPushed() {
+    @Test public void testLimitWithOffsetFullyPushed() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true); 
@@ -299,13 +274,13 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 50, 100" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
     }
     
-    public void testSort() {
+    @Test public void testSort() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
@@ -314,7 +289,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -336,7 +311,7 @@
         }, NODE_TYPES);
     }
 
-    public void testSortPushed() {
+    @Test public void testSortPushed() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
@@ -347,7 +322,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 ORDER BY pm3.g1.e1" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -369,7 +344,7 @@
         }, NODE_TYPES);
     }
 
-    public void testSortPushedWithLimit() {
+    @Test public void testSortPushedWithLimit() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
@@ -381,13 +356,13 @@
         String[] expectedSql = new String[] {
             "SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 ORDER BY pm3.g1.e1 LIMIT 100" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
     }
 
-    public void testSortUnderLimitNotRemoved() {
+    @Test public void testSortUnderLimitNotRemoved() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         // pm3 model supports order by
@@ -397,7 +372,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -420,7 +395,7 @@
     }
     
     //TODO: there is a redundent project node here
-    public void testSortAboveLimitNotPushed() {
+    @Test public void testSortAboveLimitNotPushed() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
@@ -453,7 +428,7 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitNotPushedWithUnion() {
+    @Test public void testLimitNotPushedWithUnion() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -464,7 +439,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1", "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM PM1.g2" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -486,7 +461,7 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitNotPushedWithDupRemove() {
+    @Test public void testLimitNotPushedWithDupRemove() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -497,7 +472,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -519,7 +494,7 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitPushedWithUnionAll() {
+    @Test public void testLimitPushedWithUnionAll() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -530,7 +505,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM PM1.g2 LIMIT 100", "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 LIMIT 100" //$NON-NLS-1$ //$NON-NLS-2$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -552,7 +527,7 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitWithOffsetPushedWithUnion() throws Exception {
+    @Test public void testLimitWithOffsetPushedWithUnion() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -565,7 +540,7 @@
         String[] expectedSql = new String[] {
             "SELECT PM1.g2.e1 AS c_0, PM1.g2.e2 AS c_1, PM1.g2.e3 AS c_2, PM1.g2.e4 AS c_3 FROM PM1.g2 LIMIT 150", "SELECT pm1.g1.e1 AS c_0, pm1.g1.e2 AS c_1, pm1.g1.e3 AS c_2, pm1.g1.e4 AS c_3 FROM pm1.g1 LIMIT 150" //$NON-NLS-1$ //$NON-NLS-2$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -587,7 +562,7 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitNotPushedWithUnionOrderBy() {
+    @Test public void testLimitNotPushedWithUnionOrderBy() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -598,7 +573,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM PM1.g2", "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" //$NON-NLS-1$ //$NON-NLS-2$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -621,7 +596,7 @@
         TestOptimizer.checkNodeTypes(plan, new int[] {1}, new Class[]{DupRemoveSortNode.class});
     }
     
-    public void testCombinedLimits() throws Exception {
+    @Test public void testCombinedLimits() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -633,7 +608,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1 AS c_0 FROM pm1.g1 LIMIT 105" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -655,7 +630,7 @@
         }, NODE_TYPES);
     }
 
-    public void testCombinedLimitsWithOffset() throws Exception {
+    @Test public void testCombinedLimitsWithOffset() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -668,13 +643,13 @@
         String[] expectedSql = new String[] {
             "SELECT pm1.g1.e1 AS c_0 FROM pm1.g1 LIMIT 10, 60" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);  
 
         TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
     }
 
-    public void testInlineView() {
+    @Test public void testInlineView() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         //caps.setCapabilitySupport(SourceCapabilities.QUERY_ORDERBY, true);
@@ -687,7 +662,7 @@
         String[] expectedSql = new String[] {
             "SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 LIMIT 100" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
@@ -702,7 +677,7 @@
      * 
      * @since 4.3
      */
-    public void testInlineViewAboveLimitNotMerged() {
+    @Test public void testInlineViewAboveLimitNotMerged() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
@@ -716,7 +691,7 @@
         String[] expectedSql = new String[] {
             "SELECT v_0.c_0, v_0.c_1, v_0.c_2, v_0.c_3 FROM (SELECT pm3.g1.e1 AS c_0, pm3.g1.e2 AS c_1, pm3.g1.e3 AS c_2, pm3.g1.e4 AS c_3 FROM pm3.g1 LIMIT 100) AS v_0 ORDER BY c_0" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
@@ -726,7 +701,7 @@
      * since there is no order by with the nested limit, the criteria can be pushed through 
      *
      */
-    public void testCriteriaPushedUnderLimit() {
+    @Test public void testCriteriaPushedUnderLimit() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
@@ -738,13 +713,13 @@
         String[] expectedSql = new String[] {
             "SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 WHERE pm3.g1.e1 = '1' LIMIT 100" //$NON-NLS-1$
             };
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
     }
     
-    public void testInlineViewJoin() {
+    @Test public void testInlineViewJoin() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_UNION, true);
@@ -755,7 +730,7 @@
         String sql = "SELECT x FROM ((SELECT e1 as x FROM pm1.g1 LIMIT 700) c INNER JOIN (SELECT e1 FROM pm1.g2) d ON d.e1 = c.x) order by x LIMIT 5";//$NON-NLS-1$
         String[] expectedSql = new String[] {"SELECT e1 FROM pm1.g1 LIMIT 700", "SELECT e1 FROM pm1.g2"};//$NON-NLS-1$ //$NON-NLS-2$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                       null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -788,7 +763,7 @@
         });
     }
     
-    public void testDontPushSelectWithOrderedLimit() {
+    @Test public void testDontPushSelectWithOrderedLimit() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
@@ -796,7 +771,7 @@
         String sql = "select * from (SELECT e1 as x FROM pm1.g1 order by x LIMIT 700) y where x = 1";//$NON-NLS-1$
         String[] expectedSql = new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0"};//$NON-NLS-1$ 
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                       null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -818,7 +793,7 @@
         }, NODE_TYPES);
     }
     
-    public void testDontPushSelectWithOrderedLimit1() {
+    @Test public void testDontPushSelectWithOrderedLimit1() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
@@ -826,7 +801,7 @@
         String sql = "select * from (SELECT e1 as x FROM pm1.g1 order by x LIMIT 10, 700) y where x = 1";//$NON-NLS-1$
         String[] expectedSql = new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0"};//$NON-NLS-1$ 
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                       null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -848,11 +823,11 @@
         }, NODE_TYPES);
     }
     
-    public void testLimitWithNoAccessNode() {
+    @Test public void testLimitWithNoAccessNode() {
         String sql = "select 1 limit 1";//$NON-NLS-1$
         String[] expectedSql = new String[] {};
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), expectedSql);  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), expectedSql);  
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
                                         0,      // Access
@@ -876,7 +851,7 @@
     /**
      * Note here that the criteria made it to the having clause 
      */
-    public void testAggregateCriteriaOverUnSortedLimit() {
+    @Test public void testAggregateCriteriaOverUnSortedLimit() {
         String sql = "select a from (SELECT MAX(e2) as a FROM pm1.g1 GROUP BY e2 LIMIT 1) x where a = 0"; //$NON-NLS-1$
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -889,15 +864,15 @@
         
         String[] expectedSql = new String[] {"SELECT MAX(e2) FROM pm1.g1 GROUP BY e2 HAVING MAX(e2) = 0 LIMIT 1"};//$NON-NLS-1$ 
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, expectedSql, true);  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, expectedSql, true);  
 
         TestOptimizer.checkNodeTypes(plan, FULL_PUSHDOWN, NODE_TYPES);
     }
     
-    public void testSortWithLimitInlineView() {
+    @Test public void testSortWithLimitInlineView() {
         String sql = "select e1 from (select pm1.g1.e1, pm1.g1.e2 from pm1.g1 order by pm1.g1.e1, pm1.g1.e2 limit 1) x"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0, g_0.e2"}); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0, g_0.e2"}); //$NON-NLS-1$
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
                 1,      // Access


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestLimit.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -39,11 +39,13 @@
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.function.FunctionTree;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
@@ -81,10 +83,7 @@
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
 import org.teiid.query.sql.visitor.ValueIteratorProviderCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 import org.teiid.query.validator.Validator;
 import org.teiid.query.validator.ValidatorReport;
@@ -457,284 +456,205 @@
         checkNodeTypes(plan, new int[] {expectedCount}, new Class[] {DependentJoin.class});
     }
                 
-	public static FakeMetadataFacade example1() {
+	public static TransformationMetadata example1() {
+		MetadataStore metadataStore = new MetadataStore();
 		// Create models
-		FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject pm2 = FakeMetadataFactory.createPhysicalModel("pm2"); //$NON-NLS-1$
-		FakeMetadataObject vm1 = FakeMetadataFactory.createVirtualModel("vm1");	 //$NON-NLS-1$
+		Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        Schema pm2 = RealMetadataFactory.createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
+		Schema vm1 = RealMetadataFactory.createVirtualModel("vm1", metadataStore);	 //$NON-NLS-1$
 
 		// Create physical groups
-		FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g2 = FakeMetadataFactory.createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g3 = FakeMetadataFactory.createPhysicalGroup("pm1.g3", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g4 = FakeMetadataFactory.createPhysicalGroup("pm1.g4", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g5 = FakeMetadataFactory.createPhysicalGroup("pm1.g5", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g6 = FakeMetadataFactory.createPhysicalGroup("pm1.g6", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g7 = FakeMetadataFactory.createPhysicalGroup("pm1.g7", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g8 = FakeMetadataFactory.createPhysicalGroup("pm1.g8", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm2g1 = FakeMetadataFactory.createPhysicalGroup("pm2.g1", pm2); //$NON-NLS-1$
-        FakeMetadataObject pm2g2 = FakeMetadataFactory.createPhysicalGroup("pm2.g2", pm2); //$NON-NLS-1$
-        FakeMetadataObject pm2g3 = FakeMetadataFactory.createPhysicalGroup("pm2.g3", pm2); //$NON-NLS-1$
+		Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+		Table pm1g2 = RealMetadataFactory.createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+		Table pm1g3 = RealMetadataFactory.createPhysicalGroup("g3", pm1); //$NON-NLS-1$
+        Table pm1g4 = RealMetadataFactory.createPhysicalGroup("g4", pm1); //$NON-NLS-1$
+        Table pm1g5 = RealMetadataFactory.createPhysicalGroup("g5", pm1); //$NON-NLS-1$
+        Table pm1g6 = RealMetadataFactory.createPhysicalGroup("g6", pm1); //$NON-NLS-1$
+        Table pm1g7 = RealMetadataFactory.createPhysicalGroup("g7", pm1); //$NON-NLS-1$
+        Table pm1g8 = RealMetadataFactory.createPhysicalGroup("g8", pm1); //$NON-NLS-1$
+        Table pm2g1 = RealMetadataFactory.createPhysicalGroup("g1", pm2); //$NON-NLS-1$
+        Table pm2g2 = RealMetadataFactory.createPhysicalGroup("g2", pm2); //$NON-NLS-1$
+        Table pm2g3 = RealMetadataFactory.createPhysicalGroup("g3", pm2); //$NON-NLS-1$
 				
 		// Create physical elements
-		List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
+		RealMetadataFactory.createElements(pm1g1, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g2e = FakeMetadataFactory.createElements(pm1g2, 
+		RealMetadataFactory.createElements(pm1g2, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g3e = FakeMetadataFactory.createElements(pm1g3, 
+		RealMetadataFactory.createElements(pm1g3, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g4e = FakeMetadataFactory.createElements(pm1g4, 
+        RealMetadataFactory.createElements(pm1g4, 
             new String[] { "e1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List pm1g5e = FakeMetadataFactory.createElements(pm1g5, 
+        RealMetadataFactory.createElements(pm1g5, 
             new String[] { "e1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List pm1g6e = FakeMetadataFactory.createElements(pm1g6, 
+        RealMetadataFactory.createElements(pm1g6, 
             new String[] { "e1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List pm1g7e = FakeMetadataFactory.createElements(pm1g7, 
+        RealMetadataFactory.createElements(pm1g7, 
             new String[] { "e1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List pm1g8e = FakeMetadataFactory.createElements(pm1g8, 
+        RealMetadataFactory.createElements(pm1g8, 
             new String[] { "e1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List pm2g1e = FakeMetadataFactory.createElements(pm2g1, 
+        RealMetadataFactory.createElements(pm2g1, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm2g2e = FakeMetadataFactory.createElements(pm2g2, 
+        RealMetadataFactory.createElements(pm2g2, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm2g3e = FakeMetadataFactory.createElements(pm2g3, 
+        RealMetadataFactory.createElements(pm2g3, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
 
 		// Create virtual groups
 		QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g1 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
+		Table vm1g1 = RealMetadataFactory.createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
 
 		QueryNode vm1g2n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g2 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
+		Table vm1g2 = RealMetadataFactory.createUpdatableVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
 
 		//defect 8096
 		QueryNode vm1sub1n1 = new QueryNode("SELECT * FROM vm1.g1 WHERE e1 IN (SELECT e1 FROM vm1.g3)"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1sub1 = FakeMetadataFactory.createVirtualGroup("vm1.sub1", vm1, vm1sub1n1); //$NON-NLS-1$
+		Table vm1sub1 = RealMetadataFactory.createVirtualGroup("sub1", vm1, vm1sub1n1); //$NON-NLS-1$
 
 		QueryNode vm1g3n1 = new QueryNode("SELECT * FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g3 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.g3", vm1, vm1g3n1); //$NON-NLS-1$
+		Table vm1g3 = RealMetadataFactory.createUpdatableVirtualGroup("g3", vm1, vm1g3n1); //$NON-NLS-1$
 
         QueryNode vm1g4n1 = new QueryNode("SELECT pm1.g1.e1, pm1.g2.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1=pm1.g2.e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g4 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.g4", vm1, vm1g4n1); //$NON-NLS-1$
+        Table vm1g4 = RealMetadataFactory.createUpdatableVirtualGroup("g4", vm1, vm1g4n1); //$NON-NLS-1$
 
         QueryNode vm1g5n1 = new QueryNode("SELECT DISTINCT pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g5 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.g5", vm1, vm1g5n1); //$NON-NLS-1$
+        Table vm1g5 = RealMetadataFactory.createUpdatableVirtualGroup("g5", vm1, vm1g5n1); //$NON-NLS-1$
 
         QueryNode vm1g6n1 = new QueryNode("SELECT e1, convert(e2, string), 3 as e3, ((e2+e4)/3) as e4 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g6 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.g6", vm1, vm1g6n1); //$NON-NLS-1$
+        Table vm1g6 = RealMetadataFactory.createUpdatableVirtualGroup("g6", vm1, vm1g6n1); //$NON-NLS-1$
 
 		QueryNode vm1u1n1 = new QueryNode("SELECT * FROM pm1.g1 UNION SELECT * FROM pm1.g2 UNION ALL SELECT * FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1u1 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u1", vm1, vm1u1n1); //$NON-NLS-1$
+		Table vm1u1 = RealMetadataFactory.createUpdatableVirtualGroup("u1", vm1, vm1u1n1); //$NON-NLS-1$
 
 		QueryNode vm1u2n1 = new QueryNode("SELECT * FROM pm1.g1 UNION SELECT * FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1u2 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u2", vm1, vm1u2n1); //$NON-NLS-1$
+		Table vm1u2 = RealMetadataFactory.createUpdatableVirtualGroup("u2", vm1, vm1u2n1); //$NON-NLS-1$
 
 		QueryNode vm1u3n1 = new QueryNode("SELECT e1 FROM pm1.g1 UNION SELECT convert(e2, string) as x FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1u3 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u3", vm1, vm1u3n1); //$NON-NLS-1$
+		Table vm1u3 = RealMetadataFactory.createUpdatableVirtualGroup("u3", vm1, vm1u3n1); //$NON-NLS-1$
 
         QueryNode vm1u4n1 = new QueryNode("SELECT concat(e1, 'x') as v1 FROM pm1.g1 UNION ALL SELECT e1 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1u4 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u4", vm1, vm1u4n1); //$NON-NLS-1$
+        Table vm1u4 = RealMetadataFactory.createUpdatableVirtualGroup("u4", vm1, vm1u4n1); //$NON-NLS-1$
 
         QueryNode vm1u5n1 = new QueryNode("SELECT concat(e1, 'x') as v1 FROM pm1.g1 UNION ALL SELECT concat('a', e1) FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1u5 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u5", vm1, vm1u5n1); //$NON-NLS-1$
+        Table vm1u5 = RealMetadataFactory.createUpdatableVirtualGroup("u5", vm1, vm1u5n1); //$NON-NLS-1$
 
         QueryNode vm1u6n1 = new QueryNode("SELECT x1.e1 AS elem, 'xyz' AS const FROM pm1.g1 AS x1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1u6 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u6", vm1, vm1u6n1); //$NON-NLS-1$
+        Table vm1u6 = RealMetadataFactory.createUpdatableVirtualGroup("u6", vm1, vm1u6n1); //$NON-NLS-1$
 
         QueryNode vm1u7n1 = new QueryNode("SELECT 's1' AS const, e1 FROM pm1.g1 UNION ALL SELECT 's2', e1 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1u7 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u7", vm1, vm1u7n1); //$NON-NLS-1$
+        Table vm1u7 = RealMetadataFactory.createUpdatableVirtualGroup("u7", vm1, vm1u7n1); //$NON-NLS-1$
 
         QueryNode vm1u8n1 = new QueryNode("SELECT const, e1 FROM vm1.u7 UNION ALL SELECT 's3', e1 FROM pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1u8 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u8", vm1, vm1u8n1); //$NON-NLS-1$
+        Table vm1u8 = RealMetadataFactory.createUpdatableVirtualGroup("u8", vm1, vm1u8n1); //$NON-NLS-1$
 
         QueryNode vm1u9n1 = new QueryNode("SELECT e1 as a, e1 as b FROM pm1.g1 UNION ALL SELECT e1, e1 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1u9 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.u9", vm1, vm1u9n1); //$NON-NLS-1$
+        Table vm1u9 = RealMetadataFactory.createUpdatableVirtualGroup("u9", vm1, vm1u9n1); //$NON-NLS-1$
 
         QueryNode vm1a1n1 = new QueryNode("SELECT e1, SUM(e2) AS sum_e2 FROM pm1.g1 GROUP BY e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1a1 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.a1", vm1, vm1a1n1); //$NON-NLS-1$
+        Table vm1a1 = RealMetadataFactory.createUpdatableVirtualGroup("a1", vm1, vm1a1n1); //$NON-NLS-1$
         
         QueryNode vm1a2n1 = new QueryNode("SELECT e1, SUM(e2) AS sum_e2 FROM pm1.g1 GROUP BY e1 HAVING SUM(e2) > 5"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1a2 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.a2", vm1, vm1a2n1); //$NON-NLS-1$
+        Table vm1a2 = RealMetadataFactory.createUpdatableVirtualGroup("a2", vm1, vm1a2n1); //$NON-NLS-1$
 
         QueryNode vm1a3n1 = new QueryNode("SELECT SUM(e2) AS sum_e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1a3 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.a3", vm1, vm1a3n1); //$NON-NLS-1$
+        Table vm1a3 = RealMetadataFactory.createUpdatableVirtualGroup("a3", vm1, vm1a3n1); //$NON-NLS-1$
         
         QueryNode vm1a4n1 = new QueryNode("SELECT COUNT(*) FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1a4 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.a4", vm1, vm1a4n1); //$NON-NLS-1$
+        Table vm1a4 = RealMetadataFactory.createUpdatableVirtualGroup("a4", vm1, vm1a4n1); //$NON-NLS-1$
 
         QueryNode vm1a5n1 = new QueryNode("SELECT vm1.a4.count FROM vm1.a4 UNION ALL SELECT COUNT(*) FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1a5 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.a5", vm1, vm1a5n1); //$NON-NLS-1$
+        Table vm1a5 = RealMetadataFactory.createUpdatableVirtualGroup("a5", vm1, vm1a5n1); //$NON-NLS-1$
 
         QueryNode vm1a6n1 = new QueryNode("SELECT COUNT(*) FROM vm1.u2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1a6 = FakeMetadataFactory.createUpdatableVirtualGroup("vm1.a6", vm1, vm1a6n1); //$NON-NLS-1$
+        Table vm1a6 = RealMetadataFactory.createUpdatableVirtualGroup("a6", vm1, vm1a6n1); //$NON-NLS-1$
         
         QueryNode vm1g7n1 = new QueryNode("select DECODESTRING(e1, 'S,Pay,P,Rec') as e1, e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g7 = FakeMetadataFactory.createVirtualGroup("vm1.g7", vm1, vm1g7n1); //$NON-NLS-1$
+        Table vm1g7 = RealMetadataFactory.createVirtualGroup("g7", vm1, vm1g7n1); //$NON-NLS-1$
         
 		// Create virtual elements
-		List vm1g1e = FakeMetadataFactory.createElements(vm1g1, 
+		RealMetadataFactory.createElements(vm1g1, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1g2e = FakeMetadataFactory.createElements(vm1g2, 
+		RealMetadataFactory.createElements(vm1g2, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1g3e = FakeMetadataFactory.createElements(vm1g3, 
+		RealMetadataFactory.createElements(vm1g3, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
 		//for defect 8096
-		List vm1sub1e = FakeMetadataFactory.createElements(vm1sub1, 
+		RealMetadataFactory.createElements(vm1sub1, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g4e = FakeMetadataFactory.createElements(vm1g4, 
+        RealMetadataFactory.createElements(vm1g4, 
             new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g5e = FakeMetadataFactory.createElements(vm1g5, 
+        RealMetadataFactory.createElements(vm1g5, 
             new String[] { "e1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING});
-        List vm1g6e = FakeMetadataFactory.createElements(vm1g6, 
+        RealMetadataFactory.createElements(vm1g6, 
             new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g7e = FakeMetadataFactory.createElements(vm1g7, 
+        RealMetadataFactory.createElements(vm1g7, 
             new String[] { "e1", "e2"}, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
-        List vm1u1e = FakeMetadataFactory.createElements(vm1u1, 
+        RealMetadataFactory.createElements(vm1u1, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1u2e = FakeMetadataFactory.createElements(vm1u2, 
+		RealMetadataFactory.createElements(vm1u2, 
 			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1u3e = FakeMetadataFactory.createElements(vm1u3, 
+		RealMetadataFactory.createElements(vm1u3, 
 			new String[] { "e1" }, //$NON-NLS-1$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List vm1u4e = FakeMetadataFactory.createElements(vm1u4, 
+        RealMetadataFactory.createElements(vm1u4, 
             new String[] { "v1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List vm1u5e = FakeMetadataFactory.createElements(vm1u5, 
+        RealMetadataFactory.createElements(vm1u5, 
             new String[] { "v1" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List vm1u6e = FakeMetadataFactory.createElements(vm1u6, 
+        RealMetadataFactory.createElements(vm1u6, 
             new String[] { "elem", "const" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1u7e = FakeMetadataFactory.createElements(vm1u7, 
+        RealMetadataFactory.createElements(vm1u7, 
             new String[] { "const", "e1" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1u8e = FakeMetadataFactory.createElements(vm1u8, 
+        RealMetadataFactory.createElements(vm1u8, 
             new String[] { "const", "e1" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1u9e = FakeMetadataFactory.createElements(vm1u9, 
+        RealMetadataFactory.createElements(vm1u9, 
             new String[] { "a", "b" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1a1e = FakeMetadataFactory.createElements(vm1a1, 
+        RealMetadataFactory.createElements(vm1a1, 
             new String[] { "e1", "sum_e2" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.LONG });
-        List vm1a2e = FakeMetadataFactory.createElements(vm1a2, 
+        RealMetadataFactory.createElements(vm1a2, 
             new String[] { "e1", "sum_e2" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.LONG });
-        List vm1a3e = FakeMetadataFactory.createElements(vm1a3, 
+        RealMetadataFactory.createElements(vm1a3, 
             new String[] { "sum_e2" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.LONG });
-        List vm1a4e = FakeMetadataFactory.createElements(vm1a4, 
+        RealMetadataFactory.createElements(vm1a4, 
             new String[] { "count" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1a5e = FakeMetadataFactory.createElements(vm1a5, 
+        RealMetadataFactory.createElements(vm1a5, 
             new String[] { "count" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1a6e = FakeMetadataFactory.createElements(vm1a6, 
+        RealMetadataFactory.createElements(vm1a6, 
             new String[] { "count" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
 			
-		// Add all objects to the store
-		FakeMetadataStore store = new FakeMetadataStore();
-		store.addObject(pm1);
-		store.addObject(pm1g1);		
-		store.addObjects(pm1g1e);
-		store.addObject(pm1g2);		
-		store.addObjects(pm1g2e);
- 		store.addObject(pm1g3);		
-		store.addObjects(pm1g3e);
-        store.addObject(pm1g4);     
-        store.addObjects(pm1g4e);
-        store.addObject(pm1g5);     
-        store.addObjects(pm1g5e);
-        store.addObject(pm1g6);     
-        store.addObjects(pm1g6e);
-        store.addObject(vm1g7);
-        store.addObjects(vm1g7e);
-        store.addObject(pm1g7);     
-        store.addObjects(pm1g7e);
-        store.addObject(pm1g8);     
-        store.addObjects(pm1g8e);
-        
-        store.addObject(pm2);
-        store.addObject(pm2g1);     
-        store.addObjects(pm2g1e);
-        store.addObject(pm2g2);     
-        store.addObjects(pm2g2e);
-        store.addObject(pm2g3);     
-        store.addObjects(pm2g3e);
-       	
-		store.addObject(vm1);
-		store.addObject(vm1g1);
-		store.addObjects(vm1g1e);
-		store.addObject(vm1g2);
-		store.addObjects(vm1g2e);
-		store.addObject(vm1g3);
-		store.addObjects(vm1g3e);
-
-		//for defect 8096
-		store.addObject(vm1sub1);
-		store.addObjects(vm1sub1e);
-		
-        store.addObject(vm1g4);
-        store.addObjects(vm1g4e);
-        store.addObject(vm1g5);
-        store.addObjects(vm1g5e);
-        store.addObject(vm1g6);
-        store.addObjects(vm1g6e);
-		store.addObject(vm1u1);
-		store.addObjects(vm1u1e);
-		store.addObject(vm1u2);
-		store.addObjects(vm1u2e);
-		store.addObject(vm1u3);
-		store.addObjects(vm1u3e);
-        store.addObject(vm1u4);
-        store.addObjects(vm1u4e);
-        store.addObject(vm1u5);
-        store.addObjects(vm1u5e);
-        store.addObject(vm1u6);
-        store.addObjects(vm1u6e);
-        store.addObject(vm1u7);
-        store.addObjects(vm1u7e);
-        store.addObject(vm1u8);
-        store.addObjects(vm1u8e);
-        store.addObject(vm1u9);
-        store.addObjects(vm1u9e);
-        store.addObject(vm1a1);
-        store.addObjects(vm1a1e);   
-        store.addObject(vm1a2);
-        store.addObjects(vm1a2e);   
-        store.addObject(vm1a3);
-        store.addObjects(vm1a3e);   
-        store.addObject(vm1a4);
-        store.addObjects(vm1a4e);   
-        store.addObject(vm1a5);
-        store.addObjects(vm1a5e);   
-        store.addObject(vm1a6);
-        store.addObjects(vm1a6e);   
-						
-		// Create the facade from the store
-		return new FakeMetadataFacade(store);
+		return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
 	}	
 				
 	// ################################## ACTUAL TESTS ################################
@@ -748,48 +668,48 @@
 	}
 
 	@Test public void testQueryPhysical() { 
-		ProcessorPlan plan = helpPlan("SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+		ProcessorPlan plan = helpPlan("SELECT pm1.g1.e1, e2, pm1.g1.e3 as a, e4 as b FROM pm1.g1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] {"SELECT pm1.g1.e1, e2, pm1.g1.e3, e4 FROM pm1.g1"} ); //$NON-NLS-1$
 		assertTrue(!plan.requiresTransaction(true));
         checkNodeTypes(plan, FULL_PUSHDOWN);    
 	}
     
 	@Test public void testSelectStarPhysical() { 
-		ProcessorPlan plan = helpPlan("SELECT * FROM pm1.g1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+		ProcessorPlan plan = helpPlan("SELECT * FROM pm1.g1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1"} ); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
 	}
 
 	@Test public void testQuerySingleSourceVirtual() { 
-		ProcessorPlan plan = helpPlan("SELECT * FROM vm1.g1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+		ProcessorPlan plan = helpPlan("SELECT * FROM vm1.g1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1"} ); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
 	}
 	
 	@Test public void testQueryMultiSourceVirtual() { 
-		ProcessorPlan plan = helpPlan("SELECT * FROM vm1.g2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+		ProcessorPlan plan = helpPlan("SELECT * FROM vm1.g2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "SELECT g_0.e1, g_0.e2, g_1.e3, g_1.e4 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE g_0.e1 = g_1.e1"} ); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
 	}
 
 	@Test public void testPhysicalVirtualJoinWithCriteria() throws Exception { 
-		ProcessorPlan plan = helpPlan("SELECT vm1.g2.e1 from vm1.g2, pm1.g3 where vm1.g2.e1=pm1.g3.e1 and vm1.g2.e2 > 0", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+		ProcessorPlan plan = helpPlan("SELECT vm1.g2.e1 from vm1.g2, pm1.g3 where vm1.g2.e1=pm1.g3.e1 and vm1.g2.e2 > 0", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1, pm1.g3 AS g_2 WHERE (g_0.e1 = g_1.e1) AND (g_0.e1 = g_2.e1) AND (g_0.e2 > 0)" }, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
 	}
     
     @Test public void testQueryWithExpression() { 
-        helpPlan("SELECT e4 FROM pm3.g1 WHERE e4 < convert('2001-11-01 10:30:40.42', timestamp)", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        helpPlan("SELECT e4 FROM pm3.g1 WHERE e4 < convert('2001-11-01 10:30:40.42', timestamp)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "SELECT e4 FROM pm3.g1 WHERE e4 < {ts'2001-11-01 10:30:40.42'}"} ); //$NON-NLS-1$
     }
     
     @Test public void testInsert() { 
-        helpPlan("Insert into pm1.g1 (pm1.g1.e1, pm1.g1.e2) values ('MyString', 1)", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        helpPlan("Insert into pm1.g1 (pm1.g1.e1, pm1.g1.e2) values ('MyString', 1)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2) VALUES ('MyString', 1)"} ); //$NON-NLS-1$
     }
     
     @Test public void testUpdate1() { 
-      	helpPlan("Update pm1.g1 Set pm1.g1.e1= LTRIM('MyString'), pm1.g1.e2= 1 where pm1.g1.e3= 'true'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+      	helpPlan("Update pm1.g1 Set pm1.g1.e1= LTRIM('MyString'), pm1.g1.e2= 1 where pm1.g1.e3= 'true'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "UPDATE pm1.g1 SET pm1.g1.e1 = 'MyString', pm1.g1.e2 = 1 WHERE pm1.g1.e3 = TRUE"} ); //$NON-NLS-1$
   	}
   	
@@ -797,7 +717,7 @@
     	BasicSourceCapabilities bsc = TestOptimizer.getTypicalCapabilities();
     	bsc.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
     	DefaultCapabilitiesFinder dcf = new DefaultCapabilitiesFinder(bsc);
-        helpPlan("Update pm1.g1 Set pm1.g1.e1= LTRIM('MyString'), pm1.g1.e2= 1 where pm1.g1.e2= convert(pm1.g1.e4, integer)", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        helpPlan("Update pm1.g1 Set pm1.g1.e1= LTRIM('MyString'), pm1.g1.e2= 1 where pm1.g1.e2= convert(pm1.g1.e4, integer)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "UPDATE pm1.g1 SET e1 = 'MyString', e2 = 1 WHERE pm1.g1.e2 = convert(pm1.g1.e4, integer)"}, dcf, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
     }
     
@@ -805,7 +725,7 @@
     	BasicSourceCapabilities bsc = TestOptimizer.getTypicalCapabilities();
     	bsc.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
     	DefaultCapabilitiesFinder dcf = new DefaultCapabilitiesFinder(bsc);
-    	helpPlan("Delete from pm1.g1 where pm1.g1.e1 = cast(pm1.g1.e2 AS string)", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+    	helpPlan("Delete from pm1.g1 where pm1.g1.e1 = cast(pm1.g1.e2 AS string)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 			new String[] { "DELETE FROM pm1.g1 WHERE pm1.g1.e1 = convert(pm1.g1.e2, string)"}, dcf, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
   	}
 
@@ -936,16 +856,16 @@
     
     @Test public void testPushCriteriaThroughUnion11() {
         helpPlan("select * from vm1.u8 where const = 's3' or e1 is null", example1(), //$NON-NLS-1$
-            new String[] { "SELECT 's3', e1 FROM pm1.g3", //$NON-NLS-1$
-                            "SELECT 's2', e1 FROM pm1.g2 WHERE e1 IS NULL", //$NON-NLS-1$
-                            "SELECT 's1', e1 FROM pm1.g1 WHERE e1 IS NULL" } );     //$NON-NLS-1$
+            new String[] { "SELECT e1 FROM pm1.g3", //$NON-NLS-1$
+                            "SELECT e1 FROM pm1.g2 WHERE e1 IS NULL", //$NON-NLS-1$
+                            "SELECT e1 FROM pm1.g1 WHERE e1 IS NULL" } );     //$NON-NLS-1$
     }
 
     @Test public void testPushCriteriaThroughUnion12() {
         helpPlan("select * from vm1.u8 where const = 's1' or e1 is null", example1(), //$NON-NLS-1$
-            new String[] { "SELECT 's3', e1 FROM pm1.g3 WHERE e1 IS NULL", //$NON-NLS-1$
-                            "SELECT 's2', e1 FROM pm1.g2 WHERE e1 IS NULL", //$NON-NLS-1$
-                            "SELECT 's1', e1 FROM pm1.g1" } );     //$NON-NLS-1$
+            new String[] { "SELECT e1 FROM pm1.g3 WHERE e1 IS NULL", //$NON-NLS-1$
+                            "SELECT e1 FROM pm1.g2 WHERE e1 IS NULL", //$NON-NLS-1$
+                            "SELECT e1 FROM pm1.g1" } );     //$NON-NLS-1$
     }
 
     /** defect #4997 */
@@ -1064,7 +984,7 @@
 
     @Test public void testDefect5282_2() {
         helpPlan("select count(*) FROM vm1.a4", example1(), //$NON-NLS-1$
-            new String[] { "SELECT 1 FROM pm1.g1" } );     //$NON-NLS-1$
+            new String[] { } );     //$NON-NLS-1$
     }
 
     @Test public void testDefect5282_3() {
@@ -1096,8 +1016,8 @@
     
     @Test public void testDefect6425_1() {
         helpPlan("select * from vm1.u9", example1(), //$NON-NLS-1$
-            new String[] { "SELECT e1, e1 FROM pm1.g1", //$NON-NLS-1$
-                            "SELECT e1, e1 FROM pm1.g2" } );     //$NON-NLS-1$
+            new String[] { "SELECT e1 FROM pm1.g1", //$NON-NLS-1$
+                            "SELECT e1 FROM pm1.g2" } );     //$NON-NLS-1$
     }
 
     @Test public void testDefect6425_2() {
@@ -1358,29 +1278,8 @@
         }); 
     }
     
-    @Test public void testTempGroup() {
-        ProcessorPlan plan = helpPlan("select e1 from tm1.g1 where e1 = 'x'", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
-            new String[] { "SELECT e1 FROM tm1.g1" }); //$NON-NLS-1$
-        checkNodeTypes(plan, new int[] {
-            1,      // Access
-            0,      // DependentAccess
-            0,      // DependentSelect
-            0,      // DependentProject
-            0,      // DupRemove
-            0,      // Grouping
-            0,      // NestedLoopJoinStrategy
-            0,      // MergeJoinStrategy
-            0,      // Null
-            0,      // PlanExecution
-            1,      // Project
-            1,      // Select
-            0,      // Sort
-            0       // UnionAll
-        }); 
-    }
-    
     @Test public void testNotPushDistinct() throws Exception {
-        ProcessorPlan plan = helpPlan("select distinct e1 from pm1.g1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select distinct e1 from pm1.g1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm1.g1.e1 FROM pm1.g1" }, new DefaultCapabilitiesFinder(), ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -1401,73 +1300,73 @@
     }
 
     @Test public void testPushDistinct() {
-        ProcessorPlan plan = helpPlan("select distinct e1 from pm3.g1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select distinct e1 from pm3.g1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT e1 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctSort() {
-        ProcessorPlan plan = helpPlan("select distinct e1 from pm3.g1 order by e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select distinct e1 from pm3.g1 order by e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT e1 FROM pm3.g1 ORDER BY e1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctWithCriteria() {
-        ProcessorPlan plan = helpPlan("select distinct e1 from pm3.g1 where e1 = 'x'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select distinct e1 from pm3.g1 where e1 = 'x'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT e1 FROM pm3.g1 WHERE e1 = 'x'" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual1() {
-        ProcessorPlan plan = helpPlan("select * from vm1.g12", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select * from vm1.g12", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual2() {
-        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g12", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g12", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual3() {
-        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g12 ORDER BY e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g12 ORDER BY e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 ORDER BY pm3.g1.e1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual4() {
-        ProcessorPlan plan = helpPlan("select * from vm1.g13", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select * from vm1.g13", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual5() {
-        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g13", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g13", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual6() {
-        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g13 ORDER BY e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g13 ORDER BY e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 ORDER BY pm3.g1.e1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual7() {
-        ProcessorPlan plan = helpPlan("select * from vm1.g14", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select * from vm1.g14", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual8() {
-        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g14", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g14", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
 
     @Test public void testPushDistinctVirtual9() {
-        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g14 ORDER BY e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select DISTINCT * from vm1.g14 ORDER BY e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1 ORDER BY pm3.g1.e1" }); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
@@ -1476,7 +1375,7 @@
      * Defect #7819
      */
     @Test public void testPushDistinctWithExpressions() {
-        ProcessorPlan plan = helpPlan("SELECT DISTINCT * FROM vm1.g15", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT DISTINCT * FROM vm1.g15", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm3.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -1497,7 +1396,7 @@
     }
 
     @Test public void testNestedSubquery() {
-        ProcessorPlan plan = helpPlan("SELECT IntKey, LongNum FROM (SELECT IntKey, LongNum FROM (SELECT IntKey, LongNum, DoubleNum FROM BQT2.SmallA ) AS x ) AS y ORDER BY IntKey", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT IntKey, LongNum FROM (SELECT IntKey, LongNum FROM (SELECT IntKey, LongNum, DoubleNum FROM BQT2.SmallA ) AS x ) AS y ORDER BY IntKey", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
             new String[] { "SELECT IntKey, LongNum FROM BQT2.SmallA order by intkey" }); //$NON-NLS-1$
 
         checkNodeTypes(plan, FULL_PUSHDOWN);                                    
@@ -1505,7 +1404,7 @@
 
     /** Tests a user's order by is pushed to the source */
     @Test public void testPushOrderBy() {
-        ProcessorPlan plan = helpPlan("SELECT pm3.g1.e1 FROM pm3.g1 ORDER BY e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT pm3.g1.e1 FROM pm3.g1 ORDER BY e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm3.g1.e1 FROM pm3.g1 ORDER BY pm3.g1.e1"}); //$NON-NLS-1$
 
         checkNodeTypes(plan, FULL_PUSHDOWN);                                    
@@ -1513,7 +1412,7 @@
     
     /** Tests an order by is not pushed to source due to join */
     @Test public void testDontPushOrderByWithJoin() {
-        ProcessorPlan plan = helpPlan("SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1 INNER JOIN pm2.g2 ON pm3.g1.e1 = pm2.g2.e1 ORDER BY pm3.g1.e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1 INNER JOIN pm2.g2 ON pm3.g1.e1 = pm2.g2.e1 ORDER BY pm3.g1.e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1 ORDER BY pm3.g1.e1", //$NON-NLS-1$
                            "SELECT pm2.g2.e1 FROM pm2.g2 ORDER BY pm2.g2.e1"}); //$NON-NLS-1$
 
@@ -1540,7 +1439,7 @@
      * transformation order by is discarded 
      */
     @Test public void testPushOrderByThroughFrame() {
-        ProcessorPlan plan = helpPlan("SELECT e1, e2 FROM vm1.g14 ORDER BY e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT e1, e2 FROM vm1.g14 ORDER BY e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1 ORDER BY pm3.g1.e2"}); //$NON-NLS-1$
 
         checkNodeTypes(plan, FULL_PUSHDOWN);                                    
@@ -1550,7 +1449,7 @@
      * Tests that query transformation order by is discarded by
      */
     @Test public void testPushOrderByThroughFrame2() {
-        ProcessorPlan plan = helpPlan("SELECT e1, e2 FROM vm1.g1 ORDER BY e2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT e1, e2 FROM vm1.g1 ORDER BY e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 order by e2"}); //$NON-NLS-1$
 
         checkNodeTypes(plan, FULL_PUSHDOWN);                                    
@@ -1561,7 +1460,7 @@
      * if there is a UNION in the query transformation 
      */
     @Test public void testPushOrderByThroughFrame4_Union() {
-        ProcessorPlan plan = helpPlan("SELECT e1, e2 FROM vm1.g17 ORDER BY e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT e1, e2 FROM vm1.g17 ORDER BY e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1", //$NON-NLS-1$
                            "SELECT pm3.g2.e1, pm3.g2.e2 FROM pm3.g2"}); //$NON-NLS-1$
 
@@ -1590,7 +1489,7 @@
             "FROM (BQT1.SmallA RIGHT OUTER JOIN BQT2.MediumB ON BQT1.SmallA.IntKey = BQT2.MediumB.IntKey) " +  //$NON-NLS-1$
             "RIGHT OUTER JOIN BQT3.MediumB ON BQT2.MediumB.IntKey = BQT3.MediumB.IntKey " +   //$NON-NLS-1$
             "WHERE BQT3.MediumB.IntKey < 1500",  //$NON-NLS-1$
-            FakeMetadataFactory.exampleBQTCached(),
+            RealMetadataFactory.exampleBQTCached(),
             new String[] { 
                 "SELECT BQT3.MediumB.IntKey FROM BQT3.MediumB WHERE BQT3.MediumB.IntKey < 1500 order by intkey", //$NON-NLS-1$
                 "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA WHERE BQT1.SmallA.IntKey < 1500 order by intkey", //$NON-NLS-1$
@@ -1618,7 +1517,7 @@
     @Test public void testFunctionSimplification1() {
         ProcessorPlan plan = helpPlan(
             "SELECT x FROM vm1.g18 WHERE x = 92.0",   //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             new String[] { 
                 "SELECT e4 FROM pm1.g1 WHERE e4 = 0.92" }); //$NON-NLS-1$
 
@@ -1643,7 +1542,7 @@
     @Test public void testCantPushJoin1() {
         ProcessorPlan plan = helpPlan(
             "SELECT a.e1, b.e2 FROM pm1.g1 a, pm1.g2 b WHERE a.e1 = b.e1",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, TestOptimizer.getGenericFinder(false),
             new String[] {"SELECT a.e1 FROM pm1.g1 AS a", "SELECT b.e1, b.e2 FROM pm1.g2 AS b"}, //$NON-NLS-1$ //$NON-NLS-2$
             SHOULD_SUCCEED );
@@ -1669,7 +1568,7 @@
     @Test public void testCantPushJoin2() {
         ProcessorPlan plan = helpPlan(
             "SELECT a.e1, b.e2 FROM pm1.g1 a, pm1.g2 b, pm2.g1 c WHERE a.e1 = b.e1 AND b.e1 = c.e1",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, TestOptimizer.getGenericFinder(false),
             new String[] {"SELECT a.e1 FROM pm1.g1 AS a",  //$NON-NLS-1$
                            "SELECT b.e1, b.e2 FROM pm1.g2 AS b", //$NON-NLS-1$
@@ -1703,7 +1602,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT a.e1, b.e2 FROM pm1.g1 a, pm1.g1 b WHERE a.e1 = b.e1",  //$NON-NLS-1$
@@ -1724,7 +1623,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT a.e1 AS x, concat(a.e2, b.e2) AS y FROM pm1.g1 a, pm1.g1 b WHERE a.e1 = b.e1",  //$NON-NLS-1$
@@ -1759,7 +1658,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT pm1.g1.e1 FROM pm1.g1 RIGHT OUTER JOIN pm1.g2 ON pm1.g1.e1 = pm1.g2.e1",  //$NON-NLS-1$
@@ -1778,7 +1677,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT pm1.g1.e1 FROM pm1.g1 RIGHT OUTER JOIN pm1.g2 ON pm1.g1.e1 = pm1.g2.e1",  //$NON-NLS-1$
@@ -1815,7 +1714,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT pm1.g1.e1 FROM pm1.g1 RIGHT OUTER JOIN pm1.g2 ON pm1.g1.e1 = pm1.g2.e1 || 'x'",  //$NON-NLS-1$
@@ -1851,7 +1750,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1, e2 as x FROM pm1.g1 GROUP BY e1, e2",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1, e2 FROM pm1.g1 GROUP BY e1, e2"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -1869,7 +1768,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1, MAX(e2) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -1886,7 +1785,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1, e2 as x FROM pm1.g1 GROUP BY e1, e2",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1, e2 FROM pm1.g1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -1919,7 +1818,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT x+2 AS y FROM (SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT MAX(e2) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -1953,7 +1852,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -1969,7 +1868,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2001,7 +1900,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1 FROM pm1.g1 GROUP BY e1 HAVING MAX(e1) = 'zzz'",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2033,7 +1932,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT MAX(e1) FROM pm1.g1",  //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT MAX(e1) FROM pm1.g1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2050,7 +1949,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT MAX(e1) FROM pm1.g1 GROUP BY e1", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT MAX(e1) FROM pm1.g1 GROUP BY e1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2067,7 +1966,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2086,7 +1985,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2108,7 +2007,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT e2, MAX(e1) FROM pm1.g1 GROUP BY e2 HAVING COUNT(e1) > 0", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e2, e1 FROM pm1.g1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2143,7 +2042,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT COUNT(length(e1)) FROM pm1.g1", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2178,7 +2077,7 @@
          
         ProcessorPlan plan = helpPlan(
             "SELECT COUNT(*) FROM pm1.g1 GROUP BY e1 HAVING length(e1) > 0", //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, capFinder,
             new String[] {"SELECT e1 FROM pm1.g1"}, //$NON-NLS-1$
             SHOULD_SUCCEED );
@@ -2223,10 +2122,10 @@
             "SELECT MAX(sa.datevalue) FROM bqt1.smalla AS sb " + //$NON-NLS-1$
             "WHERE (sb.intkey = sa.intkey) AND (sa.stringkey = sb.stringkey) ))"; //$NON-NLS-1$
 
-        String sqlOut = "SELECT g_0.intkey FROM bqt1.smalla AS g_0 WHERE (g_0.intkey = 46) AND (g_0.stringkey = '46') AND (g_0.datevalue = (SELECT g_0.datevalue FROM bqt1.smalla AS g_1 WHERE (g_1.intkey = g_0.intkey) AND (g_1.stringkey = g_0.stringkey)))"; //$NON-NLS-1$
+        String sqlOut = "SELECT g_0.intkey FROM bqt1.smalla AS g_0 WHERE (g_0.intkey = 46) AND (g_0.stringkey = '46') AND (g_0.datevalue = (SELECT MAX(g_0.datevalue) FROM bqt1.smalla AS g_1 WHERE (g_1.intkey = g_0.intkey) AND (g_1.stringkey = g_0.stringkey)))"; //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sqlIn, 
-            FakeMetadataFactory.exampleBQTCached(),
+            RealMetadataFactory.exampleBQTCached(),
             null, capFinder,
             new String[] {sqlOut}, 
             ComparisonMode.EXACT_COMMAND_STRING );
@@ -2235,7 +2134,7 @@
     }
     
     @Test public void testQueryManyJoin() throws Exception { 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = helpPlan("SELECT pm1.g1.e1 FROM pm1.g1 JOIN ((pm1.g2 JOIN pm1.g3 ON pm1.g2.e1=pm1.g3.e1) JOIN pm1.g4 ON pm1.g3.e1=pm1.g4.e1) ON pm1.g1.e1=pm1.g4.e1",  //$NON-NLS-1$
             metadata,
             new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1, pm1.g3 AS g_2, pm1.g4 AS g_3 WHERE (g_1.e1 = g_2.e1) AND (g_2.e1 = g_3.e1) AND (g_0.e1 = g_3.e1)"}, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
@@ -2243,7 +2142,7 @@
     }
     
     @Test public void testPushSelectDistinct() { 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = helpPlan("SELECT DISTINCT e1 FROM pm3.g1",  //$NON-NLS-1$
             metadata,
             new String[] { "SELECT DISTINCT e1 FROM pm3.g1"} ); //$NON-NLS-1$
@@ -2258,7 +2157,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1 FROM pm1.g1 WHERE upper(e1) = 'X'",  //$NON-NLS-1$
@@ -2280,7 +2179,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT lower(e1) FROM pm1.g1 WHERE upper(e1) = 'X'",  //$NON-NLS-1$
@@ -2302,7 +2201,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT lower(e1), upper(e1), e2 FROM pm1.g1 WHERE upper(e1) = 'X'",  //$NON-NLS-1$
@@ -2323,7 +2222,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT lower(e1), upper(e1) FROM pm1.g1 WHERE upper(e1) = 'X'",  //$NON-NLS-1$
@@ -2360,7 +2259,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT x FROM (SELECT lower(e1) AS x, upper(e1) AS y FROM pm1.g1 WHERE upper(e1) = 'X') AS z",  //$NON-NLS-1$
@@ -2382,7 +2281,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT y, e, x FROM (SELECT lower(e1) AS x, upper(e1) AS y, 5 as z, e1 AS e FROM pm1.g1 WHERE upper(e1) = 'X') AS w",  //$NON-NLS-1$
@@ -2402,7 +2301,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT upper(lower(e1)) FROM pm1.g1",  //$NON-NLS-1$
@@ -2440,7 +2339,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1, lower(e1) FROM pm1.g1 WHERE upper(e1) = 'X' ORDER BY e1",  //$NON-NLS-1$
@@ -2464,7 +2363,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1, lower(e1) AS x FROM pm1.g1 WHERE upper(e1) = 'X' ORDER BY x",  //$NON-NLS-1$
@@ -2488,7 +2387,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1, x FROM (SELECT e1, lower(e1) AS x FROM pm1.g1 WHERE upper(e1) = 'X') AS z ORDER BY x",  //$NON-NLS-1$
@@ -2510,7 +2409,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = convert(pm1.g2.e2, string) AND upper(pm1.g1.e1) = 'X'",  //$NON-NLS-1$
@@ -2532,7 +2431,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = convert(pm1.g2.e2, string) AND pm1.g1.e1 = concat(pm1.g3.e1, 'a') AND upper(pm1.g1.e1) = 'X'",  //$NON-NLS-1$
@@ -2570,7 +2469,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT pm1.g1.e1, pm1.g2.e3 FROM pm1.g1, pm1.g2, (SELECT e1 AS x FROM pm1.g3) AS g WHERE pm1.g1.e1 = convert(pm1.g2.e2, string) AND pm1.g1.e1 = concat(g.x, 'a') AND upper(pm1.g1.e1) = 'X'",  //$NON-NLS-1$
@@ -2607,7 +2506,7 @@
         caps.setFunctionSupport("convert", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT StringCol AS E " +  //$NON-NLS-1$
@@ -2638,7 +2537,7 @@
     }    
 
     @Test public void testDefect9827() { 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan("SELECT intkey, c FROM (SELECT DISTINCT b.intkey, b.intnum, a.stringkey AS c FROM bqt1.smalla AS a, bqt1.smallb AS b WHERE a.INTKEY = b.INTKEY) AS x ORDER BY x.intkey", metadata, //$NON-NLS-1$
             new String[] {"SELECT DISTINCT b.intkey, b.intnum, a.stringkey FROM bqt1.smalla AS a, bqt1.smallb AS b WHERE a.INTKEY = b.INTKEY"} ); //$NON-NLS-1$
@@ -2853,7 +2752,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT ltrim(e1) FROM pm1.g2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT ltrim(e1) FROM pm1.g2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 IN (SELECT ltrim(e1) FROM pm1.g2)" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -2872,7 +2771,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT ltrim(e1) as m FROM pm1.g2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT ltrim(e1) as m FROM pm1.g2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 IN (SELECT ltrim(e1) FROM pm1.g2)" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
 
@@ -2896,7 +2795,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(),  
             null, capFinder,
             new String[] { "SELECT g1__1.e1 FROM pm1.g1 AS g1__1 WHERE g1__1.e2 = (SELECT MAX(pm1.g1.e2) FROM pm1.g1 WHERE pm1.g1.e1 = g1__1.e1)" }, SHOULD_SUCCEED); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -2919,7 +2818,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -2945,7 +2844,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -2954,7 +2853,7 @@
     }
         
     /** Should use merge join since neither access node is "strong" - order by's pushed to source */
-    @Test public void testUseMergeJoin3(){
+    @Test public void testUseMergeJoin3() throws Exception{
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
 
@@ -2965,9 +2864,8 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -2991,7 +2889,7 @@
     }    
 
     /** Model supports order by, should be pushed to the source */
-    @Test public void testUseMergeJoin4(){
+    @Test public void testUseMergeJoin4() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
 
@@ -3002,11 +2900,9 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3040,7 +2936,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3064,7 +2960,7 @@
     }
     
     /** one side of join supports order by, the other doesn't*/
-    @Test public void testUseMergeJoin7(){
+    @Test public void testUseMergeJoin7() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g2 WHERE pm1.g1.e1 = pm2.g2.e1";//$NON-NLS-1$
 
@@ -3077,11 +2973,9 @@
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm2.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3105,7 +2999,7 @@
     }     
 
     /** reverse of testUseMergeJoin7 */
-    @Test public void testUseMergeJoin7a(){
+    @Test public void testUseMergeJoin7a() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g2 WHERE pm1.g1.e1 = pm2.g2.e1";//$NON-NLS-1$
 
@@ -3118,11 +3012,9 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm2.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3146,7 +3038,7 @@
     }   
 
     /** function on one side of join should prevent order by from being pushed down*/
-    @Test public void testUseMergeJoin8(){
+    @Test public void testUseMergeJoin8() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm2.g2 WHERE concat(pm1.g1.e1, 'x') = pm2.g2.e1";//$NON-NLS-1$
 
@@ -3160,11 +3052,9 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm2.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3188,7 +3078,7 @@
     }
 
     /** Model supports order by, functions in join criteria */
-    @Test public void testUseMergeJoin9(){
+    @Test public void testUseMergeJoin9() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE concat(pm1.g1.e1, 'x') = concat(pm1.g2.e1, 'x')";//$NON-NLS-1$
 
@@ -3201,11 +3091,9 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 500, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3229,7 +3117,7 @@
     } 
 
     /** should be one dependent join */
-    @Test public void testMultiMergeJoin1(){
+    @Test public void testMultiMergeJoin1() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g2.e1 = pm1.g3.e1";//$NON-NLS-1$
 
@@ -3241,13 +3129,10 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE / 4));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE));
-        FakeMetadataObject g3 = metadata.getStore().findObject("pm1.g3", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE / 4, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE, metadata);
+        RealMetadataFactory.setCardinality("pm1.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3282,7 +3167,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
             null, capFinder,
             new String[] { "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA ORDER BY BQT1.SmallA.IntKey",  //$NON-NLS-1$
                             "SELECT BQT2.SmallB.IntKey FROM BQT2.SmallB ORDER BY BQT2.SmallB.IntKey" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
@@ -3317,7 +3202,7 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3342,7 +3227,7 @@
     }
         
     @Test public void testNoFrom() { 
-        ProcessorPlan plan = helpPlan("SELECT 1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT 1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {} ); 
 
         checkNodeTypes(plan, new int[] {
@@ -3363,7 +3248,7 @@
         });                                    
     }
 
-    @Test public void testINCriteria_defect10718(){
+    @Test public void testINCriteria_defect10718() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
 
@@ -3378,11 +3263,9 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY -1, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,
@@ -3406,7 +3289,7 @@
     }
     
     @Test public void testDefect10711(){
-        ProcessorPlan plan = helpPlan("SELECT * from vm1.g1a as X", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT * from vm1.g1a as X", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1"} ); //$NON-NLS-1$
 
         checkNodeTypes(plan, FULL_PUSHDOWN);         
@@ -3415,7 +3298,7 @@
     
     // SELECT 5, SUM(IntKey) FROM BQT1.SmallA
     @Test public void testAggregateNoGroupByWithExpression() {
-        ProcessorPlan plan = helpPlan("SELECT 5, SUM(IntKey) FROM BQT1.SmallA", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT 5, SUM(IntKey) FROM BQT1.SmallA", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
             new String[] { "SELECT IntKey FROM BQT1.SmallA"  }); //$NON-NLS-1$
 
         checkNodeTypes(plan, new int[] {
@@ -3439,7 +3322,7 @@
     /** defect 11630 - note that the lookup function is not pushed down, it will actually be evaluated before being sent to the connector */
     @Test public void testLookupFunction() {
 
-        ProcessorPlan plan = helpPlan("SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1', 'e1', 'e2', 1) IS NULL"  }); //$NON-NLS-1$
 
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -3449,7 +3332,7 @@
     /** case 5213 - note here that the lookup cannot be pushed down since it is dependent upon an element symbol*/
     @Test public void testLookupFunction2() throws Exception {
 
-        ProcessorPlan plan = helpPlan("SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1','e1', 'e2', e2) IS NULL", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1','e1', 'e2', e2) IS NULL", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e2, g_0.e1 FROM pm1.g2 AS g_0"  }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
 
         checkNodeTypes(plan, new int[] {
@@ -3473,7 +3356,7 @@
     
     /** defect 21965 */
     @Test public void testLookupFunctionInSelect() {
-        ProcessorPlan plan = helpPlan("SELECT e1, LOOKUP('pm1.g1','e1', 'e2', 1) FROM pm1.g2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT e1, LOOKUP('pm1.g1','e1', 'e2', 1) FROM pm1.g2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT e1, LOOKUP('pm1.g1','e1', 'e2', 1) FROM pm1.g2"  }); //$NON-NLS-1$
 
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -3481,7 +3364,7 @@
     
     // SELECT * FROM (SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT DISTINCT IntNum FROM BQT1.SmallA) AS x WHERE IntKey = 0
     @Test public void testCase1649() {
-        ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT DISTINCT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA) AS x WHERE IntKey = 0", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT DISTINCT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA) AS x WHERE IntKey = 0", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT IntKey FROM BQT1.SmallA WHERE IntKey = 0", "SELECT IntNum FROM BQT1.SmallA WHERE IntNum = 0"  }); //$NON-NLS-1$ //$NON-NLS-2$
 
         checkNodeTypes(plan, new int[] {
@@ -3504,10 +3387,10 @@
 
     // SELECT * FROM (SELECT IntKey a, IntNum b FROM BQT1.SmallA UNION ALL SELECT Intkey, Intkey FROM BQT1.SmallA) as x WHERE b = 0
     @Test public void testCase1727_1() {
-        ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT IntKey a, IntNum b FROM BQT1.SmallA UNION ALL SELECT Intkey, Intkey FROM BQT1.SmallA) as x WHERE b = 0", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT IntKey a, IntNum b FROM BQT1.SmallA UNION ALL SELECT Intkey, Intkey FROM BQT1.SmallA) as x WHERE b = 0", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
             new String[] { 
                 "SELECT IntKey, IntNum FROM BQT1.SmallA WHERE IntNum = 0", //$NON-NLS-1$
-                "SELECT IntKey, IntKey FROM BQT1.SmallA WHERE IntKey = 0"  }); //$NON-NLS-1$ 
+                "SELECT IntKey FROM BQT1.SmallA WHERE IntKey = 0"  }); //$NON-NLS-1$ 
 
         checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -3529,10 +3412,10 @@
 
     // SELECT * FROM (SELECT IntKey a, IntNum b FROM BQT1.SmallA UNION ALL SELECT Intkey, Intkey FROM BQT1.SmallA) as x WHERE b = 0
     @Test public void testCase1727_2() {
-        ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT IntKey a, IntKey b FROM BQT1.SmallA UNION ALL SELECT IntKey, IntNum FROM BQT1.SmallA) as x WHERE b = 0", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT IntKey a, IntKey b FROM BQT1.SmallA UNION ALL SELECT IntKey, IntNum FROM BQT1.SmallA) as x WHERE b = 0", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
             new String[] { 
                 "SELECT IntKey, IntNum FROM BQT1.SmallA WHERE IntNum = 0", //$NON-NLS-1$
-                "SELECT IntKey, IntKey FROM BQT1.SmallA WHERE IntKey = 0"  }); //$NON-NLS-1$ 
+                "SELECT IntKey FROM BQT1.SmallA WHERE IntKey = 0"  }); //$NON-NLS-1$ 
 
         checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -3553,7 +3436,7 @@
     }
     
     @Test public void testCountStarOverSelectDistinct() {
-        ProcessorPlan plan = helpPlan("SELECT COUNT(*) FROM (SELECT DISTINCT IntNum, Intkey FROM bqt1.smalla) AS x", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT COUNT(*) FROM (SELECT DISTINCT IntNum, Intkey FROM bqt1.smalla) AS x", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
                                       new String[] { 
                                           "SELECT DISTINCT IntNum, Intkey FROM bqt1.smalla" }); //$NON-NLS-1$ 
 
@@ -3577,7 +3460,7 @@
 
     //virtual group with two elements. One selectable, one not
     @Test public void testVirtualGroup1() {
-        ProcessorPlan plan = helpPlan("select e2 from vm1.g35", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("select e2 from vm1.g35", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT e2 FROM pm1.g1" } ); //$NON-NLS-1$
 
         checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);     
@@ -3585,7 +3468,7 @@
     
     @Test public void testBQT9500_126() throws Exception {
         String sql = "SELECT IntKey, LongNum, expr FROM (SELECT IntKey, LongNum, concat(LongNum, 'abc') FROM BQT2.SmallA ) AS x ORDER BY IntKey"; //$NON-NLS-1$
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
                                       new String[] { 
                                           "SELECT g_0.IntKey AS c_0, g_0.LongNum AS c_1 FROM BQT2.SmallA AS g_0 ORDER BY c_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ 
 
@@ -3638,7 +3521,7 @@
             expectedSql = new String[] { "SELECT IntKey FROM BQT1.SmallA", "SELECT IntKey FROM BQT1.SmallB" };  //$NON-NLS-1$//$NON-NLS-2$
         }
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(sql, metadata, 
                                       null, capFinder, expectedSql, SHOULD_SUCCEED);  
@@ -3715,7 +3598,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT 1 UNION ALL SELECT 2", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT 1 UNION ALL SELECT 2", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, new String[] {}, SHOULD_SUCCEED);  
 
         checkNodeTypes(plan, new int[] {
@@ -3745,7 +3628,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT 1 UNION ALL SELECT IntKey FROM BQT1.SmallA", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT 1 UNION ALL SELECT IntKey FROM BQT1.SmallA", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, new String[] {"SELECT IntKey FROM BQT1.SmallA"}, SHOULD_SUCCEED);   //$NON-NLS-1$
 
         checkNodeTypes(plan, new int[] {
@@ -3775,7 +3658,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT 1", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT 1", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, new String[] {"SELECT IntKey FROM BQT1.SmallA"}, SHOULD_SUCCEED);   //$NON-NLS-1$
 
         checkNodeTypes(plan, new int[] {
@@ -3805,7 +3688,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB UNION ALL SELECT IntKey FROM BQT1.SmallA", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB UNION ALL SELECT IntKey FROM BQT1.SmallA", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB UNION ALL SELECT IntKey FROM BQT1.SmallA"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -3823,7 +3706,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB UNION ALL SELECT IntKey FROM BQT2.SmallA", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB UNION ALL SELECT IntKey FROM BQT2.SmallA", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB", "SELECT IntKey FROM BQT2.SmallA"},  //$NON-NLS-1$ //$NON-NLS-2$
                                       SHOULD_SUCCEED);   
@@ -3855,7 +3738,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION SELECT IntKey FROM BQT1.SmallB UNION SELECT IntKey FROM BQT1.SmallA", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT IntKey FROM BQT1.SmallA UNION SELECT IntKey FROM BQT1.SmallB UNION SELECT IntKey FROM BQT1.SmallA", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA UNION SELECT IntKey FROM BQT1.SmallB UNION SELECT IntKey FROM BQT1.SmallA"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -3872,7 +3755,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT COUNT(*) FROM (SELECT IntKey FROM BQT1.SmallA UNION SELECT IntKey FROM BQT1.SmallB) AS x", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT COUNT(*) FROM (SELECT IntKey FROM BQT1.SmallA UNION SELECT IntKey FROM BQT1.SmallB) AS x", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA UNION SELECT IntKey FROM BQT1.SmallB"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -3906,7 +3789,7 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT IntKey+2, StringKey AS x FROM BQT1.SmallA UNION SELECT IntKey, StringKey FROM BQT1.SmallB", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT IntKey+2, StringKey AS x FROM BQT1.SmallA UNION SELECT IntKey, StringKey FROM BQT1.SmallB", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT (IntKey + 2), StringKey AS x FROM BQT1.SmallA UNION SELECT IntKey, StringKey FROM BQT1.SmallB"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -3925,7 +3808,7 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("(SELECT IntKey FROM BQT1.SmallA ORDER BY IntKey) UNION ALL SELECT IntKey FROM BQT1.SmallB", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("(SELECT IntKey FROM BQT1.SmallA ORDER BY IntKey) UNION ALL SELECT IntKey FROM BQT1.SmallB", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -3944,7 +3827,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, false);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         ProcessorPlan plan = helpPlan("SELECT DISTINCT IntKey FROM BQT1.SmallA UNION ALL SELECT IntKey FROM BQT1.SmallB", metadata,  //$NON-NLS-1$
                                       null, capFinder, 
@@ -3965,7 +3848,7 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT x FROM (SELECT IntKey+2, StringKey AS x FROM BQT1.SmallA UNION SELECT IntKey, StringKey FROM BQT1.SmallB) AS g", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT x FROM (SELECT IntKey+2, StringKey AS x FROM BQT1.SmallA UNION SELECT IntKey, StringKey FROM BQT1.SmallB) AS g", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT (IntKey + 2), StringKey AS x FROM BQT1.SmallA UNION SELECT IntKey, StringKey FROM BQT1.SmallB"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -3998,7 +3881,7 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT x FROM (SELECT IntKey+2, StringKey AS x FROM BQT1.SmallA UNION ALL SELECT IntKey, StringKey FROM BQT1.SmallB) AS g", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT x FROM (SELECT IntKey+2, StringKey AS x FROM BQT1.SmallA UNION ALL SELECT IntKey, StringKey FROM BQT1.SmallB) AS g", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT StringKey AS x FROM BQT1.SmallA UNION ALL SELECT StringKey FROM BQT1.SmallB"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -4017,7 +3900,7 @@
         caps.setFunctionSupport("convert", true); //$NON-NLS-1$
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT * FROM vm1.g4", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT * FROM vm1.g4", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT e1 FROM pm1.g1 UNION ALL SELECT convert(e2, string) FROM pm1.g2"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -4034,7 +3917,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SET_ORDER_BY, true);
         capFinder.addCapabilities("pm3", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT e2 FROM vm1.g17", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT e2 FROM vm1.g17", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
                                       null, capFinder, 
                                       new String[] {"SELECT pm3.g1.e2 FROM pm3.g1 UNION ALL SELECT pm3.g2.e2 FROM pm3.g2"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -4052,7 +3935,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT intkey, 5 FROM BQT1.SmallA UNION ALL SELECT intnum, 10 FROM bqt1.smalla) AS x",  //$NON-NLS-1$
-                                      FakeMetadataFactory.exampleBQTCached(),  
+                                      RealMetadataFactory.exampleBQTCached(),  
                                       null, capFinder, 
                                       new String[] {"SELECT intkey FROM BQT1.SmallA", "SELECT IntNum FROM bqt1.smalla"},  //$NON-NLS-1$ //$NON-NLS-2$
                                       SHOULD_SUCCEED);   
@@ -4087,7 +3970,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan("SELECT * FROM (SELECT intkey, 5 FROM BQT1.SmallA UNION ALL SELECT intnum, 10 FROM bqt1.smalla) AS x",  //$NON-NLS-1$
-                                      FakeMetadataFactory.exampleBQTCached(),  
+                                      RealMetadataFactory.exampleBQTCached(),  
                                       null, capFinder, 
                                       new String[] {"SELECT intkey, 5 FROM BQT1.SmallA UNION ALL SELECT IntNum, 10 FROM bqt1.smalla"},  //$NON-NLS-1$ 
                                       SHOULD_SUCCEED);   
@@ -4104,7 +3987,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1",  //$NON-NLS-1$
@@ -4123,7 +4006,7 @@
         caps.setCapabilitySupport(Capability.QUERY_CASE, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT CASE e1 WHEN 'a' THEN 10 ELSE (e2+0) END FROM pm1.g1",  //$NON-NLS-1$
@@ -4158,7 +4041,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE 0 END FROM pm1.g1",  //$NON-NLS-1$
@@ -4177,7 +4060,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT CASE WHEN e1 = 'a' THEN 10 ELSE (e2+0) END FROM pm1.g1",  //$NON-NLS-1$
@@ -4214,9 +4097,7 @@
         caps.setFunctionSupport("xyz", true);         //$NON-NLS-1$
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new FakeFunctionMetadataSource()));
-        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
-        
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT e1 FROM pm1.g1 WHERE xyz() > 0",  //$NON-NLS-1$
@@ -4230,7 +4111,7 @@
 
     @Test public void testNoSourceQuery() {
         ProcessorPlan plan = helpPlan("SELECT * FROM (select parsetimestamp(x,'yyyy-MM-dd') as c1 from (select '2004-10-20' as x) as y) as z " +//$NON-NLS-1$ 
-                                      "WHERE c1= '2004-10-20 00:00:00.0'", FakeMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
+                                      "WHERE c1= '2004-10-20 00:00:00.0'", RealMetadataFactory.exampleBQTCached(), //$NON-NLS-1$
             new String[] {  }); 
 
         checkNodeTypes(plan, new int[] {
@@ -4263,9 +4144,9 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.smallb", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQT();
+        RealMetadataFactory.setCardinality("bqt1.smallb", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
+        RealMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
          
         ProcessorPlan plan = helpPlan(
             "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA, BQT1.SmallB WHERE (BQT1.SmallA.IntKey = lookup('BQT1.SmallB', 'IntKey', 'StringKey', BQT1.SmallB.StringKey)) AND (BQT1.SmallA.IntKey = 1)",  //$NON-NLS-1$
@@ -4305,9 +4186,9 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.mediumb", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQT();
+        RealMetadataFactory.setCardinality("bqt1.mediumb", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
+        RealMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
          
         ProcessorPlan plan = helpPlan(
             "SELECT BQT1.SmallA.IntKey, BQT1.MediumB.IntKey FROM BQT1.SmallA LEFT OUTER JOIN BQT1.MediumB ON BQT1.SmallA.IntKey = lookup('BQT1.MediumB', 'IntKey', 'StringKey', BQT1.MediumB.StringKey)",  //$NON-NLS-1$
@@ -4347,9 +4228,9 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000));
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQT();
-        FakeMetadataFactory.setCardinality("bqt1.mediumb", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
-        FakeMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQT();
+        RealMetadataFactory.setCardinality("bqt1.mediumb", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$
+        RealMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$
          
         ProcessorPlan plan = helpPlan(
             "SELECT BQT1.SmallA.IntKey, BQT1.MediumB.IntKey FROM BQT1.MediumB RIGHT OUTER JOIN BQT1.SmallA ON BQT1.SmallA.IntKey = lookup('BQT1.MediumB', 'IntKey', 'StringKey',BQT1.MediumB.StringKey)",  //$NON-NLS-1$          
@@ -4401,7 +4282,7 @@
             "(P.longnum > (SELECT AVG(LongNum) FROM bqt1.smallb WHERE bqt1.smallb.datevalue = O.datevalue))"; //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT g_1.longnum, g_2.datevalue, g_0.IntKEy, g_1.IntKEy, g_2.IntKey FROM bqt1.smalla AS g_0, bqt1.smallb AS g_1, bqt1.mediuma AS g_2 WHERE (g_0.StringKey = g_1.StringKey) AND (g_2.IntKey = g_0.IntKey) AND (g_0.IntNum > (SELECT SUM(g_3.IntNum) FROM bqt1.smalla AS g_3))"}, //$NON-NLS-1$ 
                                       ComparisonMode.EXACT_COMMAND_STRING );
@@ -4440,7 +4321,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT 1 AS c_0 FROM BQT1.SmallA AS a UNION ALL SELECT 1 AS c_0 FROM bqt1.smallb AS b"}, //$NON-NLS-1$ 
                                       SHOULD_SUCCEED );
@@ -4479,7 +4360,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT a.IntKey AS z FROM BQT1.SmallA AS a UNION ALL SELECT 0 FROM bqt1.smallb AS b"}, //$NON-NLS-1$ 
                                       SHOULD_SUCCEED );
@@ -4518,7 +4399,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT '' AS Code, IntKey AS ID FROM BQT1.SmallA UNION ALL SELECT stringkey, intkey FROM bqt1.smallb AS b"}, //$NON-NLS-1$ 
                                       SHOULD_SUCCEED );
@@ -4556,7 +4437,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT 1, 'ab' AS X FROM BQT1.SmallA WHERE intkey = 0 UNION ALL SELECT 2, 'Hello2' FROM BQT1.SmallA WHERE IntKey = 1 ORDER BY X DESC"}, //$NON-NLS-1$ 
                                       SHOULD_SUCCEED );
@@ -4573,7 +4454,7 @@
         String sql = "UPDATE BQT1.SmallA SET IntKey = IntKey + 1"; //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"UPDATE BQT1.SmallA SET IntKey = (IntKey + 1)"}, //$NON-NLS-1$ 
                                       ComparisonMode.EXACT_COMMAND_STRING );
@@ -4595,7 +4476,7 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);        
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         String sql = "SELECT t.intkey FROM (SELECT a.IntKey FROM bqt1.smalla a left outer join bqt1.smallb b on a.intkey=b.intkey, bqt1.smalla x) as t full outer JOIN bqt1.smallb c on t.intkey = c.intkey"; //$NON-NLS-1$
 
@@ -4625,7 +4506,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT g_2.intkey AS c_0, 'a' AS c_1 FROM BQT1.SmallA AS g_2 UNION ALL SELECT g_1.IntKey AS c_0, 'b' AS c_1 FROM BQT1.SmallA AS g_1 UNION ALL SELECT g_0.IntKey AS c_0, 'c' AS c_1 FROM BQT1.SmallA AS g_0"}, //$NON-NLS-1$ 
                                       ComparisonMode.EXACT_COMMAND_STRING );
@@ -4645,7 +4526,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         RelationalPlan plan = (RelationalPlan)helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT bqt1.smalla.datevalue, bqt1.smalla.intkey, bqt1.smalla.stringkey, bqt1.smalla.objectvalue FROM bqt1.smalla WHERE (bqt1.smalla.intkey = 46) AND (bqt1.smalla.stringkey = '46')"}, //$NON-NLS-1$
                                       SHOULD_SUCCEED );
@@ -4708,7 +4589,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT (SUM(IntKey) + 1) FROM BQT1.SmallA GROUP BY IntKey"}, //$NON-NLS-1$ 
                                       SHOULD_SUCCEED );
@@ -4725,7 +4606,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT IntKey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
                                       SHOULD_SUCCEED );
@@ -4757,7 +4638,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
-                                      FakeMetadataFactory.exampleBQTCached(),
+                                      RealMetadataFactory.exampleBQTCached(),
                                       null, capFinder,
                                       new String[] {"SELECT intkey FROM BQT1.SmallA"}, //$NON-NLS-1$ 
                                       SHOULD_SUCCEED );
@@ -4794,7 +4675,7 @@
         
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(sql,           
                                       metadata,
@@ -4837,7 +4718,7 @@
         
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(sql,           
                                       metadata,
@@ -5120,7 +5001,7 @@
         
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(sql,           
                                       metadata,
@@ -5171,7 +5052,7 @@
         
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(sql,           
                                       metadata,
@@ -5231,7 +5112,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(sql,           
                                       metadata,
@@ -5344,7 +5225,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(sql,           
                                       metadata,
@@ -5404,14 +5285,14 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);  
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         String sql = "SELECT intkey, x FROM (select intkey, intkey x from bqt1.smalla) z ORDER BY x, intkey"; //$NON-NLS-1$
 
         ProcessorPlan plan = helpPlan(sql,  
                                       metadata,
                                       null, capFinder,
-                                      new String[] {"SELECT g_0.intkey, g_0.intkey FROM bqt1.smalla AS g_0 ORDER BY g_0.intkey"},  //$NON-NLS-1$
+                                      new String[] {"SELECT g_0.intkey FROM bqt1.smalla AS g_0 ORDER BY g_0.intkey"},  //$NON-NLS-1$
                                       ComparisonMode.EXACT_COMMAND_STRING );
 
         checkNodeTypes(plan, FULL_PUSHDOWN);
@@ -5435,7 +5316,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         String sql = "SELECT vqt.smallb.a12345 FROM vqt.smallb ORDER BY vqt.smallb.a12345"; //$NON-NLS-1$
 
@@ -5464,7 +5345,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         String sql = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) as EXPR, bqt1.smalla.stringKey as EXPR_1 FROM bqt1.smalla  ORDER BY EXPR, EXPR_1"; //$NON-NLS-1$
 
@@ -5493,7 +5374,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         String sql = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum), bqt1.smalla.stringKey as EXPR_1 FROM bqt1.smalla ORDER BY EXPR_1"; //$NON-NLS-1$
 
@@ -5523,7 +5404,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         String sql = "SELECT b1.intkey from (bqt1.SmallA a1 cross join bqt1.smalla a2 cross join bqt1.mediuma b1) " +    //$NON-NLS-1$ 
             " left outer join bqt1.mediumb b2 on b1.intkey = b2.intkey"; //$NON-NLS-1$         
@@ -5552,7 +5433,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         String sql = "SELECT bqt1.SmallA.intkey from (bqt1.SmallA inner join (" //$NON-NLS-1$         
             + "SELECT BAD.intkey from bqt1.SmallB as BAD left outer join bqt1.MediumB on BAD.intkey = bqt1.MediumB.intkey) as X on bqt1.SmallA.intkey = X.intkey) inner join bqt1.MediumA on X.intkey = bqt1.MediumA.intkey"; //$NON-NLS-1$
@@ -5566,7 +5447,7 @@
     
     @Test public void testCase3367() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = example1();
+        QueryMetadataInterface metadata = example1();
 
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_IN, true);
@@ -5588,7 +5469,7 @@
      */
     @Test public void testCase3778() throws Exception {
     	
-    	FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
@@ -5618,7 +5499,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$ 
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$ 
          
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
          
         String sql = "select bqt1.smalla.intkey from bqt1.smalla, bqt2.smalla, bqt2.smallb where bqt1.smalla.intkey = bqt2.smalla.intkey and bqt1.smalla.intkey = bqt2.smallb.intkey and bqt2.smalla.stringkey = bqt2.smallb.stringkey"; //$NON-NLS-1$ 
          
@@ -5647,7 +5528,7 @@
         String sql = "select pm1.g1.e1, pm1.g1.e2 from pm1.g1 where e1 = convert((exec pm1.sq11(e2, 2)), integer)"; //$NON-NLS-1$ 
          
         helpPlan(sql, 
-                 FakeMetadataFactory.example1Cached(), 
+                 RealMetadataFactory.example1Cached(), 
                  null, 
                  capFinder, 
                  new String[] { 
@@ -5666,14 +5547,14 @@
         caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true); 
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$ 
          
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached(); 
          
         String sql = "SELECT * from (select '1' as test, intkey from bqt2.smalla) foo, (select '2' as test, intkey from bqt2.smalla) foo2 where foo.intkey = foo2.intkey"; //$NON-NLS-1$ 
          
         helpPlan(sql,  
                                       metadata, 
                                       null, capFinder, 
-                                      new String[] {"SELECT '1', g_0.intkey, '2', g_1.IntKey FROM bqt2.smalla AS g_0, bqt2.smalla AS g_1 WHERE g_0.intkey = g_1.IntKey"},  //$NON-NLS-1$ 
+                                      new String[] {"SELECT g_0.intkey, g_1.IntKey FROM bqt2.smalla AS g_0, bqt2.smalla AS g_1 WHERE g_0.intkey = g_1.IntKey"},  //$NON-NLS-1$ 
                                       ComparisonMode.EXACT_COMMAND_STRING ); 
              
     } 
@@ -5688,7 +5569,7 @@
         String sql = "select convert(e2+1,string) from pm1.g1 union all select e1 from pm1.g2";//$NON-NLS-1$
         String[] expectedSql = new String[] {"SELECT e2 FROM pm1.g1", "SELECT e1 FROM pm1.g2"};//$NON-NLS-1$ //$NON-NLS-2$
         
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                       null, capFinder, expectedSql, SHOULD_SUCCEED);  
 
         checkNodeTypes(plan, new int[] {
@@ -5711,7 +5592,7 @@
     }
     
     @Test public void testCase3966() {
-        ProcessorPlan plan = helpPlan("insert into vm1.g37 (e1, e2, e3, e4) values('test', 1, convert('true', boolean) , convert('12', double) )", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("insert into vm1.g37 (e1, e2, e3, e4) values('test', 1, convert('true', boolean) , convert('12', double) )", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
                                       new String[] {} ); 
 
         checkNodeTypes(plan, new int[] {
@@ -5739,7 +5620,7 @@
         
         String sql = "SELECT env('soap_host') AS HOST, intkey from bqt2.smalla"; //$NON-NLS-1$
         
-        helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, new DefaultCapabilitiesFinder(),
+        helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, new DefaultCapabilitiesFinder(),
                                       new String[] {"SELECT bqt2.smalla.intkey FROM bqt2.smalla"}, ComparisonMode.EXACT_COMMAND_STRING);  //$NON-NLS-1$      
     }
         
@@ -5750,7 +5631,7 @@
     @Test public void testCase4265() throws Exception {
         String sql = "SELECT X.intkey, Y.intkey FROM BQT1.SmallA X, BQT1.SmallA Y WHERE X.IntKey <> Y.IntKey and Y.IntKey = 1"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
                                       new String[] { 
                                           "SELECT g_0.intkey FROM BQT1.SmallA AS g_0 WHERE g_0.IntKey <> 1",  //$NON-NLS-1$ 
                                           "SELECT g_0.intkey FROM BQT1.SmallA AS g_0 WHERE g_0.IntKey = 1" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ 
@@ -5781,7 +5662,7 @@
     @Test public void testCase4265ControlTest() throws Exception {
         String sql = "SELECT X.intkey, Y.intkey FROM BQT1.SmallA X, BQT1.SmallA Y WHERE X.IntKey = Y.IntKey and Y.IntKey = 1"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
                                       new String[] { 
                                           "SELECT g_0.intkey FROM BQT1.SmallA AS g_0 WHERE g_0.IntKey = 1" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ 
 
@@ -5810,7 +5691,7 @@
     @Test public void testExistsCriteriaInSelect() {
         String sql = "select intkey, case when exists (select stringkey from bqt1.smallb) then 'nuge' end as a from vqt.smalla"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
                                       new String[] { 
                                           "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$ 
 
@@ -5839,7 +5720,7 @@
     @Test public void testScalarSubQueryInSelect() {
         String sql = "select intkey, case when (select stringkey from bqt1.smallb) is not null then 'nuge' end as a from vqt.smalla"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
                                       new String[] { 
                                           "SELECT BQT1.SmallA.IntKey FROM BQT1.SmallA" }); //$NON-NLS-1$ 
 
@@ -5864,7 +5745,7 @@
     
     @Test public void testCase4263() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = example1();
+        QueryMetadataInterface metadata = example1();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
@@ -5883,7 +5764,7 @@
     
     @Test public void testCase4263b() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = example1();
+        QueryMetadataInterface metadata = example1();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
@@ -5917,7 +5798,7 @@
     
     @Test public void testCase4279() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = example1();
+        QueryMetadataInterface metadata = example1();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
@@ -5968,7 +5849,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,         
                                       metadata,
@@ -5999,7 +5880,7 @@
         caps.setFunctionSupport("+", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,        
                                       metadata,
@@ -6020,16 +5901,12 @@
         helpTestCase2430and2507(sql, expected);
     }     
 
-    /*
-     * If expressionsymbol comparison would ignore expression names then this should just select a single column,
-     * but for now it will select 2.
-     */
     @Test public void testCase2430E() {
         String sql = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) as c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
                      "CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) AS EXPR FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890, EXPR "; //$NON-NLS-1$
 
-        String expected = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) AS c1234567890123456789012345678901234567890, CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) " + //$NON-NLS-1$
-                     "FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890"; //$NON-NLS-1$
+        String expected = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) AS c_0 " + //$NON-NLS-1$
+                     "FROM bqt1.smalla ORDER BY c_0"; //$NON-NLS-1$
         helpTestCase2430and2507(sql, expected);
     }     
     
@@ -6037,8 +5914,8 @@
         String sql = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) as c1234567890123456789012345678901234567890, " + //$NON-NLS-1$
                      "CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) AS EXPR FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890"; //$NON-NLS-1$
 
-        String expected = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) AS c1234567890123456789012345678901234567890, CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) " + //$NON-NLS-1$
-                     "FROM bqt1.smalla ORDER BY c1234567890123456789012345678901234567890"; //$NON-NLS-1$
+        String expected = "SELECT CONCAT(bqt1.smalla.stringKey, bqt1.smalla.stringNum) AS c_0 " + //$NON-NLS-1$
+                     "FROM bqt1.smalla ORDER BY c_0"; //$NON-NLS-1$
         helpTestCase2430and2507(sql, expected);
     }  
     
@@ -6058,7 +5935,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,         
                                       metadata,
@@ -6088,7 +5965,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT intkey FROM bqt1.smalla AS n WHERE intkey = (SELECT MAX(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = concat(n.stringkey, 'a') )", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT intkey FROM bqt1.smalla AS n WHERE intkey = (SELECT MAX(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = concat(n.stringkey, 'a') )", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT intkey, n.stringkey FROM bqt1.smalla AS n" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -6125,7 +6002,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(
             "SELECT A.IntKey, B.IntKey FROM BQT1.SmallA A LEFT OUTER JOIN BQT2.MediumB B ON A.IntKey = B.IntKey",  //$NON-NLS-1$
@@ -6156,7 +6033,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = helpPlan(
               "SELECT 'a' as A FROM BQT1.SmallA A UNION select 'b' as B from BQT1.MediumB B",  //$NON-NLS-1$
@@ -6174,7 +6051,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SELECT_DISTINCT, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         String sql = "select b from (select distinct booleanvalue b, intkey from bqt1.smalla) as x"; //$NON-NLS-1$
         
@@ -6210,7 +6087,7 @@
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         String sql = "SELECT a.intkey as stringkey, b.stringkey as key2 from bqt1.smalla a, bqt1.smallb b where a.intkey = b.intkey order by stringkey"; //$NON-NLS-1$ 
          
@@ -6228,7 +6105,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT intkey from bqt1.smalla WHERE stringkey = convert(objectvalue, string)",  //$NON-NLS-1$
@@ -6263,7 +6140,7 @@
         capFinder.addCapabilities("LOB", caps); //$NON-NLS-1$
 
         // Add join capability to pm1
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
          
         ProcessorPlan plan = helpPlan(
             "SELECT ClobValue from LOB.LobTbl WHERE convert(ClobValue, string) = ?",  //$NON-NLS-1$
@@ -6293,7 +6170,7 @@
     @Test public void testSelectIntoWithDistinct() throws Exception {
         String sql = "select distinct e1 into #temp from pm1.g1"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpPlan(sql, metadata, new String[] {"SELECT DISTINCT g_0.e1 FROM pm1.g1 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         //no txn required, since an interated insert is used
@@ -6307,7 +6184,7 @@
     @Test public void testInsertQueryExpression() throws Exception {
         String sql = "insert into pm1.g1 (e1) select e1 from pm1.g2"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpPlan(sql, metadata, new String[] {"SELECT g_0.e1 FROM pm1.g2 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         //requires a txn, since an non pushdown/iterated insert is used
@@ -6323,7 +6200,7 @@
     @Test public void testInsertQueryExpression1() throws Exception {
         String sql = "insert into pm1.g1 (e1) select e1 || 1 from pm1.g2"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpPlan(sql, metadata, new String[] {"SELECT g_0.e1 FROM pm1.g2 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         //requires a txn, since an non pushdown/iterated insert is used
@@ -6344,7 +6221,7 @@
         caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         String sql = "select pm1.g1.e1 from pm1.g1, (select * from pm1.g2) y where (pm1.g1.e1 = y.e1) and exists (select e2 from pm1.g2 where e1 = y.e1) and exists (select e3 from pm1.g2 where e1 = y.e1)"; //$NON-NLS-1$
         
@@ -6384,14 +6261,14 @@
         
         String sql = "select count(*) from (select intkey from bqt1.smalla union all select intkey from bqt1.smallb) as a"; //$NON-NLS-1$
         
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                       new String[] {"SELECT COUNT(*) FROM (SELECT 1 FROM bqt1.smalla UNION ALL SELECT 1 FROM bqt1.smallb) AS a"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ 
         
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
         
     @Test public void testCase6181() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
@@ -6409,7 +6286,7 @@
         String sql = "select a.e1 from (select 1 e1) a, (select e1, 1 as a, x from (select e1, CASE WHEN e1 = 'a' THEN e2 ELSE e3 END as x from pm1.g2) y group by e1, x) b where a.e1 = b.x"; //$NON-NLS-1$
         
         ProcessorPlan plan = helpPlan(sql, metadata, null, capFinder, 
-                                      new String[] {"SELECT v_1.c_0 FROM (SELECT v_0.c_1 AS c_0 FROM (SELECT g_0.e1 AS c_0, CASE WHEN g_0.e1 = 'a' THEN g_0.e2 ELSE g_0.e3 END AS c_1 FROM pm1.g2 AS g_0 WHERE CASE WHEN g_0.e1 = 'a' THEN g_0.e2 ELSE g_0.e3 END IN (<dependent values>)) AS v_0 GROUP BY v_0.c_0, v_0.c_1) AS v_1 ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ 
+                                      new String[] {"SELECT v_0.c_0 FROM (SELECT CASE WHEN g_0.e1 = 'a' THEN g_0.e2 ELSE g_0.e3 END AS c_0 FROM pm1.g2 AS g_0 GROUP BY g_0.e1, CASE WHEN g_0.e1 = 'a' THEN g_0.e2 ELSE g_0.e3 END) AS v_0 WHERE v_0.c_0 IN (<dependent values>) ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ 
         
         checkNodeTypes(plan, new int[] {
             0,      // Access
@@ -6432,7 +6309,7 @@
     @Test public void testCase6325() {
         String sql = "select e1 into #temp from pm4.g1 where e1='1'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpPlan(sql, metadata, new String[] {"SELECT e1 FROM pm4.g1 WHERE e1 = '1'"}); //$NON-NLS-1$
         
@@ -6450,7 +6327,7 @@
         
         String sql = "select * from (SELECT 1+ SUM(intnum) AS s FROM bqt1.smalla) a WHERE a.s>10"; //$NON-NLS-1$
        
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                       new String[] {"SELECT (1 + SUM(intnum)) FROM bqt1.smalla HAVING SUM(intnum) > 9"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ 
         
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -6464,7 +6341,7 @@
         
         String sql = "select e1 from pm1.g1 except select e1 from pm1.g2"; //$NON-NLS-1$
        
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT g_1.e1 AS c_0 FROM pm1.g1 AS g_1 EXCEPT SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ 
         
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -6480,7 +6357,7 @@
         // Create query 
         String sql = "select IntKey from bqt1.smalla where stringkey not like '2%'"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                       new String[] {"SELECT stringkey, IntKey FROM bqt1.smalla"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
         
         checkNodeTypes(plan, new int[] {
@@ -6504,7 +6381,7 @@
     @Test public void testCopyCriteriaWithIsNull() {
     	String sql = "select * from (select a.intnum, a.intkey y, b.intkey from bqt1.smalla a, bqt2.smalla b where a.intkey = b.intkey) x where intkey is null"; //$NON-NLS-1$
     	
-    	helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), new String[] {});
+    	helpPlan(sql, RealMetadataFactory.exampleBQTCached(), new String[] {});
     }
     
     /**
@@ -6517,7 +6394,7 @@
      * SELECT * FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2
      */
     @Test public void testBetween() { 
-        helpPlan("select * from pm1.g1 where e2 between 1 and 2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        helpPlan("select * from pm1.g1 where e2 between 1 and 2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
     			new String[] { "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1 WHERE (e2 >= 1) AND (e2 <= 2)"} ); //$NON-NLS-1$
     }
 
@@ -6538,7 +6415,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         helpPlan("select case when e2 between 3 and 5 then e2 else -1 end from pm1.g1", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), null, capFinder, 
+        		RealMetadataFactory.example1Cached(), null, capFinder, 
     			new String[] { "SELECT CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END FROM pm1.g1"},  //$NON-NLS-1$
     			TestOptimizer.SHOULD_SUCCEED);
     }
@@ -6562,7 +6439,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         helpPlan("select sum(case when e2 between 3 and 5 then e2 else -1 end) from pm1.g1", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), null, capFinder, 
+        		RealMetadataFactory.example1Cached(), null, capFinder, 
     			new String[] { "SELECT SUM(CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END) FROM pm1.g1"},  //$NON-NLS-1$
     			TestOptimizer.SHOULD_SUCCEED);
     }
@@ -6587,7 +6464,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         helpPlan("select sum(case when e2 between 3 and 5 then e2 else -1 end) from pm1.g1 group by e1", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), null, capFinder, 
+        		RealMetadataFactory.example1Cached(), null, capFinder, 
     			new String[] { "SELECT SUM(CASE WHEN (e2 >= 3) AND (e2 <= 5) THEN e2 ELSE -1 END) FROM pm1.g1 GROUP BY e1"},  //$NON-NLS-1$
     			TestOptimizer.SHOULD_SUCCEED);
     }
@@ -6612,7 +6489,7 @@
     	"	) AS A" + //$NON-NLS-1$
     	") AS A"; //$NON-NLS-1$
 
-        helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {});
+        helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {});
     }
          
     /**
@@ -6637,7 +6514,7 @@
     	"	) AS A" + //$NON-NLS-1$
     	") AS A"; //$NON-NLS-1$
 
-    	helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {});
+    	helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {});
     }
 
     /**
@@ -6657,7 +6534,7 @@
     	"   SELECT e2 AS e2 FROM pm1.g1 AS A" + //$NON-NLS-1$
     	") AS A"; //$NON-NLS-1$
 
-        helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {"SELECT e2 FROM pm1.g1 AS A"}); //$NON-NLS-1$
+        helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT e2 FROM pm1.g1 AS A"}); //$NON-NLS-1$
     }
          
     /**
@@ -6679,7 +6556,7 @@
     	"   SELECT CONVERT(e2, long) AS e2 FROM pm1.g1 AS A" + //$NON-NLS-1$
     	") AS A"; //$NON-NLS-1$
 
-    	FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         helpPlan(sql, metadata, new String[] {"SELECT e2 FROM pm1.g1 AS A"}); //$NON-NLS-1$
 
@@ -6706,10 +6583,57 @@
     }
     
     @Test public void testUpdatePushdownFails() { 
-        helpPlan("update pm1.g1 set e1 = 1 where exists (select 1 from pm1.g2)", FakeMetadataFactory.example1Cached(), null, //$NON-NLS-1$
+        helpPlan("update pm1.g1 set e1 = 1 where exists (select 1 from pm1.g2)", RealMetadataFactory.example1Cached(), null, //$NON-NLS-1$
 			null, null, false); //$NON-NLS-1$
     }
     
+    @Test public void testUnnamedAggInView() throws Exception {
+    	MetadataStore metadataStore = new MetadataStore();
+    	
+        Schema bqt1 = RealMetadataFactory.createPhysicalModel("BQT1", metadataStore); //$NON-NLS-1$
+        Schema vqt = RealMetadataFactory.createVirtualModel("VQT", metadataStore); //$NON-NLS-1$
+        
+        Table bqt1SmallA = RealMetadataFactory.createPhysicalGroup("SmallA", bqt1); //$NON-NLS-1$
+        RealMetadataFactory.createElement("col", bqt1SmallA, DataTypeManager.DefaultDataTypes.STRING);
+        
+        Table agg3 = RealMetadataFactory.createVirtualGroup("Agg3", vqt, new QueryNode("select count(*) from smalla"));
+        RealMetadataFactory.createElement("count", agg3, DataTypeManager.DefaultDataTypes.INTEGER);
+        
+        TransformationMetadata metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "x");
+        BasicSourceCapabilities bac = getTypicalCapabilities();
+        bac.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+        bac.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
+        bac.setCapabilitySupport(Capability.QUERY_GROUP_BY, true);
+        helpPlan("select count(*) from agg3", metadata, new String[] {}, new DefaultCapabilitiesFinder(bac), ComparisonMode.EXACT_COMMAND_STRING);
+    }
+    
+    @Test public void testMergeGroupBy1() throws Exception {
+    	BasicSourceCapabilities caps = new BasicSourceCapabilities();
+    	caps.setCapabilitySupport(Capability.ROW_LIMIT, true);
+    	caps.setFunctionSupport("+", true); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT a, b FROM (select 1 as a, 2 as b from pm1.g1) as x group by a, b", //$NON-NLS-1$
+                                      RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
+                                      new String[] {
+                                          "SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 1"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+    
+        checkNodeTypes(plan, new int[] {
+                1,      // Access
+                0,      // DependentAccess
+                0,      // DependentSelect
+                0,      // DependentProject
+                0,      // DupRemove
+                0,      // Grouping
+                0,      // NestedLoopJoinStrategy
+                0,      // MergeJoinStrategy
+                0,      // Null
+                0,      // PlanExecution
+                1,      // Project
+                0,      // Select
+                0,      // Sort
+                0       // UnionAll
+            });                                    
+    }
+    
 	public static final boolean DEBUG = false;
 
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java:3149-3217,3220-3275
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestOptimizer.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,34 +25,34 @@
 import org.junit.Test;
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestOptionalJoins {
     
     @Test public void testOptionalJoinNode1() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode1WithPredicate() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode1WithJoinCriteria() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM (pm1.g1 CROSS JOIN /* optional */ pm1.g2) INNER JOIN pm1.g3 ON pm1.g1.e1 = pm1.g3.e1 AND pm1.g2.e1 = pm1.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM (pm1.g1 CROSS JOIN /* optional */ pm1.g2) INNER JOIN pm1.g3 ON pm1.g1.e1 = pm1.g3.e1 AND pm1.g2.e1 = pm1.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_1.e1 FROM pm1.g1 AS g_0, pm1.g3 AS g_1 WHERE g_0.e1 = g_1.e1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNodeNonAnsiWithHaving() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e1 FROM (SELECT pm1.g1.e1, max(pm1.g2.e2) FROM pm1.g1, /* optional */ pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 GROUP BY pm1.g1.e1) x", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e1 FROM (SELECT pm1.g1.e1, max(pm1.g2.e2) FROM pm1.g1, /* optional */ pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1 GROUP BY pm1.g1.e1) x", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -74,7 +74,7 @@
     }
     
     @Test public void testOptionalJoinNode1_1() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1,pm2.g2.e1  FROM pm1.g1, /* optional */ pm2.g2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1,pm2.g2.e1  FROM pm1.g1, /* optional */ pm2.g2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm2.g2.e1 FROM pm2.g2"} ); //$NON-NLS-1$//$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -96,21 +96,21 @@
     }
     
     @Test public void testOptionalJoinNode2() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2, pm1.g3", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1, /* optional */ pm1.g2, pm1.g3", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g3 AS g_1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode3() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode3_1() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1, pm2.g2.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm2.g2 on pm1.g1.e1 = pm2.g2.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1, pm2.g2.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm2.g2 on pm1.g1.e1 = pm2.g2.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 AS c_0 FROM pm2.g2 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0"} ); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -132,70 +132,70 @@
     }
     
     @Test public void testOptionalJoinNode4() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM (pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN /* optional */ pm1.g3 on pm1.g1.e1 = pm1.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM (pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN /* optional */ pm1.g3 on pm1.g1.e1 = pm1.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode5() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM (pm1.g1 LEFT OUTER JOIN pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN /* optional */ pm1.g3 on pm1.g1.e1 = pm1.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM (pm1.g1 LEFT OUTER JOIN pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN /* optional */ pm1.g3 on pm1.g1.e1 = pm1.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 FROM pm1.g1 AS g_0 LEFT OUTER JOIN pm1.g2 AS g_1 ON g_0.e1 = g_1.e1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode6() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM (pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN pm1.g3 on pm1.g1.e1 = pm1.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM (pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN pm1.g3 on pm1.g1.e1 = pm1.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 FROM pm1.g1 AS g_0 LEFT OUTER JOIN pm1.g3 AS g_1 ON g_0.e1 = g_1.e1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode7() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM /* optional */ (pm1.g1 LEFT OUTER JOIN pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN pm1.g3 on pm1.g1.e1 = pm1.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM /* optional */ (pm1.g1 LEFT OUTER JOIN pm1.g2 on pm1.g1.e1 = pm1.g2.e1) LEFT OUTER JOIN pm1.g3 on pm1.g1.e1 = pm1.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g3.e1 FROM pm1.g3"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode8() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ (select * from pm1.g2) as X on pm1.g1.e1 = x.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ (select * from pm1.g2) as X on pm1.g1.e1 = x.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode9() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g2.e1 FROM pm1.g2, /* optional */ vm1.g1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g2.e1 FROM pm1.g2, /* optional */ vm1.g1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g2.e1 FROM pm1.g2"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode10() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM /* optional */ vm1.g1, pm1.g1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM /* optional */ vm1.g1, pm1.g1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode11() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ vm1.g2 on pm1.g1.e1 = vm1.g2.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g1.e1 FROM pm1.g1 LEFT OUTER JOIN /* optional */ vm1.g2 on pm1.g1.e1 = vm1.g2.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode12() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM /* optional */ (pm1.g1 LEFT OUTER JOIN vm1.g1 on pm1.g1.e1 = vm1.g1.e1) LEFT OUTER JOIN pm1.g3 on pm1.g1.e1 = pm1.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM /* optional */ (pm1.g1 LEFT OUTER JOIN vm1.g1 on pm1.g1.e1 = vm1.g1.e1) LEFT OUTER JOIN pm1.g3 on pm1.g1.e1 = pm1.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g3.e1 FROM pm1.g3"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode13() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT count(pm1.g1.e1) FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT count(pm1.g1.e1) FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -220,7 +220,7 @@
      * The distinct prevents the removal of the optional join 
      */
     @Test public void testOptionalJoinNode14() throws Exception { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT ve1 FROM vm1.g4", FakeMetadataFactory.example4(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT ve1 FROM vm1.g4", RealMetadataFactory.example4(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0", "SELECT DISTINCT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 ORDER BY c_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -242,14 +242,14 @@
     }
     
     @Test public void testOptionalJoinNode15() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x.e1 FROM (select vm1.g1.e1, vm1.g2.e2 from vm1.g1 LEFT OUTER JOIN /* optional */vm1.g2 on vm1.g1.e2 = vm1.g2.e2) AS x", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x.e1 FROM (select vm1.g1.e1, vm1.g2.e2 from vm1.g1 LEFT OUTER JOIN /* optional */vm1.g2 on vm1.g1.e2 = vm1.g2.e2) AS x", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g1.e1 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNode16() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT length(z) FROM /* optional */ pm1.g1, (select distinct e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY y, z) AS x", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT length(z) FROM /* optional */ pm1.g1, (select distinct e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY y, z) AS x", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT e2, e3 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -271,7 +271,7 @@
     }
     
     @Test public void testOptionalJoinNode17() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT length(z) FROM /* optional */ pm1.g1 inner join (select e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY z) AS x on pm1.g1.e2=x.y", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT length(z) FROM /* optional */ pm1.g1 inner join (select e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY z) AS x on pm1.g1.e2=x.y", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT e3 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -293,14 +293,14 @@
     }
     
     @Test public void testOptionalJoinWithIntersection() throws Exception { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM pm1.g3 inner join (select pm1.g1.e2 as y from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1) AS x on pm1.g3.e2=x.y", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM pm1.g3 inner join (select pm1.g1.e2 as y from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1) AS x on pm1.g3.e2=x.y", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 FROM pm1.g3 AS g_0, pm1.g1 AS g_1, pm1.g2 AS g_2 WHERE (g_1.e1 = g_2.e1) AND (g_0.e2 = g_1.e2)"}, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ 
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinWithNestedOrderBy() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM pm1.g3 inner join (select pm1.g2.e1, pm1.g1.e2 as y from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1 order by pm1.g2.e1 limit 10000) AS x on pm1.g3.e2=x.y", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM pm1.g3 inner join (select pm1.g2.e1, pm1.g1.e2 as y from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1 order by pm1.g2.e1 limit 10000) AS x on pm1.g3.e2=x.y", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e2 AS c_0, g_0.e1 AS c_1 FROM pm1.g3 AS g_0 ORDER BY c_0", "SELECT g_0.e2 AS c_0 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE g_0.e1 = g_1.e1 ORDER BY g_1.e1"} ); //$NON-NLS-1$ //$NON-NLS-2$ 
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -325,7 +325,7 @@
      * Grouping will prevent the removal from happening 
      */
     @Test public void testOptionalJoinWithGroupingOverAllColumns() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM pm1.g3, (select max(pm1.g1.e4) y from /* optional */ pm1.g1, pm1.g2 where pm1.g1.e1 = pm1.g2.e1) AS x where pm1.g3.e2=x.y", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT pm1.g3.e1 FROM pm1.g3, (select max(pm1.g1.e4) y from /* optional */ pm1.g1, pm1.g2 where pm1.g1.e1 = pm1.g2.e1) AS x where pm1.g3.e2=x.y", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e2, g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e4 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE g_0.e1 = g_1.e1"} ); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -347,10 +347,10 @@
     }
     
     /**
-     * Union should prevent the removal from happening 
+     * Union all should not prevent the removal from happening 
      */
     @Test public void testOptionalJoinWithUnion() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g2.e4 from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1 union all select convert(pm1.g2.e2, double) from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g2.e4 from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1 union all select convert(pm1.g2.e2, double) from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT pm1.g2.e4 FROM pm1.g2", "SELECT pm1.g2.e2 FROM pm1.g2"} ); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -371,8 +371,33 @@
         });    
     }
     
+    /**
+     * The first branch should have the join removed, but not the second branch
+     */
+    @Test public void testOptionalJoinWithUnion1() { 
+        ProcessorPlan plan = TestOptimizer.helpPlan("select e4 from (select e4, e2 from (select pm1.g2.e4, pm1.g1.e2 from /* optional */ pm1.g1 inner join pm1.g2 on pm1.g1.e1 = pm1.g2.e1) as x union all select e4, e2 from (select convert(pm2.g1.e2, double) as e4, pm2.g2.e2 from /* optional */ pm2.g1 inner join pm2.g2 on pm2.g1.e1 = pm2.g2.e1) as x) as y", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
+            new String[] {"SELECT pm1.g2.e4 FROM pm1.g2", "SELECT g_0.e2 FROM pm2.g1 AS g_0, pm2.g2 AS g_1 WHERE g_0.e1 = g_1.e1"} ); //$NON-NLS-1$ //$NON-NLS-2$
+
+        TestOptimizer.checkNodeTypes(plan, new int[] {
+            2,      // Access
+            0,      // DependentAccess
+            0,      // DependentSelect
+            0,      // DependentProject
+            0,      // DupRemove
+            0,      // Grouping
+            0,      // Join
+            0,      // MergeJoin
+            0,      // Null
+            0,      // PlanExecution
+            1,      // Project
+            0,      // Select
+            0,      // Sort
+            1       // UnionAll
+        });    
+    }
+    
     @Test public void testOptionalJoinWithCompoundCriteria() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT length(z) FROM /* optional */ pm1.g1 inner join (select e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY z) AS x on pm1.g1.e2=x.y and concat(x.y, x.z) = '1'", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT length(z) FROM /* optional */ pm1.g1 inner join (select e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY z) AS x on pm1.g1.e2=x.y and concat(x.y, x.z) = '1'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT e3 FROM pm1.g1"} ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -394,7 +419,7 @@
     }
     
     @Test public void testOptionalJoinWithDupRemoval() { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT a.e1 from (SELECT distinct pm1.g1.e1, x.y FROM pm1.g1, /* optional */ (select e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY z) AS x where pm1.g1.e2=x.y) as a", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT a.e1 from (SELECT distinct pm1.g1.e1, x.y FROM pm1.g1, /* optional */ (select e2 as y, e3 || 'x' as z from pm1.g1 ORDER BY z) AS x where pm1.g1.e2=x.y) as a", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT DISTINCT g_0.e2 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT DISTINCT g_0.e2 AS c_0, g_0.e1 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0"} ); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -422,7 +447,7 @@
     @Test public void testOptionalJoinWithoutHint_crossJoin() {
 		ProcessorPlan plan = TestOptimizer
 				.helpPlan(
-						"SELECT distinct pm1.g1.e1 from pm1.g1, pm1.g2", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+						"SELECT distinct pm1.g1.e1 from pm1.g1, pm1.g2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 						new String[] { "SELECT DISTINCT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1" }); //$NON-NLS-1$
 
 		TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
@@ -431,7 +456,7 @@
     @Test public void testOptionalJoinWithoutHint_outerJoin() {
 		ProcessorPlan plan = TestOptimizer
 				.helpPlan(
-						"SELECT distinct pm1.g1.e2 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1)", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+						"SELECT distinct pm1.g1.e2 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1)", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 						new String[] { "SELECT DISTINCT g_0.e2 FROM pm1.g1 AS g_0" }); //$NON-NLS-1$
 
 		TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
@@ -440,7 +465,7 @@
     @Test public void testOptionalJoinWithoutHint_aggregate() {
 		ProcessorPlan plan = TestOptimizer
 				.helpPlan(
-						"SELECT pm1.g1.e3, max(pm1.g1.e2) from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) group by pm1.g1.e3", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+						"SELECT pm1.g1.e3, max(pm1.g1.e2) from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) group by pm1.g1.e3", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 						new String[] { "SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0" }); //$NON-NLS-1$
 
 		TestOptimizer.checkNodeTypes(plan, new int[] { 
@@ -467,7 +492,7 @@
     @Test public void testOptionalJoinWithoutHint_aggregate1() {
 		ProcessorPlan plan = TestOptimizer
 				.helpPlan(
-						"SELECT pm1.g1.e3, avg(pm1.g1.e2) from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) group by pm1.g1.e3", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+						"SELECT pm1.g1.e3, avg(pm1.g1.e2) from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) group by pm1.g1.e3", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 						new String[] { "SELECT g_0.e3, g_0.e2 FROM pm1.g1 AS g_0 LEFT OUTER JOIN pm1.g2 AS g_1 ON g_0.e1 = g_1.e1" }); //$NON-NLS-1$
 
 		TestOptimizer.checkNodeTypes(plan, new int[] { 
@@ -491,7 +516,7 @@
     @Test public void testOptionalJoinWithoutHint_union() {
 		ProcessorPlan plan = TestOptimizer
 				.helpPlan(
-						"SELECT pm1.g1.e3 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) union select 1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+						"SELECT pm1.g1.e3 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) union select 1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 						new String[] { "SELECT g_0.e3 FROM pm1.g1 AS g_0" }); //$NON-NLS-1$
 
 		TestOptimizer.checkNodeTypes(plan, new int[] { 
@@ -515,7 +540,7 @@
     @Test public void testOptionalJoinWithOrderedLimit() {
 		ProcessorPlan plan = TestOptimizer
 				.helpPlan(
-						"select distinct * from (SELECT pm1.g1.e3 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) order by e3 limit 10) x", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+						"select distinct * from (SELECT pm1.g1.e3 from pm1.g1 left outer join pm1.g2 on (pm1.g1.e1 = pm1.g2.e1) order by e3 limit 10) x", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
 						new String[] { "SELECT g_0.e3 AS c_0 FROM pm1.g1 AS g_0 LEFT OUTER JOIN pm1.g2 AS g_1 ON g_0.e1 = g_1.e1 ORDER BY c_0" }); //$NON-NLS-1$
 
 		TestOptimizer.checkNodeTypes(plan, new int[] { 
@@ -537,28 +562,28 @@
 	}
     
     @Test public void testOptionalJoinNodeStar() throws Exception { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g2.e1 FROM /* optional */ ( /* optional */ pm1.g1 as g1 makedep INNER JOIN /* optional */ pm2.g2 ON g1.e1 = pm2.g2.e1) makedep INNER JOIN /* optional */ pm2.g3 ON g1.e1 = pm2.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g2.e1 FROM /* optional */ ( /* optional */ pm1.g1 as g1 makedep INNER JOIN /* optional */ pm2.g2 ON g1.e1 = pm2.g2.e1) makedep INNER JOIN /* optional */ pm2.g3 ON g1.e1 = pm2.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 FROM pm2.g2 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNodeStarTransitiveAnsi() throws Exception { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g3.e1 FROM ( /* optional */ pm1.g1 as g1 makedep INNER JOIN /* optional */ pm2.g2 ON g1.e1 = pm2.g2.e1) makedep INNER JOIN /* optional */ pm2.g3 ON g1.e1 = pm2.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g3.e1 FROM ( /* optional */ pm1.g1 as g1 makedep INNER JOIN /* optional */ pm2.g2 ON g1.e1 = pm2.g2.e1) makedep INNER JOIN /* optional */ pm2.g3 ON g1.e1 = pm2.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 FROM pm2.g3 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNodeStarNonAnsi() throws Exception { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g3.e1 FROM /* optional */ pm1.g1 as g1, /* optional */ pm2.g2, /* optional */ pm2.g3 WHERE g1.e1 = pm2.g2.e1 AND g1.e1 = pm2.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g3.e1 FROM /* optional */ pm1.g1 as g1, /* optional */ pm2.g2, /* optional */ pm2.g3 WHERE g1.e1 = pm2.g2.e1 AND g1.e1 = pm2.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_0.e1 FROM pm2.g3 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);    
     }
     
     @Test public void testOptionalJoinNodeBridgeNonAnsi() throws Exception { 
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g3.e1 FROM /* optional */ pm1.g1 as g1 makedep, pm2.g2, /* optional */ pm2.g3 WHERE g1.e1 = pm2.g2.e1 AND g1.e1 = pm2.g3.e1", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT g3.e1 FROM /* optional */ pm1.g1 as g1 makedep, pm2.g2, /* optional */ pm2.g3 WHERE g1.e1 = pm2.g2.e1 AND g1.e1 = pm2.g3.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] {"SELECT g_1.e1 AS c_0, g_0.e1 AS c_1 FROM pm2.g2 AS g_0, pm2.g3 AS g_1 WHERE g_1.e1 = g_0.e1 ORDER BY c_0, c_1", "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 WHERE (g_0.e1 IN (<dependent values>)) AND (g_0.e1 IN (<dependent values>)) ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$
 
 		TestOptimizer.checkNodeTypes(plan, new int[] { 


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java:3149-3217,3220-3275
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestOptionalJoins.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,19 +27,18 @@
 
 import org.junit.Test;
 import org.teiid.common.buffer.BufferManager;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.processor.relational.EnhancedSortMergeJoinStrategy;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 
-
+ at SuppressWarnings("nls")
 public class TestPartitionedJoinPlanning {
 	
-    @Test public void testUsePartitionedMergeJoin(){
+    @Test public void testUsePartitionedMergeJoin() throws Exception {
         // Create query
         String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$
 
@@ -51,11 +50,9 @@
         caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, 100);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE * 2);
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm1.g2", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE * 16);
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE * 2, metadata);
+        RealMetadataFactory.setCardinality("pm1.g2", BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE * 16, metadata);
     
         ProcessorPlan plan = helpPlan(sql, metadata,  
             null, capFinder,


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java
___________________________________________________________________
Modified: svn:mergeinfo
   - 
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestPartitionedJoinPlanning.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,15 +34,14 @@
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.processor.relational.RelationalPlan;
 import org.teiid.query.processor.relational.SortNode;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestRuleMergeVirtual {
     
     @Test public void testSimpleMergeGroupBy() {
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x FROM (SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
+                                      RealMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
                                       new String[] {
                                           "SELECT MAX(e2) AS x FROM pm1.g1 GROUP BY e1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -51,7 +50,7 @@
     
     @Test public void testSimpleMergeGroupBy1() {
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x FROM (SELECT distinct min(e1), max(e2) as x FROM pm1.g1 GROUP BY e1) AS z", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
+                                      RealMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
                                       new String[] {
                                           "SELECT v_0.c_1 FROM (SELECT DISTINCT MIN(g_0.e1) AS c_0, MAX(g_0.e2) AS c_1 FROM pm1.g1 AS g_0 GROUP BY g_0.e1) AS v_0"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -62,7 +61,7 @@
      * Same as above but all required symbols are selected
      */
     @Test public void testSimpleMergeGroupBy2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x, e1 FROM (SELECT distinct e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z", //$NON-NLS-1$
                                       metadata, null, TestAggregatePushdown.getAggregatesFinder(),
@@ -73,7 +72,7 @@
     }
     
     @Test public void testSimpleMergeGroupBy3() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT distinct x, e1 FROM (SELECT min(e1) as e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z", //$NON-NLS-1$
                                       metadata, null, TestAggregatePushdown.getAggregatesFinder(),
@@ -85,16 +84,16 @@
     
     @Test public void testSimpleMergeGroupBy4() {
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x, x FROM (SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
+                                      RealMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
                                       new String[] {
-                                          "SELECT v_0.c_0, v_0.c_0 FROM (SELECT MAX(g_0.e2) AS c_0 FROM pm1.g1 AS g_0 GROUP BY g_0.e1) AS v_0"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
+                                          "SELECT v_0.c_0 FROM (SELECT MAX(g_0.e2) AS c_0 FROM pm1.g1 AS g_0 GROUP BY g_0.e1) AS v_0"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);                                    
     }
     
     @Test public void testSimpleMergeGroupBy5() {
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x FROM (SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z where z.x = 1", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
+                                      RealMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
                                       new String[] {
                                           "SELECT MAX(e2) AS x FROM pm1.g1 GROUP BY e1 HAVING MAX(e2) = 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -103,7 +102,7 @@
     
     @Test public void testSimpleMergeGroupBy6() {
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x FROM (SELECT e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z where z.x = 1", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
+                                      RealMetadataFactory.example1Cached(), null, TestAggregatePushdown.getAggregatesFinder(),
                                       new String[] {
                                           "SELECT MAX(e2) AS x FROM pm1.g1 GROUP BY e1 HAVING MAX(e2) = 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -111,7 +110,7 @@
     }
     
     @Test public void testSimpleMergeGroupBy7() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
          
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT distinct x, e1 FROM (SELECT distinct min(e1) as e1, max(e2) as x FROM pm1.g1 GROUP BY e1) AS z", //$NON-NLS-1$
                                       metadata, null, TestAggregatePushdown.getAggregatesFinder(),
@@ -129,7 +128,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x FROM (select '1' as x, e2 from pm1.g1 union all select e1, 1 from pm1.g2) x", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {
                                           "SELECT '1' AS x FROM pm1.g1 UNION ALL SELECT e1 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -144,7 +143,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT distinct x FROM (select '1' as x, e2 from pm1.g1 union all select e1, 1 from pm1.g2) x", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {
                                           "SELECT '1' AS x FROM pm1.g1 UNION SELECT e1 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -162,7 +161,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT distinct x || 'b' FROM (select '1' as x, e2 from pm1.g1 union all select e1, 1 from pm1.g2) x", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {
                                           "SELECT '1' AS x FROM pm1.g1 UNION ALL SELECT e1 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -193,7 +192,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         TestOptimizer.helpPlan("select * from (SELECT x.x, x.e2 FROM (select '1' as x, pm1.g1.e2 from pm1.g1, pm1.g2 where pm1.g1.e1 = pm1.g2.e1 group by pm1.g1.e2, pm1.g1.e3 || '1') x union all select e1, 1 from pm1.g2) as y where x = '1'", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {
                                           "SELECT pm1.g2.e1 FROM pm1.g2", "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); 
     }
@@ -206,7 +205,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("select * from (SELECT distinct x FROM (select '1' as x, e2 from pm1.g1 union all select e1, 1 from pm1.g2) x) y, pm1.g2", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {
                                           "SELECT '1' AS x FROM pm1.g1 UNION SELECT e1 FROM pm1.g2", "SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
     
@@ -235,7 +234,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("select * from (select e1 from pm1.g1 limit 1) x", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {
                                           "SELECT e1 FROM pm1.g1 LIMIT 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -249,7 +248,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("select * from (select e1 from pm1.g1 limit 1) x order by e1", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {
                                         "SELECT e1 FROM pm1.g1 LIMIT 1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
     
@@ -283,7 +282,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("select '1' as x, e2 from pm1.g1 union all select e1, e2 from (select e1, 1 as e2 from pm1.g2 limit 1) as x order by x", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {"SELECT '1' AS c_0, pm1.g1.e2 AS c_1 FROM pm1.g1 UNION ALL (SELECT pm1.g2.e1 AS c_0, 1 AS c_1 FROM pm1.g2 LIMIT 1) ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);                                    
@@ -301,7 +300,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
          
         ProcessorPlan plan = TestOptimizer.helpPlan("select '1' as x, e2 from pm1.g1 union all (select e1, e2 from (select distinct e1, 1 as e2 from pm1.g2) as x order by e1 limit 1) order by x", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, capFinder,
+                                      RealMetadataFactory.example1Cached(), null, capFinder,
                                       new String[] {"SELECT '1' AS c_0, pm1.g1.e2 AS c_1 FROM pm1.g1 UNION ALL (SELECT DISTINCT pm1.g2.e1 AS c_0, 1 AS c_1 FROM pm1.g2 ORDER BY c_0 LIMIT 1) ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);                                    
@@ -330,7 +329,7 @@
         caps.setFunctionSupport("convert", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         // Plan query
         ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, 
@@ -348,7 +347,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e1 FROM pm1.g1 AS g_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  
         
         SortNode node = (SortNode)plan.getRootNode();
@@ -363,7 +362,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
         		new String[] {"SELECT g_0.e1 FROM pm1.g1 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0"}, capFinder, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  
         
         SortNode node = (SortNode)plan.getRootNode();
@@ -374,7 +373,7 @@
     	BasicSourceCapabilities caps = TestAggregatePushdown.getAggregateCapabilities();
     	caps.setFunctionSupport("+", true); //$NON-NLS-1$
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x FROM (SELECT min(y), max(x) as x FROM (select e1 x, e2 + 1 y from pm1.g1) a) AS b", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
+                                      RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
                                       new String[] {
                                           "SELECT MAX(g_0.e1) FROM pm1.g1 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     
@@ -385,7 +384,7 @@
     	BasicSourceCapabilities caps = TestAggregatePushdown.getAggregateCapabilities();
     	caps.setFunctionSupport("+", true); //$NON-NLS-1$
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT x FROM (select c.e1 as x from (select e1 from pm1.g1) as c, pm1.g2 as d) as a group by x", //$NON-NLS-1$
-                                      FakeMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
+                                      RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
                                       new String[] {
                                           "SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 GROUP BY g_0.e1"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java:3149-3171
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleMergeVirtual.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,7 +34,7 @@
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.processor.relational.RelationalPlan;
 import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 public class TestRuleRaiseNull {
     
@@ -67,8 +67,8 @@
 
         String sql = "select * from ( select intkey as cola, null as colb, intnum as colc from bqt1.smalla union all select null, intkey, intnum from bqt2.smalla) as X where X.cola = 1";  //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),
-                                      new String[] {"SELECT intkey, null, intnum FROM bqt1.smalla WHERE intkey = 1"} ); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),
+                                      new String[] {"SELECT intkey, intnum FROM bqt1.smalla WHERE intkey = 1"} ); //$NON-NLS-1$
         
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);          
         
@@ -77,7 +77,7 @@
     @Test public void testRaiseNullWithInnerJoin() {
         String sql = "select b.intkey from (select intkey from bqt1.smalla where 1 = 0) a inner join (select intkey from bqt1.smallb) b on (a.intkey = b.intkey)"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{});
         TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
     }
@@ -85,7 +85,7 @@
     @Test public void testRaiseNullWithFullOuterJoin() {
         String sql = "select b.intkey from (select intkey from bqt1.smalla) a full outer join (select intkey from bqt1.smallb where 1 = 0) b on (a.intkey = b.intkey)"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{"SELECT null FROM bqt1.smalla"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
@@ -93,7 +93,7 @@
     @Test public void testRaiseNullWithOuterJoin() {
         String sql = "select b.intkey from (select intkey from bqt1.smalla) a left outer join (select intkey from bqt1.smallb where 1 = 0) b on (a.intkey = b.intkey)"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{"SELECT null FROM bqt1.smalla"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
@@ -106,15 +106,15 @@
 
         String sql = "select smallb.intkey, smalla.intkey from bqt1.smalla left outer join bqt1.smallb on (1 = 2)"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder,  
-                                                    new String[]{"SELECT null, bqt1.smalla.intkey FROM bqt1.smalla"}, true); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder,  
+                                                    new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smalla"}, true); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
     
     @Test public void testRaiseNullWithUnion() {
         String sql = "select b.x from (select intkey as x from bqt1.smalla where 1 = 0 union all select intnum as y from bqt1.smalla) b"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{"SELECT IntNum FROM bqt1.smalla"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
         
@@ -124,7 +124,7 @@
     @Test public void testRaiseNullWithUnion1() {
         String sql = "select b.intkey from (select intkey from bqt1.smalla union all select intnum from bqt1.smalla where 1 = 0) b"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{"SELECT intkey FROM bqt1.smalla"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }    
@@ -132,8 +132,8 @@
     @Test public void testRaiseNullWithUnion2() {
         String sql = "select b.intkey, b.x from (select intkey, intnum as x from bqt1.smalla where 1 = 0 union all select intnum as a, null from bqt1.smalla union all select 1 as z, intkey as b from bqt1.smallb) b"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
-                                                    new String[]{"SELECT 1, intkey FROM bqt1.smallb", "SELECT IntNum, null FROM bqt1.smalla"}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
+                                                    new String[]{"SELECT intkey FROM bqt1.smallb", "SELECT IntNum FROM bqt1.smalla"}); //$NON-NLS-1$ //$NON-NLS-2$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
             0,      // DependentAccess
@@ -155,7 +155,7 @@
     @Test public void testRaiseNullWithUnion3() {
         String sql = "select intkey, intnum as x from bqt1.smalla where 1 = 0 union all select intnum, intkey as z from bqt1.smalla where 1 = 0"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{});
         TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
     } 
@@ -163,15 +163,15 @@
     @Test public void testRaiseNullWithUnion4() throws Exception {
         String sql = "select b.intkey, b.x from (select intkey, intnum as x from bqt1.smalla where 1 = 0 union all select 1 as z, intkey as b from bqt1.smallb) b inner join bqt1.smalla on b.intkey = bqt1.smalla.intkey"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
-                                                    new String[]{"SELECT 1, g_0.intkey FROM bqt1.smallb AS g_0, bqt1.smalla AS g_1 WHERE g_1.IntKey = 1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
+                                                    new String[]{"SELECT g_0.intkey FROM bqt1.smallb AS g_0, bqt1.smalla AS g_1 WHERE g_1.IntKey = 1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
     
     @Test public void testRaiseNullWithUnion5() {
         String sql = "select intkey from bqt1.smalla union all select intkey from bqt2.smalla where 1 = 0"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{"SELECT intkey FROM bqt1.smalla"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
@@ -179,7 +179,7 @@
     @Test public void testRaiseNullWithUnion6() {
         String sql = "select intkey from bqt1.smalla union all select intkey from bqt2.smalla union all select intkey from bqt2.smalla where 1 = 0"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{"SELECT intkey FROM bqt1.smalla", "SELECT intkey FROM bqt2.smalla"}); //$NON-NLS-1$ //$NON-NLS-2$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -201,12 +201,12 @@
     
     @Test public void testPushCriteriaThroughUnion9() {
         TestOptimizer.helpPlan("select * from vm1.u8 where const = 's1'", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT 's1', e1 FROM pm1.g1" } );     //$NON-NLS-1$
+            new String[] { "SELECT e1 FROM pm1.g1" } );     //$NON-NLS-1$
     }
 
     @Test public void testPushCriteriaThroughUnion10() {
         TestOptimizer.helpPlan("select * from vm1.u8 where const = 's3'", TestOptimizer.example1(), //$NON-NLS-1$
-            new String[] { "SELECT 's3', e1 FROM pm1.g3" } );     //$NON-NLS-1$
+            new String[] { "SELECT e1 FROM pm1.g3" } );     //$NON-NLS-1$
     }
     
     @Test public void testRaiseNullWithOuterJoinAndHaving() {
@@ -217,7 +217,7 @@
 
         String sql = "select smallb.intkey, smalla.intkey from bqt1.smalla left outer join bqt1.smallb on (1 = 2) group by smalla.intkey, smallb.intkey having max(smallb.intkey) = 1"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder,  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder,  
                                                     new String[]{"SELECT bqt1.smalla.intkey FROM bqt1.smalla"}, true); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -254,7 +254,7 @@
         
         String sql = "select max(intkey), intnum from (select intkey, intnum from bqt2.smalla where 1 = 0 union all select intnum, intnum from bqt2.smalla union all select intkey, stringkey from bqt2.smalla) x group by intnum"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                                     new String[]{"SELECT MAX(v_0.c_1), v_0.c_0 FROM (SELECT g_1.IntNum AS c_0, g_1.IntNum AS c_1 FROM bqt2.smalla AS g_1 UNION ALL SELECT g_0.StringKey AS c_0, g_0.IntKey AS c_1 FROM bqt2.smalla AS g_0) AS v_0 GROUP BY v_0.c_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
@@ -263,7 +263,7 @@
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
@@ -278,7 +278,7 @@
     @Test public void testRaiseNullWithGroupBy() {
         String sql = "select max(e2), e1 from pm1.g1 where 1 = 0 group by e1"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[]{});
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[]{});
 
         TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
     }
@@ -286,7 +286,7 @@
     @Test public void testRaiseNullWithGroupBy1() {
         String sql = "select max(e2) from pm1.g1 where 1 = 0"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[]{});
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[]{});
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
             0,      // Access
@@ -309,7 +309,7 @@
     @Test public void testRaiseNullWithExcept() {
         String sql = "select e1 from pm1.g1 except select e2 from pm1.g2 where 1 = 0"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[]{"SELECT DISTINCT g_0.e1 FROM pm1.g1 AS g_0"}); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[]{"SELECT DISTINCT g_0.e1 FROM pm1.g1 AS g_0"}); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
@@ -317,7 +317,7 @@
     @Test public void testRaiseNullWithIntersect() {
         String sql = "select max(e2) from pm1.g1 intersect select e2 from pm1.g2 where 1 = 0"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[]{});
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[]{});
 
         TestOptimizer.checkNodeTypes(plan, FULLY_NULL);
     }
@@ -342,7 +342,7 @@
     @Test public void testRaiseNullWithUnionNotAll() {
         String sql = "select intkey from bqt2.smalla union select intkey from bqt2.smalla where 1 = 0"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(),  
                                                     new String[]{"SELECT DISTINCT intkey FROM bqt2.smalla"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
@@ -350,7 +350,7 @@
     @Test public void testRaiseNullWithUnionAndAliases() {
         String sql = "select pm1.g1.e1 from pm1.g1, (select e1 from pm1.g1 where (1 = 0) union all select e1 as x from pm1.g2) x where pm1.g1.e1 <> x.e1"; //$NON-NLS-1$
         
-        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(),  
+        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(),  
                                                     new String[]{"SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE g_0.e1 <> g_1.e1"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleRaiseNull.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,7 +24,7 @@
 
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 import junit.framework.TestCase;
 
@@ -33,7 +33,7 @@
     
     /** Tests an order by in a query transformation */
     public void testRemovedOrderByFromQueryTransform() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e1, e2 FROM vm1.g14", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e1, e2 FROM vm1.g14", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1"}); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);                                    
@@ -44,7 +44,7 @@
      * physical model does not support pushing order bys
      */
     public void testRemovedOrderByFromQueryTransform2() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e, e2 FROM vm1.g8", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e, e2 FROM vm1.g8", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm1.g1"}); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -70,7 +70,7 @@
      * query transformation contains a function 
      */
     public void testRemovedOrderByFromQueryTransform3() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e, e2 FROM vm1.g16", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e, e2 FROM vm1.g16", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm3.g1"}); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -93,7 +93,7 @@
     
     /** Tests an order by in a query transformation */
     public void testRemovedOrderByFromQueryTransform4() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e1, e2 FROM vm1.g13", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT e1, e2 FROM vm1.g13", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT DISTINCT pm3.g1.e1, pm3.g1.e2, pm3.g1.e3, pm3.g1.e4 FROM pm3.g1"}); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -116,7 +116,7 @@
     
     /** Order by is not removed */
     public void testOrderByWithLimit() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (SELECT e1, e2 FROM pm1.g1 order by e1 limit 10) x", FakeMetadataFactory.example1Cached(), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (SELECT e1, e2 FROM pm1.g1 order by e1 limit 10) x", RealMetadataFactory.example1Cached(), //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);                                    


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestRuleRemoveSorts.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,7 +36,7 @@
 import org.teiid.query.processor.relational.LimitNode;
 import org.teiid.query.processor.relational.ProjectNode;
 import org.teiid.query.processor.relational.RelationalPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TestSortOptimization {
@@ -49,7 +49,7 @@
         // Create query 
         String sql = "select distinct e1, e2 from pm1.g1 order by e2"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT e1, e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
         
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -64,7 +64,7 @@
         // Create query 
         String sql = "select e1, e2 from pm1.g1 union select e1, e2 from pm1.g2 order by e2"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT e1, e2 FROM pm1.g1", "SELECT e1, e2 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
         
         checkNodeTypes(plan, new int[] {
@@ -94,7 +94,7 @@
         // Create query 
         String sql = "select x.*, y.* from (select distinct e1, e2 from pm1.g1) x, (select distinct e1, e2 from pm1.g2) y where x.e1 = y.e1"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT e1, e2 FROM pm1.g1", "SELECT e1, e2 FROM pm1.g2"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
         
         checkNodeTypes(plan, new int[] {
@@ -124,7 +124,7 @@
         // Create query 
         String sql = "select max(e1), e2 from (select distinct e1, e2 from pm1.g1) x group by e2"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ 
         
         checkNodeTypes(plan, new int[] {
@@ -146,6 +146,39 @@
         checkNodeTypes(plan, new int[] {0}, new Class[] {DupRemoveSortNode.class});
     }
 
+    /**
+     * The grouping expression inhibits combining the dup removal.
+     */
+    @Test public void testGroupDupCombination1() { 
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+
+        // Create query 
+        String sql = "select max(e1), e2 || e1 from (select distinct e1, e2 from pm1.g1) x group by e2 || e1"; //$NON-NLS-1$
+
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
+                                      new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ 
+        
+        checkNodeTypes(plan, new int[] {
+                1,      // Access
+                0,      // DependentAccess
+                0,      // DependentSelect
+                0,      // DependentProject
+                0,      // DupRemove
+                1,      // Grouping
+                0,      // NestedLoopJoinStrategy
+                0,      // MergeJoinStrategy
+                0,      // Null
+                0,      // PlanExecution
+                1,      // Project
+                0,      // Select
+                0,      // Sort
+                0       // UnionAll
+            });
+        checkNodeTypes(plan, new int[] {1}, new Class[] {DupRemoveSortNode.class});
+    }
+
     @Test public void testSortGroupCombination() { 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -154,7 +187,7 @@
         // Create query 
         String sql = "select max(e1), e2 from pm1.g1 x group by e2 order by e2"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ 
         
         checkNodeTypes(plan, new int[] {
@@ -180,7 +213,7 @@
         // Create query 
         String sql = "select e1, (select e1 from pm2.g1 where e2 = x.e2) from pm1.g1 as x order by e1 limit 2"; //$NON-NLS-1$
 
-        RelationalPlan plan = (RelationalPlan)helpPlan(sql, FakeMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), 
+        RelationalPlan plan = (RelationalPlan)helpPlan(sql, RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), 
                                       new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
         
         assertTrue(plan.getRootNode() instanceof ProjectNode);
@@ -190,7 +223,7 @@
         // Create query 
         String sql = "select (select e1 from pm2.g1 where e2 = x.e2) as z from pm1.g1 as x order by z limit 2"; //$NON-NLS-1$
 
-        RelationalPlan plan = (RelationalPlan)helpPlan(sql, FakeMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), 
+        RelationalPlan plan = (RelationalPlan)helpPlan(sql, RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), 
                                       new String[] {"SELECT pm1.g1.e2 FROM pm1.g1"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$
         
         assertTrue(plan.getRootNode() instanceof LimitNode);
@@ -200,7 +233,7 @@
         // Create query 
         String sql = "select e1, (select e1 from pm2.g1 where e2 = x.e2) as z from pm1.g1 as x order by e1"; //$NON-NLS-1$
 
-        helpPlan(sql, FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), 
+        helpPlan(sql, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), 
                                       new String[] {"SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     }
     
@@ -208,7 +241,7 @@
         // Create query 
         String sql = "select e1, (select e1 from pm2.g1 where e2 = x.e2) as z from pm1.g1 as x order by e1 limit 1"; //$NON-NLS-1$
 
-        helpPlan(sql, FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), 
+        helpPlan(sql, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), 
                                       new String[] {"SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     }
     
@@ -222,7 +255,7 @@
         
         String sql = "select (select e1 from pm2.g1 where e2 = x.e2) as z from pm1.g1 as x order by e1 limit 1"; //$NON-NLS-1$
 
-        helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 ORDER BY pm1.g1.e1 LIMIT 1"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     }
     
@@ -236,7 +269,7 @@
         
         String sql = "select e2 from pm1.g1 as x order by e1"; //$NON-NLS-1$
 
-        helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 ORDER BY pm1.g1.e1"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     }
     
@@ -250,7 +283,7 @@
         
         String sql = "select (select e1 from pm2.g1 where e2 = x.e2) as z, x.e1 as foo from pm1.g1 as x order by foo limit 1"; //$NON-NLS-1$
 
-        helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, 
+        helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, 
                                       new String[] {"SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0 LIMIT 1"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
     }
 


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestSortOptimization.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,7 +27,7 @@
 import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.metadata.TempMetadataStore;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TestStoredProcedurePlanning {
@@ -37,7 +37,7 @@
      */
 	@Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery1() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq1()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq1()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm1.g1" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -47,7 +47,7 @@
      */
 	@Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery2() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq1()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq1()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm1.g1" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -57,19 +57,19 @@
      */
 	@Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery3() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq2('1')", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq2('1')", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1'" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
 	@Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery4() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select x.e1 from (EXEC pm1.sq1()) as x", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select x.e1 from (EXEC pm1.sq1()) as x", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
 
     @Test public void testStoredQuery5() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sp1()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sp1()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp1()" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -90,7 +90,7 @@
     }
     
     @Test public void testStoredQuery6() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select x.e1 from (EXEC pm1.sp1()) as x", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select x.e1 from (EXEC pm1.sp1()) as x", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp1()" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -112,7 +112,7 @@
     
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery7() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sqsp1()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sqsp1()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp1()" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -137,7 +137,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery8() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq3('1', 1)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq3('1', 1)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1'", "SELECT e1, e2 FROM pm1.g1 WHERE e2 = 1" }); //$NON-NLS-1$ //$NON-NLS-2$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -162,7 +162,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery9() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq4()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq4()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] {"SELECT e1, e2 FROM pm1.g1" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -172,7 +172,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery10() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq5('1')", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq5('1')", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1'"}); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -182,7 +182,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery11() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq6()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq6()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] {"SELECT e1, e2 FROM pm1.g1 WHERE e1 = '1'" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -192,7 +192,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery12() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq7()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq7()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -202,7 +202,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery13() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq8('1')", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq8('1')", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = '1'" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -212,7 +212,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery14() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq9('1')", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq9('1')", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1 FROM pm1.g1 WHERE e1 = '1'" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -222,7 +222,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery15() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq10('1', 2)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq10('1', 2)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT e1 FROM pm1.g1 WHERE (e1 = '1') AND (e2 = 2)" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
     }
@@ -231,7 +231,7 @@
      * Test planning stored queries. 
      */
     @Test public void testStoredQuery16() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sp2(1)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sp2(1)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp2(1)" }); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -256,7 +256,7 @@
      */
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery17() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq11(1, 2)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq11(1, 2)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp2(?)" }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -280,7 +280,7 @@
     //GeminiStoredQueryTestPlan - 2a, 2b
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery18() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq12('1', 1)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq12('1', 1)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "INSERT INTO pm1.g1 (e1, e2) VALUES ('1', 1)" }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
@@ -289,7 +289,7 @@
     //GeminiStoredQueryTestPlan - 2c
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery19() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq13('1')", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq13('1')", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "INSERT INTO pm1.g1 (e1, e2) VALUES ('1', 2)" }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
@@ -298,7 +298,7 @@
     //GeminiStoredQueryTestPlan - 3c
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery20() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq14('1', 2)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq14('1', 2)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "UPDATE pm1.g1 SET e1 = '1' WHERE e2 = 2" }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN); 
@@ -307,7 +307,7 @@
     //GeminiStoredQueryTestPlan - 4b
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery21() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq15('1', 2)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq15('1', 2)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "DELETE FROM pm1.g1 WHERE (e1 = '1') AND (e2 = 2)" }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);               
@@ -315,7 +315,7 @@
     
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery22() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select e1 from (EXEC pm1.sq1()) as x where e1='a' union (select e1 from vm1.g2 where e1='b')", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select e1 from (EXEC pm1.sq1()) as x where e1='a' union (select e1 from vm1.g2 where e1='b')", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 = 'a'", "SELECT g_0.e1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 WHERE (g_0.e1 = g_1.e1) AND (g_0.e1 = 'b') AND (g_1.e1 = 'b')" }); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -338,14 +338,14 @@
     
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery23() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq16()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq16()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "INSERT INTO pm1.g1 (e1, e2) VALUES ('1', 2)" }); //$NON-NLS-1$
             
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);               
     }
     
     @Test public void testStoredQuery24() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sp3()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sp3()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp3()" }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -369,21 +369,21 @@
     // test implicit type conversion of argument
     @Ignore("stored procedure wrapper removal logic has been removed")
     @Test public void testStoredQuery25() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq15(1, 2)", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("EXEC pm1.sq15(1, 2)", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "DELETE FROM pm1.g1 WHERE (e1 = '1') AND (e2 = 2)" }); //$NON-NLS-1$
 
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
 
     @Test public void testStoredQueryXML1() {
-        TestOptimizer.helpPlan("EXEC pm1.sq18()", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), new String[] { }); //$NON-NLS-1$
+        TestOptimizer.helpPlan("EXEC pm1.sq18()", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), new String[] { }); //$NON-NLS-1$
     }
     
     /**
      * union of two stored procs - case #1466
      */
     @Test public void testStoredProc1() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT * FROM (EXEC pm1.sp2(1)) AS x UNION ALL SELECT * FROM (EXEC pm1.sp2(2)) AS y", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT * FROM (EXEC pm1.sp2(1)) AS x UNION ALL SELECT * FROM (EXEC pm1.sp2(2)) AS y", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp2(1)", "EXEC pm1.sp2(2)" }); //$NON-NLS-1$ //$NON-NLS-2$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -407,7 +407,7 @@
      * union of stored proc and query - case #1466
      */
     @Test public void testStoredProc2() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT * FROM (EXEC pm1.sp2(1)) AS x UNION ALL SELECT e1, e2 FROM pm1.g1", new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT * FROM (EXEC pm1.sp2(1)) AS x UNION ALL SELECT e1, e2 FROM pm1.g1", new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore()), //$NON-NLS-1$
             new String[] { "EXEC pm1.sp2(1)", "SELECT e1, e2 FROM pm1.g1" }); //$NON-NLS-1$ //$NON-NLS-2$
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestStoredProcedurePlanning.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,6 +28,7 @@
 import org.junit.Test;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer.AntiSemiJoin;
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.optimizer.TestOptimizer.SemiJoin;
@@ -38,8 +39,6 @@
 import org.teiid.query.optimizer.relational.rules.RuleMergeCriteria;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.rewriter.TestQueryRewriter;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.SourceSystemFunctions;
 
@@ -56,7 +55,7 @@
 	    caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
 	    capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 	    
-	    FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+	    QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 	
 	    // Plan query
 	    ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, 
@@ -96,7 +95,7 @@
 	    caps.setCapabilitySupport(Capability.CRITERIA_EXISTS, true);
 	    capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 	    
-	    FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+	    QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 	
 	    // Plan query
 	    ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, 
@@ -138,7 +137,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT intkey FROM bqt1.smalla AS n WHERE intkey = (SELECT MAX(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = n.stringkey )", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT intkey FROM bqt1.smalla AS n WHERE intkey = (SELECT MAX(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = n.stringkey )", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT intkey FROM bqt1.smalla AS n WHERE intkey = (SELECT MAX(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = n.stringkey)" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -179,7 +178,7 @@
 
         String sqlOut = "SELECT g_0.intkey FROM bqt1.mediuma AS g_0, bqt1.smallb AS g_1 WHERE (g_0.stringkey = concat('1', concat(g_1.intkey, '0'))) AND (g_0.datevalue = (SELECT MAX(g_2.datevalue) FROM bqt1.mediuma AS g_2, bqt1.smallb AS g_3 WHERE (g_2.stringkey = concat('1', concat(g_3.intkey, '0'))) AND (g_3.stringkey LIKE '%0') AND (g_3.stringkey = g_1.stringkey))) AND (g_1.stringkey LIKE '%0')"; //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan(sqlIn, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = helpPlan(sqlIn, RealMetadataFactory.exampleBQTCached(),  
             null, capFinder,
             new String[] { sqlOut }, SHOULD_SUCCEED); 
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -218,7 +217,7 @@
         String sqlOut = 
             "SELECT SmallA__1.IntKey FROM BQT1.SmallA AS SmallA__1 WHERE (SmallA__1.StringKey = 'VOD.L') AND (SmallA__1.DateValue = (SELECT MAX(BQT1.SmallA.DateValue) FROM BQT1.SmallA WHERE BQT1.SmallA.StringKey = SmallA__1.StringKey))"; //$NON-NLS-1$
         
-        ProcessorPlan plan = helpPlan(sqlIn, FakeMetadataFactory.exampleBQTCached(),  
+        ProcessorPlan plan = helpPlan(sqlIn, RealMetadataFactory.exampleBQTCached(),  
             null, capFinder,
             new String[] { sqlOut }, SHOULD_SUCCEED); 
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -236,7 +235,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT stringkey, (SELECT intkey FROM BQT1.SmallA AS b WHERE Intnum = 22) FROM BQT1.SmallA", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT stringkey, (SELECT intkey FROM BQT1.SmallA AS b WHERE Intnum = 22) FROM BQT1.SmallA", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT stringkey, (SELECT intkey FROM BQT1.SmallA AS b WHERE Intnum = 22) FROM BQT1.SmallA" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -258,7 +257,7 @@
     }   
     
     @Test public void testCorrelatedSubquery1() {
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm2.g1 WHERE pm1.g1.e2 = pm2.g1.e2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm2.g1 WHERE pm1.g1.e2 = pm2.g1.e2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             new String[] { "SELECT e1, pm1.g1.e2 FROM pm1.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -279,7 +278,7 @@
     }
 
     @Test public void testCorrelatedSubquery2() {
-        ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 WHERE pm1.g1.e2 = pm2.g1.e2) from pm1.g1", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 WHERE pm1.g1.e2 = pm2.g1.e2) from pm1.g1", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             new String[] { "SELECT e1, pm1.g1.e2 FROM pm1.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -364,7 +363,7 @@
 
     @Test public void testCorrelatedSubqueryInTransformation2() {
         String sql = "Select * from vm1.g20"; //$NON-NLS-1$
-        ProcessorPlan plan = helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = helpPlan(sql, RealMetadataFactory.example1Cached(), 
             new String[] { "SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 FROM pm1.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -394,7 +393,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select max(e1) FROM pm1.g2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select max(e1) FROM pm1.g2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -426,7 +425,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", getTypicalCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm2.g1)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select e1 FROM pm2.g1)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -459,7 +458,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select * from xmltest.doc1)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (select * from xmltest.doc1)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -492,7 +491,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT ltrim(e1) FROM pm1.g2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT ltrim(e1) FROM pm1.g2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -524,7 +523,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT 'xyz' FROM pm1.g2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT 'xyz' FROM pm1.g2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -556,7 +555,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT e1 FROM pm1.g2 ORDER BY e1 limit 2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT e1 FROM pm1.g2 ORDER BY e1 limit 2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -590,7 +589,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT rtrim(ltrim(e1)) FROM pm1.g2)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT rtrim(ltrim(e1)) FROM pm1.g2)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -622,7 +621,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (EXEC pm1.sqsp1())", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (EXEC pm1.sqsp1())", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -654,7 +653,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g2.e1 = pm1.g1.e1)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in (SELECT pm1.g2.e1 FROM pm1.g2 WHERE pm1.g2.e1 = pm1.g1.e1)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT e1 FROM pm1.g1" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, new int[] {
@@ -693,7 +692,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        ProcessorPlan plan = helpPlan("SELECT intkey FROM bqt1.smalla AS n WHERE intkey = (SELECT MAX(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = n.stringkey ) or intkey = (SELECT MIN(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = n.stringkey )", FakeMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("SELECT intkey FROM bqt1.smalla AS n WHERE intkey = (SELECT MAX(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = n.stringkey ) or intkey = (SELECT MIN(intkey) FROM bqt1.smallb AS s WHERE s.stringkey = n.stringkey )", RealMetadataFactory.exampleBQTCached(),  //$NON-NLS-1$
             null, capFinder,
             new String[] { "SELECT g_0.intkey FROM bqt1.smalla AS g_0 WHERE (g_0.intkey = (SELECT MAX(g_1.intkey) FROM bqt1.smallb AS g_1 WHERE g_1.stringkey = g_0.stringkey)) OR (g_0.intkey = (SELECT MIN(g_2.IntKey) FROM bqt1.smallb AS g_2 WHERE g_2.StringKey = g_0.stringkey))" }, SHOULD_SUCCEED); //$NON-NLS-1$ 
         checkNodeTypes(plan, FULL_PUSHDOWN); 
@@ -704,7 +703,7 @@
      */
     @Test public void testProjectSubqueryPushdown() {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_CORRELATED, true);
@@ -722,7 +721,7 @@
     }
     
     @Test public void testScalarSubquery2() {
-        ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 where pm1.g1.e1 = 'x') as X from pm1.g1", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 where pm1.g1.e1 = 'x') as X from pm1.g1", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             new String[] { "SELECT e1 FROM pm1.g1" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -746,66 +745,73 @@
      * Technically this is not a full push-down, but the subquery will be evaluated prior to pushdown
      */
     @Test public void testCompareSubquery4() throws TeiidComponentException, TeiidProcessingException {
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 > (select e1 FROM pm2.g1 where e2 = 13)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 > (select e1 FROM pm2.g1 where e2 = 13)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 > (SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e2 = 13)" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
     
     @Test public void testScalarSubquery1() throws TeiidComponentException, TeiidProcessingException {
-        ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 where e1 = 'x') from pm1.g1", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1, (select e1 FROM pm2.g1 where e1 = 'x') from pm1.g1", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             new String[] { "SELECT g_0.e1, (SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e1 = 'x') FROM pm1.g1 AS g_0" }, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         checkNodeTypes(plan, FULL_PUSHDOWN); 
     }
     
     @Test public void testSubqueryRewriteToJoinDistinct() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select distinct e1 from pm1.g1 as x where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = x.e1)", "SELECT DISTINCT e1 FROM pm1.g1 AS x, (SELECT pm1.g1.e1 FROM pm1.g1) AS X__1 WHERE x.e1 = X__1.e1", FakeMetadataFactory.example1Cached());
+    	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
+        TestQueryRewriter.helpTestRewriteCommand("Select distinct e1 from pm1.g1 as x where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = x.e1)", "SELECT DISTINCT e1 FROM pm1.g1 AS x, (SELECT pm1.g1.e1 FROM pm1.g1) AS X__1 WHERE x.e1 = X__1.e1", RealMetadataFactory.example1Cached());
     }
     
     /**
      * Agg does not depend on cardinality
      */
     @Test public void testSubqueryRewriteToJoinGroupBy() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select max(e1) from pm1.g1 as x where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = x.e1) group by e2", "SELECT MAX(e1) FROM pm1.g1 AS x, (SELECT pm1.g1.e1 FROM pm1.g1) AS X__1 WHERE x.e1 = X__1.e1 GROUP BY e2", FakeMetadataFactory.example1Cached());
+    	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
+        TestQueryRewriter.helpTestRewriteCommand("Select max(e1) from pm1.g1 as x where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = x.e1) group by e2", "SELECT MAX(e1) FROM pm1.g1 AS x, (SELECT pm1.g1.e1 FROM pm1.g1) AS X__1 WHERE x.e1 = X__1.e1 GROUP BY e2", RealMetadataFactory.example1Cached());
     }
     
     /**
      * Agg does depend on cardinality
      */
     @Test public void testSubqueryRewriteToJoinGroupBy1() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select avg(e1) from pm1.g1 as x where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = x.e1) group by e2", "SELECT AVG(e1) FROM pm1.g1 AS x WHERE EXISTS (SELECT pm1.g1.e1 FROM pm1.g1 WHERE e1 = x.e1 LIMIT 1) GROUP BY e2", FakeMetadataFactory.example1Cached());
+        TestQueryRewriter.helpTestRewriteCommand("Select avg(e1) from pm1.g1 as x where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = x.e1) group by e2", "SELECT AVG(e1) FROM pm1.g1 AS x WHERE EXISTS (SELECT pm1.g1.e1 FROM pm1.g1 WHERE e1 = x.e1 LIMIT 1) GROUP BY e2", RealMetadataFactory.example1Cached());
     }
     
     @Test public void testSubqueryRewriteToJoin() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = pm3.g1.e1)", "SELECT e1 FROM pm3.g1, (SELECT pm1.g1.e1 FROM pm1.g1) AS X__1 WHERE pm3.g1.e1 = X__1.e1", FakeMetadataFactory.example4());
+    	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where exists (select pm1.g1.e1 FROM pm1.g1 where e1 = pm3.g1.e1)", "SELECT e1 FROM pm3.g1, (SELECT pm1.g1.e1 FROM pm1.g1) AS X__1 WHERE pm3.g1.e1 = X__1.e1", RealMetadataFactory.example4());
     }
     
     @Test public void testSubqueryRewriteToJoin1() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ mj */ (select pm1.g1.e1 as x FROM pm1.g1)", "SELECT e1 FROM pm3.g1, (SELECT pm1.g1.e1 AS x FROM pm1.g1) AS X__1 WHERE pm3.g1.e1 = X__1.x", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ mj */ (select pm1.g1.e1 as x FROM pm1.g1)", "SELECT e1 FROM pm3.g1, (SELECT pm1.g1.e1 AS x FROM pm1.g1) AS X__1 WHERE pm3.g1.e1 = X__1.x", RealMetadataFactory.example4());
     }
     
     @Test public void testSubqueryRewriteToJoin2() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ mj */ (select pm1.g1.e1 || 1 FROM pm1.g1)", "SELECT e1 FROM pm3.g1, (SELECT concat(pm1.g1.e1, '1') AS EXPR FROM pm1.g1) AS X__1 WHERE pm3.g1.e1 = X__1.EXPR", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ mj */ (select distinct pm1.g1.e1 || 1 FROM pm1.g1)", "SELECT e1 FROM pm3.g1, (SELECT DISTINCT concat(pm1.g1.e1, '1') AS EXPR FROM pm1.g1) AS X__1 WHERE pm3.g1.e1 = X__1.EXPR", RealMetadataFactory.example4());
     }
-    
+
+    @Test public void testSubqueryRewriteToJoin2a() throws Exception {
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ mj */ (select pm1.g1.e1 || 1 FROM pm1.g1)", "SELECT e1 FROM pm3.g1, (SELECT DISTINCT concat(pm1.g1.e1, '1') AS EXPR FROM pm1.g1) AS X__1 WHERE pm3.g1.e1 = X__1.EXPR", RealMetadataFactory.example4());
+    }
+
     /**
      * Even though this situation is essentially the same as above, we don't yet handle it
      */
     @Test public void testSubqueryRewriteToJoin3() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where exists (select pm1.g1.e2 FROM pm1.g1 WHERE pm3.g1.e1 = pm1.g1.e1 || 1)", "SELECT e1 FROM pm3.g1 WHERE EXISTS (SELECT pm1.g1.e2 FROM pm1.g1 WHERE concat(pm1.g1.e1, '1') = pm3.g1.e1 LIMIT 1)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where exists (select pm1.g1.e2 FROM pm1.g1 WHERE pm3.g1.e1 = pm1.g1.e1 || 1)", "SELECT e1 FROM pm3.g1 WHERE EXISTS (SELECT pm1.g1.e2 FROM pm1.g1 WHERE concat(pm1.g1.e1, '1') = pm3.g1.e1 LIMIT 1)", RealMetadataFactory.example4());
     }
     
     @Test public void testSubqueryRewriteToJoinWithOtherCriteria() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ mj */ (select pm1.g1.e1 FROM pm1.g1 where e2 < pm3.g1.e2)", "SELECT e1 FROM pm3.g1, (SELECT pm1.g1.e1, e2 FROM pm1.g1) AS X__1 WHERE (X__1.e2 < pm3.g1.e2) AND (pm3.g1.e1 = X__1.e1)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ mj */ (select pm1.g1.e1 FROM pm1.g1 where e2 < pm3.g1.e2)", "SELECT e1 FROM pm3.g1, (SELECT pm1.g1.e1, e2 FROM pm1.g1) AS X__1 WHERE (X__1.e2 < pm3.g1.e2) AND (pm3.g1.e1 = X__1.e1)", RealMetadataFactory.example4());
     }
     
     @Test public void testDontRewriteToJoinWithOtherCriteria() throws Exception {
     	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ NO_UNNEST */ (select pm1.g1.e1 FROM pm1.g1 where e2 < pm3.g1.e2)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e1 IN /*+ NO_UNNEST */ (SELECT pm1.g1.e1 FROM pm1.g1 WHERE e2 < pm3.g1.e2)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e1 in /*+ NO_UNNEST */ (select pm1.g1.e1 FROM pm1.g1 where e2 < pm3.g1.e2)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e1 IN /*+ NO_UNNEST */ (SELECT pm1.g1.e1 FROM pm1.g1 WHERE e2 < pm3.g1.e2)", RealMetadataFactory.example4());
     }
 
     @Test public void testSubqueryRewriteToJoinWithAggregate() throws Exception {
     	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (select max(e2) FROM pm1.g1 where pm3.g1.e1 = e1)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1 FROM pm1.g1 GROUP BY e1) AS X__1 WHERE (pm3.g1.e2 < X__1.MAX) AND (pm3.g1.e1 = X__1.e1)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (select max(e2) FROM pm1.g1 where pm3.g1.e1 = e1)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1 FROM pm1.g1 GROUP BY e1) AS X__1 WHERE (pm3.g1.e2 < X__1.MAX) AND (pm3.g1.e1 = X__1.e1)", RealMetadataFactory.example4());
     }
     
     /**
@@ -813,20 +819,25 @@
      * @throws Exception
      */
     @Test public void testSubqueryRewriteToJoinWithAggregate1() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (select max(e2) FROM pm1.g1 where pm3.g1.e1 = e1 and pm3.g1.e3 > e3)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e2 < (SELECT MAX(e2) FROM pm1.g1 WHERE (e1 = pm3.g1.e1) AND (e3 < pm3.g1.e3))", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (select max(e2) FROM pm1.g1 where pm3.g1.e1 = e1 and pm3.g1.e3 > e3)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e2 < (SELECT MAX(e2) FROM pm1.g1 WHERE (e1 = pm3.g1.e1) AND (e3 < pm3.g1.e3))", RealMetadataFactory.example4());
     }
     
     @Test public void testSubqueryRewriteToJoinWithAggregate2() throws Exception {
     	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (select max(e2) FROM pm1.g1 WHERE pm3.g1.e1 = e1 HAVING min(e3) < pm3.g1.e3)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1, MIN(e3) AS MIN FROM pm1.g1 GROUP BY e1) AS X__1 WHERE (X__1.MIN < pm3.g1.e3) AND (pm3.g1.e2 < X__1.MAX) AND (pm3.g1.e1 = X__1.e1)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (select max(e2) FROM pm1.g1 WHERE pm3.g1.e1 = e1 HAVING min(e3) < pm3.g1.e3)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1, MIN(e3) AS MIN FROM pm1.g1 GROUP BY e1) AS X__1 WHERE (X__1.MIN < pm3.g1.e3) AND (pm3.g1.e2 < X__1.MAX) AND (pm3.g1.e1 = X__1.e1)", RealMetadataFactory.example4());
     }
+    
+    @Test public void testSubqueryRewriteToJoinWithGroupingExpression() throws Exception {
+    	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
+        TestQueryRewriter.helpTestRewriteCommand("Select distinct e1 from pm3.g1 where exists (select 1 FROM pm1.g1 group by e4 || 'x' HAVING min(e3) || (e4 || 'x') = pm3.g1.e3)", "SELECT DISTINCT e1 FROM pm3.g1, (SELECT 1 AS EXPR, MIN(e3) AS MIN, concat(e4, 'x') AS EXPR_0, concat(MIN(e3), concat(e4, 'x')) AS EXPR_1 FROM pm1.g1 GROUP BY concat(e4, 'x')) AS X__1 WHERE pm3.g1.e3 = X__1.EXPR_1", RealMetadataFactory.example4());
+    }
 
     /**
      * A join will not be used here because of the not
      * @throws Exception
      */
     @Test public void testSubqueryRewriteNot() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 not in (select e2 FROM pm1.g1 where pm3.g1.e1 = e1)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e2 NOT IN (SELECT e2 FROM pm1.g1 WHERE e1 = pm3.g1.e1)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 not in (select e2 FROM pm1.g1 where pm3.g1.e1 = e1)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e2 NOT IN (SELECT e2 FROM pm1.g1 WHERE e1 = pm3.g1.e1)", RealMetadataFactory.example4());
     }
 
     /**
@@ -834,19 +845,35 @@
      * @throws Exception
      */
     @Test public void testSubqueryRewriteAll() throws Exception {
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 = all (select e2 FROM pm1.g1 where pm3.g1.e1 = e1)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e2 = ALL (SELECT e2 FROM pm1.g1 WHERE e1 = pm3.g1.e1)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 = all (select e2 FROM pm1.g1 where pm3.g1.e1 = e1)", "SELECT e1 FROM pm3.g1 WHERE pm3.g1.e2 = ALL (SELECT e2 FROM pm1.g1 WHERE e1 = pm3.g1.e1)", RealMetadataFactory.example4());
     }
     
+    @Test public void testRewriteSubqueryCompare() throws Exception {
+    	TestQueryRewriter.helpTestRewriteCommand("select e1 from pm1.g1 where e1 <> ANY (select e1 from pm1.g1)", "SELECT e1 FROM pm1.g1 WHERE e1 <> SOME (SELECT e1 FROM pm1.g1)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteSubqueryCompare1() throws Exception {
+    	TestQueryRewriter.helpTestRewriteCommand("select e1 from pm1.g1 where e1 <> ALL (select e1 from pm1.g1)", "SELECT e1 FROM pm1.g1 WHERE e1 NOT IN (SELECT e1 FROM pm1.g1)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+    @Test public void testRewriteSubqueryCompare2() throws Exception {
+    	TestQueryRewriter.helpTestRewriteCommand("select e1 from pm1.g1 where e1 = ANY (select e1 from pm1.g1)", "SELECT e1 FROM pm1.g1 WHERE e1 IN (SELECT e1 FROM pm1.g1)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteSubqueryCompare3() throws Exception {
+    	TestQueryRewriter.helpTestRewriteCommand("select e1 from pm1.g1 where e1 = ALL (select e1 from pm1.g1)", "SELECT e1 FROM pm1.g1 WHERE e1 = ALL (SELECT e1 FROM pm1.g1)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
     @Test public void testSubqueryExpressionJoin() throws Exception {
     	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
-        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (Select max(e2) from pm2.g2 where e1 = pm3.g1.e1 having convert(min(e2), string) > pm3.g1.e1)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1, MIN(e2) AS MIN FROM pm2.g2 GROUP BY e1) AS X__1 WHERE (convert(X__1.MIN, string) > pm3.g1.e1) AND (pm3.g1.e2 < X__1.MAX) AND (pm3.g1.e1 = X__1.e1)", FakeMetadataFactory.example4());
+        TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 < (Select max(e2) from pm2.g2 where e1 = pm3.g1.e1 having convert(min(e2), string) > pm3.g1.e1)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1, MIN(e2) AS MIN FROM pm2.g2 GROUP BY e1) AS X__1 WHERE (convert(X__1.MIN, string) > pm3.g1.e1) AND (pm3.g1.e2 < X__1.MAX) AND (pm3.g1.e1 = X__1.e1)", RealMetadataFactory.example4());
     }
 
     /**
      * Must be handled as a semi-join, rather than a regular join
      */
     @Test public void testSemiJoin() {
-        ProcessorPlan plan = helpPlan("Select e1 from pm2.g2 where e2 in /*+ mj */ (select count(e2) FROM pm1.g2 group by e1 having e1 < pm2.g2.e3)", FakeMetadataFactory.example4(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm2.g2 where e2 in /*+ mj */ (select count(e2) FROM pm1.g2 group by e1 having e1 < pm2.g2.e3)", RealMetadataFactory.example4(),  //$NON-NLS-1$
             new String[] { "SELECT g_0.e2 AS c_0, g_0.e3 AS c_1, g_0.e1 AS c_2 FROM pm2.g2 AS g_0 ORDER BY c_0" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -871,7 +898,7 @@
      * This will not plan as a anti semi-join since the cost seems too high
      */
     @Test public void testNoAntiSemiJoinExistsCosting() {
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g2 as o where not exists (select 1 from pm3.g1 where e1 = o.e1 having o.e2 = count(e2))", FakeMetadataFactory.example4(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g2 as o where not exists (select 1 from pm3.g1 where e1 = o.e1 having o.e2 = count(e2))", RealMetadataFactory.example4(),  //$NON-NLS-1$
             new String[] { "SELECT g_0.e1, g_0.e2 FROM pm1.g2 AS g_0" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -895,7 +922,8 @@
      * Same as above, but the source is much larger, so a semi-join is favorable
      */
     @Test public void testSemiJoinExistsCosting() {
-        ProcessorPlan plan = helpPlan("Select e1 from pm2.g2 as o where not exists (select 1 from pm3.g1 where e1 = o.e1 having o.e2 = count(e2))", FakeMetadataFactory.example4(),  //$NON-NLS-1$
+    	System.setProperty(RuleMergeCriteria.UNNEST_DEFAULT, Boolean.TRUE.toString());
+        ProcessorPlan plan = helpPlan("Select e1 from pm2.g2 as o where not exists (select 1 from pm3.g1 where e1 = o.e1 having o.e2 = count(e2))", RealMetadataFactory.example4(),  //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm2.g2 AS g_0 ORDER BY c_0, c_1" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -917,7 +945,7 @@
     }
     
     @Test public void testAntiSemiJoinExistsHint() {
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g2 as o where not exists /*+ MJ */ (select 1 from pm3.g1 where e1 = o.e1 having o.e2 = count(e2))", FakeMetadataFactory.example4(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g2 as o where not exists /*+ MJ */ (select 1 from pm3.g1 where e1 = o.e1 having o.e2 = count(e2))", RealMetadataFactory.example4(),  //$NON-NLS-1$
             new String[] { "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm1.g2 AS g_0 ORDER BY c_0, c_1" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -943,7 +971,7 @@
     }
     
     @Test public void testAntiSemiJoinInHint() {
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g2 as o where e2 NOT IN /*+ MJ */ (select count(e2) from pm3.g1 where e1 = o.e1)", FakeMetadataFactory.example4(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g2 as o where e2 NOT IN /*+ MJ */ (select count(e2) from pm3.g1 where e1 = o.e1)", RealMetadataFactory.example4(),  //$NON-NLS-1$
             new String[] { "SELECT g_0.e2 AS c_0, g_0.e1 AS c_1 FROM pm1.g2 AS g_0 ORDER BY c_1, c_0" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -969,7 +997,7 @@
     }
     
     @Test public void testNonSemiJoin() throws Exception {
-        ProcessorPlan plan = helpPlan("Select x from xmltable('/a/b' passing convert('<a/>', xml) columns x integer path '@x') as t where x = (select count(e2) FROM pm1.g2)", FakeMetadataFactory.example4(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select x from xmltable('/a/b' passing convert('<a/>', xml) columns x integer path '@x') as t where x = (select count(e2) FROM pm1.g2)", RealMetadataFactory.example4(),  //$NON-NLS-1$
             new String[] {}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             0,      // Access
@@ -1001,7 +1029,7 @@
     }
 
     @Test public void testInvalidGeneratedSemijoinQuery1() throws Exception {
-    	TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 IN /*+ mj */ (Select max(e2) from pm2.g2 where e1 = pm3.g1.e1)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1 FROM pm2.g2 GROUP BY e1) AS X__1 WHERE (pm3.g1.e1 = X__1.e1) AND (pm3.g1.e2 = X__1.MAX)", FakeMetadataFactory.example4());
+    	TestQueryRewriter.helpTestRewriteCommand("Select e1 from pm3.g1 where pm3.g1.e2 IN /*+ mj */ (Select max(e2) from pm2.g2 where e1 = pm3.g1.e1)", "SELECT e1 FROM pm3.g1, (SELECT MAX(e2) AS MAX, e1 FROM pm2.g2 GROUP BY e1) AS X__1 WHERE (pm3.g1.e1 = X__1.e1) AND (pm3.g1.e2 = X__1.MAX)", RealMetadataFactory.example4());
     }
     
     @Test public void testCompareSubquery2() throws Exception {
@@ -1011,7 +1039,7 @@
     }
     
     @Test public void testUncorrelatedSet() {
-        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in /*+ mj */ (select e1 FROM pm2.g1)", FakeMetadataFactory.example1Cached(),  //$NON-NLS-1$
+        ProcessorPlan plan = helpPlan("Select e1 from pm1.g1 where e1 in /*+ mj */ (select e1 FROM pm2.g1)", RealMetadataFactory.example1Cached(),  //$NON-NLS-1$
             new String[] { "SELECT DISTINCT g_0.e1 FROM pm2.g1 AS g_0", "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0" }); //$NON-NLS-1$
         checkNodeTypes(plan, new int[] {
             2,      // Access


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java:3149-3217,3281-3325
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestSubqueryPushdown.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,7 +28,7 @@
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestUnionPlanning {
@@ -41,7 +41,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA", FakeMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA", RealMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
             new String[] { "SELECT IntNum FROM BQT2.SmallA", "SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA" }, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ 
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -73,7 +73,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA", FakeMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA", RealMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
             new String[] { "SELECT IntNum FROM BQT2.SmallA", "SELECT IntKey FROM BQT1.SmallA", "SELECT IntNum FROM BQT1.SmallA" }, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -104,7 +104,7 @@
         BasicSourceCapabilities caps1 = TestOptimizer.getTypicalCapabilities();
         capFinder.addCapabilities("BQT3", caps1); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT3.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA", FakeMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT3.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA", RealMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
             new String[] { "SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA", "SELECT IntNum FROM BQT3.SmallA", "SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA" }, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -135,7 +135,7 @@
         BasicSourceCapabilities caps1 = TestOptimizer.getTypicalCapabilities();
         capFinder.addCapabilities("BQT3", caps1); //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT3.SmallA UNION ALL (SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA)", FakeMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT3.SmallA UNION ALL (SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA)", RealMetadataFactory.exampleBQTCached(), null, capFinder,//$NON-NLS-1$
             new String[] { "SELECT IntNum FROM BQT3.SmallA", "SELECT IntNum FROM BQT2.SmallA UNION ALL (SELECT IntNum FROM BQT2.SmallA UNION ALL SELECT IntNum FROM BQT2.SmallA)", "SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA" }, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -157,7 +157,7 @@
     }
         
     @Test public void testUnionPushDownWithJoin() {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (SELECT IntKey FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallA where intkey in (3, 4)) A inner join (SELECT intkey FROM BQT1.SmallB where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallB where intkey in (3, 4)) B on a.intkey = b.intkey", FakeMetadataFactory.exampleBQTCached(), null, TestOptimizer.getGenericFinder(),//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (SELECT IntKey FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallA where intkey in (3, 4)) A inner join (SELECT intkey FROM BQT1.SmallB where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallB where intkey in (3, 4)) B on a.intkey = b.intkey", RealMetadataFactory.exampleBQTCached(), null, TestOptimizer.getGenericFinder(),//$NON-NLS-1$
             new String[] { "SELECT g_1.intkey, g_0.intkey FROM BQT2.SmallA AS g_0, BQT2.SmallB AS g_1 WHERE (g_0.intkey = g_1.intkey) AND (g_0.intkey IN (3, 4)) AND (g_1.intkey IN (3, 4))", 
         	"SELECT g_1.intkey, g_0.IntKey FROM BQT1.SmallA AS g_0, BQT1.SmallB AS g_1 WHERE (g_0.IntKey = g_1.intkey) AND (g_0.intkey IN (1, 2)) AND (g_1.intkey IN (1, 2))" }, TestOptimizer.SHOULD_SUCCEED); 
 
@@ -180,12 +180,12 @@
     }
     
     @Test public void testUnionPushDownWithJoinNoMatches() {
-        TestOptimizer.helpPlan("select * from (SELECT IntKey FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallA where intkey in (3, 4)) A inner join (SELECT intkey FROM BQT1.SmallB where intkey in (5, 6) UNION ALL SELECT intkey FROM BQT2.SmallB where intkey in (7, 8)) B on a.intkey = b.intkey", FakeMetadataFactory.exampleBQTCached(), null, TestOptimizer.getGenericFinder(),//$NON-NLS-1$
+        TestOptimizer.helpPlan("select * from (SELECT IntKey FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallA where intkey in (3, 4)) A inner join (SELECT intkey FROM BQT1.SmallB where intkey in (5, 6) UNION ALL SELECT intkey FROM BQT2.SmallB where intkey in (7, 8)) B on a.intkey = b.intkey", RealMetadataFactory.exampleBQTCached(), null, TestOptimizer.getGenericFinder(),//$NON-NLS-1$
             new String[] {}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$  
     }
     
     @Test public void testUnionPushDownWithJoin1() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (SELECT IntKey FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallA where intkey in (3, 4)) A inner join (SELECT intkey FROM BQT1.SmallB where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallB where intkey in (3, 4)) B on a.intkey = b.intkey where a.intkey in (1, 4)", FakeMetadataFactory.exampleBQTCached(), null, TestOptimizer.getGenericFinder(),//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (SELECT IntKey FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallA where intkey in (3, 4)) A inner join (SELECT intkey FROM BQT1.SmallB where intkey in (1, 2) UNION ALL SELECT intkey FROM BQT2.SmallB where intkey in (3, 4)) B on a.intkey = b.intkey where a.intkey in (1, 4)", RealMetadataFactory.exampleBQTCached(), null, TestOptimizer.getGenericFinder(),//$NON-NLS-1$
             new String[] { "SELECT g_1.intkey, g_0.IntKey FROM BQT1.SmallA AS g_0, BQT1.SmallB AS g_1 WHERE (g_0.IntKey = g_1.intkey) AND (g_0.intkey IN (1)) AND (g_0.IntKey = 1) AND (g_1.intkey = 1)",
             		"SELECT g_1.intkey, g_0.intkey FROM BQT2.SmallA AS g_0, BQT2.SmallB AS g_1 WHERE (g_0.intkey = g_1.intkey) AND (g_0.intkey IN (4)) AND (g_0.intkey = 4) AND (g_1.intkey = 4)" }, ComparisonMode.EXACT_COMMAND_STRING); 
 
@@ -208,7 +208,7 @@
     }
     
     @Test public void testUnionWithPartitionedAggregate() throws Exception {
-        ProcessorPlan plan = TestOptimizer.helpPlan("select max(intnum) from (SELECT IntKey, intnum FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey, intnum FROM BQT2.SmallA where intkey in (3, 4)) A group by intkey", FakeMetadataFactory.exampleBQTCached(), null, TestInlineView.getInliveViewCapabilitiesFinder(),//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select max(intnum) from (SELECT IntKey, intnum FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey, intnum FROM BQT2.SmallA where intkey in (3, 4)) A group by intkey", RealMetadataFactory.exampleBQTCached(), null, TestInlineView.getInliveViewCapabilitiesFinder(),//$NON-NLS-1$
             new String[] { "SELECT MAX(v_0.c_1) FROM (SELECT g_0.IntKey AS c_0, g_0.intnum AS c_1 FROM BQT1.SmallA AS g_0 WHERE g_0.intkey IN (1, 2)) AS v_0 GROUP BY v_0.c_0", 
         			"SELECT MAX(v_0.c_1) FROM (SELECT g_0.intkey AS c_0, g_0.intnum AS c_1 FROM BQT2.SmallA AS g_0 WHERE g_0.intkey IN (3, 4)) AS v_0 GROUP BY v_0.c_0" }, ComparisonMode.EXACT_COMMAND_STRING); 
 
@@ -232,7 +232,7 @@
     
     @Test public void testUnionPartitionedWithMerge() throws Exception {
     	//"select max(intnum) from (select * from (SELECT IntKey, intnum FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey, intnum FROM BQT2.SmallA where intkey in (3, 4)) A where intkey in (1, 2, 3, 4) UNION ALL select intkey, intnum from bqt2.smallb where intkey in 6) B group by intkey"
-        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (select * from (SELECT IntKey, intnum FROM BQT1.SmallA UNION ALL SELECT intkey, intnum FROM BQT2.SmallA) A where intkey in (1, 2, 3, 4) UNION ALL select intkey, intnum from bqt2.smallb where intkey in (6)) B inner join (SELECT IntKey, intnum FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey, intnum FROM BQT2.SmallA where intkey in (5, 6)) C on b.intkey = c.intkey", FakeMetadataFactory.exampleBQTCached(), null, TestInlineView.getInliveViewCapabilitiesFinder(),//$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan("select * from (select * from (SELECT IntKey, intnum FROM BQT1.SmallA UNION ALL SELECT intkey, intnum FROM BQT2.SmallA) A where intkey in (1, 2, 3, 4) UNION ALL select intkey, intnum from bqt2.smallb where intkey in (6)) B inner join (SELECT IntKey, intnum FROM BQT1.SmallA where intkey in (1, 2) UNION ALL SELECT intkey, intnum FROM BQT2.SmallA where intkey in (5, 6)) C on b.intkey = c.intkey", RealMetadataFactory.exampleBQTCached(), null, TestInlineView.getInliveViewCapabilitiesFinder(),//$NON-NLS-1$
             new String[] { "SELECT g_0.intkey, g_0.intnum FROM BQT2.SmallA AS g_0 WHERE g_0.intkey IN (1, 2)",
         	"SELECT g_0.IntKey, g_0.intnum FROM BQT1.SmallA AS g_0 WHERE g_0.IntKey IN (1, 2)",
         	"SELECT g_1.IntKey, g_1.IntNum, g_0.intkey, g_0.intnum FROM bqt2.smallb AS g_0, BQT2.SmallA AS g_1 WHERE (g_0.intkey = g_1.IntKey) AND (g_0.intkey = 6) AND (g_1.IntKey = 6)",


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/TestUnionPlanning.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/proc/TestProcedurePlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,6 +29,7 @@
 import org.teiid.api.exception.query.QueryValidatorException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.metadata.Table.TriggerEvent;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataID;
@@ -41,8 +42,7 @@
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.validator.Validator;
 import org.teiid.query.validator.ValidatorFailure;
 import org.teiid.query.validator.ValidatorReport;
@@ -54,9 +54,9 @@
 
 	private ProcessorPlan helpPlanProcedure(String userQuery,
                                             String procedure,
-                                            String procedureType) throws TeiidComponentException,
+                                            TriggerEvent procedureType) throws TeiidComponentException,
                                                                  QueryMetadataException, TeiidProcessingException {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
 
         QueryParser parser = QueryParser.getQueryParser();
         Command userCommand = userQuery != null ? parser.parseCommand(userQuery) : parser.parseCommand(procedure);
@@ -105,7 +105,7 @@
         String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
         
 		helpPlanProcedure(userUpdateStr, procedure,
-									 FakeMetadataObject.Props.INSERT_PROCEDURE);
+									 TriggerEvent.INSERT);
     }
     
 	// special variable CHANGING used with declared variable
@@ -124,7 +124,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpPlanProcedure(userUpdateStr, procedure,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 TriggerEvent.UPDATE);
     }
     
 	// special variable CHANGING and INPUT used in conpound criteria
@@ -143,7 +143,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpPlanProcedure(userUpdateStr, procedure,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 TriggerEvent.UPDATE);
     }
     
 	// special variable CHANGING and INPUT used in conpound criteria, with declared variables
@@ -162,7 +162,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpPlanProcedure(userUpdateStr, procedure,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 TriggerEvent.UPDATE);
     }
     
 	// virtual group elements used in procedure(HAS CRITERIA)
@@ -177,7 +177,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpPlanProcedure(userUpdateStr, procedure,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 TriggerEvent.UPDATE);
     }
     
 	// virtual group elements used in procedure in if statement(HAS CRITERIA)
@@ -195,7 +195,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpPlanProcedure(userUpdateStr, procedure,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 TriggerEvent.UPDATE);
     }
     
 	// testing rows updated incremented, Input and assignment statements
@@ -210,7 +210,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
         
 		helpPlanProcedure(userUpdateStr, procedure,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 TriggerEvent.UPDATE);
     }      
     
     // testing select into with virtual group in from clause
@@ -222,7 +222,7 @@
         procedure = procedure + "END\n"; //$NON-NLS-1$
         
         helpPlanProcedure(null, procedure,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     TriggerEvent.UPDATE);
     }  
     
     // testing select into with function in select clause
@@ -234,7 +234,7 @@
         procedure = procedure + "END\n"; //$NON-NLS-1$
         
         helpPlanProcedure(null, procedure,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     TriggerEvent.UPDATE);
     }      
     
     // testing select into with function in select clause
@@ -246,7 +246,7 @@
         procedure = procedure + "END\n"; //$NON-NLS-1$
         
         helpPlanProcedure(null, procedure,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     TriggerEvent.UPDATE);
     }
     
     @Test public void testCase4504() throws Exception { 
@@ -260,7 +260,7 @@
         procedure = procedure + "END\n"; //$NON-NLS-1$ 
          
         helpPlanProcedure(null, procedure, 
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE); 
+                                     TriggerEvent.UPDATE); 
     }
 
     // =============================================================================

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,7 +36,7 @@
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestAliasGenerator {
@@ -66,13 +66,13 @@
     @Test public void testLongOrderByAlias() throws Exception {
         String sql = "select pm1.g1.e1 || pm1.g1.e2 as asfasdfadfasdfasdfadfasdfadsfasdfasdfasdfasdfasdfadfa, pm1.g1.e2 from pm1.g1 order by asfasdfadfasdfasdfadfasdfadsfasdfasdfasdfasdfasdfadfa"; //$NON-NLS-1$
         String expected = "SELECT concat(g_0.e1, g_0.e2) AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_0"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.example1Cached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testOrderBySymbolName() throws Exception {
         String sql = "select e1 from pm1.g1 order by e1"; //$NON-NLS-1$
         String expected = "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0"; //$NON-NLS-1$
-        Query command = (Query)helpTest(sql, expected, true, false, FakeMetadataFactory.example1Cached());
+        Query command = (Query)helpTest(sql, expected, true, false, RealMetadataFactory.example1Cached());
         assertEquals(command.getOrderBy().getSortKeys().get(0).getName(), "e1"); //$NON-NLS-1$
         assertEquals(command.getProjectedSymbols().get(0).getShortName(), "e1"); //$NON-NLS-1$
     }
@@ -80,14 +80,14 @@
     @Test public void testInlineViewWithSubQuery() throws Exception {
         String sql = "select intnum from (select intnum from bqt1.smallb where intnum in (select intnum a from bqt1.smalla)) b"; //$NON-NLS-1$
         String expected = "SELECT v_0.c_0 FROM (SELECT g_0.intnum AS c_0 FROM bqt1.smallb AS g_0 WHERE g_0.intnum IN (SELECT g_1.intnum FROM bqt1.smalla AS g_1)) AS v_0"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testInlineViewOrderBy() throws Exception {
         String sql = "select intnum from (select intnum from bqt1.smallb) b order by b.intnum"; //$NON-NLS-1$
         String expected = "SELECT v_0.c_0 FROM (SELECT g_0.intnum AS c_0 FROM bqt1.smallb AS g_0) AS v_0 ORDER BY c_0"; //$NON-NLS-1$
-        Command command = helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
-        LanguageBridgeFactory lbf = new LanguageBridgeFactory(FakeMetadataFactory.exampleBQTCached());
+        Command command = helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
+        LanguageBridgeFactory lbf = new LanguageBridgeFactory(RealMetadataFactory.exampleBQTCached());
         org.teiid.language.Command c = lbf.translate(command);
         assertEquals("SELECT v_0.c_0 FROM (SELECT g_0.IntNum AS c_0 FROM SmallB AS g_0) AS v_0 ORDER BY v_0.c_0", c.toString());
     }
@@ -95,74 +95,74 @@
     @Test public void testNestedInlineViewOrderBy() throws Exception {
         String sql = "select x from (select intnum x from (select intnum from bqt1.smallb) b order by x) y order by x"; //$NON-NLS-1$
         String expected = "SELECT v_1.c_0 FROM (SELECT v_0.c_0 FROM (SELECT g_0.intnum AS c_0 FROM bqt1.smallb AS g_0) AS v_0) AS v_1 ORDER BY c_0"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testInlineViewWithOnClause() throws Exception {
         String sql = "select abcd.efg from (select intkey as efg from bqt1.smalla) abcd inner join (select intnum from bqt1.smallb) b on (b.intnum = abcd.efg)"; //$NON-NLS-1$
         String expected = "SELECT v_0.c_0 FROM (SELECT g_0.intkey AS c_0 FROM bqt1.smalla AS g_0) AS v_0 INNER JOIN (SELECT g_1.intnum AS c_0 FROM bqt1.smallb AS g_1) AS v_1 ON v_1.c_0 = v_0.c_0"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
     }
 
     @Test public void testUnionOrderBy() throws Exception {
         String sql = "select e1, e2 as c_0 from pm1.g1 union all select 1, e1 from pm1.g2 order by e1"; //$NON-NLS-1$
         String expected = "SELECT g_1.e1 AS c_0, g_1.e2 AS c_1 FROM pm1.g1 AS g_1 UNION ALL SELECT '1' AS c_0, g_0.e1 AS c_1 FROM pm1.g2 AS g_0 ORDER BY c_0"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.example1Cached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testDuplicateShortElementName() throws Exception {
     	String sql = "select pm1.g1.e1, pm1.g2.e1 from pm1.g1, pm1.g2 order by pm1.g1.e1, pm1.g2.e1"; //$NON-NLS-1$
         String expected = "SELECT g_0.e1 AS c_0, g_1.e1 AS c_1 FROM pm1.g1 AS g_0, pm1.g2 AS g_1 ORDER BY c_0, c_1"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.example1Cached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testCorrelatedRefernce() throws Exception {
     	String sql = "select intnum, stringnum from (select intnum, stringnum from bqt1.smallb) b where intnum in (select b.stringnum || b.intnum from (select intnum from bqt1.smalla) b) "; //$NON-NLS-1$
         String expected = "SELECT v_0.c_0, v_0.c_1 FROM (SELECT g_0.intnum AS c_0, g_0.stringnum AS c_1 FROM bqt1.smallb AS g_0) AS v_0 WHERE v_0.c_0 IN (SELECT concat(v_0.c_1, v_1.c_0) FROM (SELECT g_1.intnum AS c_0 FROM bqt1.smalla AS g_1) AS v_1)"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
     }
 
     @Test public void testCorrelatedRefernce1() throws Exception {
     	String sql = "select intnum, stringnum from bqt1.smallb where intnum in (select stringnum || b.intnum from (select intnum from bqt1.smalla) b) "; //$NON-NLS-1$
         String expected = "SELECT g_0.intnum, g_0.stringnum FROM bqt1.smallb AS g_0 WHERE g_0.intnum IN (SELECT concat(g_0.stringnum, v_0.c_0) FROM (SELECT g_1.intnum AS c_0 FROM bqt1.smalla AS g_1) AS v_0)"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testGroupAliasNotSupported() throws Exception {
     	String sql = "select b.intkey from bqt1.smalla b"; //$NON-NLS-1$
         String expected = "SELECT bqt1.smalla.intkey FROM bqt1.smalla"; //$NON-NLS-1$
-        helpTest(sql, expected, false, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, false, false, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testUnionAliasing() throws Exception {
     	String sql = "SELECT IntKey FROM BQT1.SmallA UNION ALL SELECT IntNum FROM BQT1.SmallA"; //$NON-NLS-1$
         String expected = "SELECT BQT1.SmallA.IntKey AS c_0 FROM BQT1.SmallA UNION ALL SELECT BQT1.SmallA.IntNum AS c_0 FROM BQT1.SmallA"; //$NON-NLS-1$
-        helpTest(sql, expected, false, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, false, false, RealMetadataFactory.exampleBQTCached());
     }
 
     @Test public void testUnrelatedOrderBy() throws Exception {
     	String sql = "SELECT b.IntKey FROM BQT1.SmallA a, BQT1.SmallA b ORDER BY a.StringKey"; //$NON-NLS-1$
         String expected = "SELECT g_1.IntKey AS c_0 FROM BQT1.SmallA AS g_0, BQT1.SmallA AS g_1 ORDER BY g_0.StringKey"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testUnrelatedOrderBy1() throws Exception {
     	String sql = "SELECT b.IntKey FROM (select intkey, stringkey from BQT1.SmallA) a, (select intkey, stringkey from BQT1.SmallA) b ORDER BY a.StringKey"; //$NON-NLS-1$
         String expected = "SELECT v_1.c_0 FROM (SELECT g_0.intkey AS c_0, g_0.stringkey AS c_1 FROM BQT1.SmallA AS g_0) AS v_0, (SELECT g_1.intkey AS c_0, g_1.stringkey AS c_1 FROM BQT1.SmallA AS g_1) AS v_1 ORDER BY v_0.c_1"; //$NON-NLS-1$
-        helpTest(sql, expected, true, false, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, false, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testStripAliases() throws Exception {
     	String sql = "select intkey as a, stringkey as b from BQT1.SmallA ORDER BY a, b"; //$NON-NLS-1$
         String expected = "SELECT g_0.intkey, g_0.stringkey FROM BQT1.SmallA AS g_0 ORDER BY g_0.intkey, g_0.stringkey"; //$NON-NLS-1$
-        helpTest(sql, expected, true, true, FakeMetadataFactory.exampleBQTCached());
+        helpTest(sql, expected, true, true, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testStripAliases1() throws Exception {
     	String sql = "select intkey as a, stringkey as b from BQT1.SmallA ORDER BY a, b"; //$NON-NLS-1$
         String expected = "SELECT BQT1.SmallA.intkey, BQT1.SmallA.stringkey FROM BQT1.SmallA ORDER BY BQT1.SmallA.intkey, BQT1.SmallA.stringkey"; //$NON-NLS-1$
-        Command command = helpTest(sql, expected, false, true, FakeMetadataFactory.exampleBQTCached());
-        LanguageBridgeFactory lbf = new LanguageBridgeFactory(FakeMetadataFactory.exampleBQTCached());
+        Command command = helpTest(sql, expected, false, true, RealMetadataFactory.exampleBQTCached());
+        LanguageBridgeFactory lbf = new LanguageBridgeFactory(RealMetadataFactory.exampleBQTCached());
         org.teiid.language.Command c = lbf.translate(command);
         assertEquals("SELECT SmallA.IntKey, SmallA.StringKey FROM SmallA ORDER BY SmallA.IntKey, SmallA.StringKey", c.toString());
     }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/optimizer/relational/TestAliasGenerator.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCalculateCostUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -31,7 +31,9 @@
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.metadata.Column;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.optimizer.relational.RelationalPlanner;
@@ -45,8 +47,7 @@
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 @SuppressWarnings("nls")
@@ -94,21 +95,21 @@
     // =====================================================================
     
     @Test public void testEstimateCostOfCriteria() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 = '3' or pm2.g3.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
     }
 
     @Test public void testEstimateCostOfCompareCriteria() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 = '3'"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);    
     }  
     
     @Test public void testEstimateCostOfCompareCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 < '3'"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);    
@@ -119,7 +120,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfMatchCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 LIKE '#%'"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 100, metadata);
@@ -130,7 +131,7 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfMatchCriteria2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 NOT LIKE '#_'"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 233, metadata);
@@ -141,7 +142,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfMatchCriteria3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 LIKE '#_'"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 50, metadata);
@@ -152,7 +153,7 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfMatchCriteria4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 NOT LIKE '#_'"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 249, metadata);
@@ -163,7 +164,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfIsNullCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 IS NULL"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 33, metadata);
@@ -174,7 +175,7 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfIsNullCriteria2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 IS NOT NULL"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 266, metadata);
@@ -185,7 +186,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfIsNullCriteria3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 IS NULL"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 1, metadata);
@@ -196,7 +197,7 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfIsNullCriteria4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 IS NOT NULL"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 299, metadata);
@@ -208,7 +209,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfSetCriteria1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -220,7 +221,7 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfSetCriteria2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -232,7 +233,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfSetCriteria3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 66, metadata);
@@ -244,7 +245,7 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfSetCriteria4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 300, 233, metadata);
@@ -256,7 +257,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfSetCriteria5() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -268,7 +269,7 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfSetCriteria6() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -280,7 +281,7 @@
      * NOT = false
      */
     @Test public void testEstimateCostOfSetCriteria7() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 200, 2, metadata);
@@ -292,14 +293,14 @@
      * NOT = true
      */
     @Test public void testEstimateCostOfSetCriteria8() throws Exception{
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm1.g1.e1 NOT IN ('2', '3')"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 200, 198, metadata);
     }
     
     @Test public void testEstimateJoinNodeCost() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, JoinType.JOIN_CROSS);
         
         float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
@@ -308,7 +309,7 @@
     
     @Ignore("this logic needs to be refined to work better")
     @Test public void testEstimateJoinNodeCostOneUnknown() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         PlanNode joinNode = helpGetJoinNode(NewCalculateCostUtil.UNKNOWN_VALUE, 500, JoinType.JOIN_INNER);
         joinNode.setProperty(NodeConstants.Info.JOIN_CRITERIA, Arrays.asList(helpGetCriteria("pm1.g1.e1 = pm1.g2.e1", metadata)));
         float cost = NewCalculateCostUtil.computeCostForTree(joinNode, metadata);
@@ -327,7 +328,7 @@
      * e1 and e2 make up a single compound key 
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 = '3' and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
@@ -340,7 +341,7 @@
      * predicted to reduce the cost of the join
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 = '3' or pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -353,7 +354,7 @@
      * lower the cost due to the NOT
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 = '3' and not pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -366,7 +367,7 @@
      * lower the cost due to the 0R
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey4() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "(pm4.g1.e1 = '3' or pm4.g1.e4 = 2.0) and not pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -379,7 +380,7 @@
      * lower the cost due to the OR
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey5() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "(pm4.g1.e1 = '3' or pm4.g1.e4 = 2.0) and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -392,7 +393,7 @@
      * lower the cost due to the OR
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey6() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "(pm4.g1.e1 = '3' and pm4.g1.e2 = 2) or pm4.g1.e4 = 2.0"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -405,7 +406,7 @@
      * key so the cost should be low
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey8() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 LIKE '3%' and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
@@ -418,7 +419,7 @@
      * lower the cost due to the NOT
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey9() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 NOT LIKE '3%' and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -431,7 +432,7 @@
      * key so the cost should be low
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey10() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "'3' LIKE pm4.g1.e1 and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
@@ -444,7 +445,7 @@
      * key so the cost should be low
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey11() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 IS NULL and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
@@ -457,7 +458,7 @@
      * lower the cost due to the NOT
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey12() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 IS NOT NULL and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -470,7 +471,7 @@
      * key so the cost should be low
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey13() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 IN ('3', '4') and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
@@ -483,14 +484,14 @@
      * lower the cost due to the NOT
      */
     @Test public void testEstimateCostOfCriteriaCompoundKey14() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 NOT IN ('3', '4') and pm4.g1.e2 = 2"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
     } 
     
     @Test public void testEstimateCostOfCriteriaCompoundKey15() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "(pm4.g1.e1 = '3' or pm4.g1.e1 = '2') and (pm4.g1.e2 = 2 or pm4.g1.e2 = 1)"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, 1, metadata);
@@ -500,7 +501,7 @@
      *  usesKey true
      */
     @Test public void testEstimateCostOfCriteriaMultiGroup() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -510,7 +511,7 @@
      *  usesKey false
      */
     @Test public void testEstimateCostOfCriteriaMultiGroup1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, NewCalculateCostUtil.UNKNOWN_VALUE, NewCalculateCostUtil.UNKNOWN_VALUE, metadata);
@@ -520,7 +521,7 @@
      *  usesKey true
      */
     @Test public void testEstimateCostOfCriteriaMultiGroup2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm4.g1.e1 = pm1.g1.e1"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 10, metadata);
@@ -530,7 +531,7 @@
      *  usesKey false
      */
     @Test public void testEstimateCostOfCriteriaMultiGroup3() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example4();
+        QueryMetadataInterface metadata = RealMetadataFactory.example4();
         String critString = "pm2.g3.e1 = pm4.g1.e1"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 33, metadata);
@@ -541,10 +542,10 @@
      *  the valid strings are timestamp format - since that is what our costing sets them as.
      */
     @Test public void testEstimateCostOfCriteriaDate1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e2 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03 12:12:12.10"); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Column e2 = metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
+        e2.setMinimumValue("2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        e2.setMaximumValue("2007-06-03 12:12:12.10"); //$NON-NLS-1$
         String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 100, metadata);
@@ -555,10 +556,10 @@
      *  one example of invalid strings is date format - since our costing sets them to timestamp.
      */
     @Test public void testEstimateCostOfCriteriaDate2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e2 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03"); //$NON-NLS-1$
-        e2.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03"); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Column e2 = metadata.getElementID("pm3.g1.e2"); //$NON-NLS-1$
+        e2.setMinimumValue("2007-04-03"); //$NON-NLS-1$
+        e2.setMaximumValue("2007-06-03"); //$NON-NLS-1$
         String critString = "pm3.g1.e2 <= {d'2008-04-03'}"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 33, metadata);
@@ -568,10 +569,10 @@
      *  Time Criteria - case using valid max and min time strings.
      */
     @Test public void testEstimateCostOfCriteriaTime1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e3 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MIN_VALUE,"12:12:12"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MAX_VALUE,"12:13:14"); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Column e3 = metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
+        e3.setMinimumValue("12:12:12"); //$NON-NLS-1$
+        e3.setMaximumValue("12:13:14"); //$NON-NLS-1$
         String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 1, metadata);
@@ -581,10 +582,10 @@
      *  Time Criteria - case using invalid max and min time strings
      */
     @Test public void testEstimateCostOfCriteriaTime2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e3 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
-        e3.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03 12:12:12.10"); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Column e3 = metadata.getElementID("pm3.g1.e3"); //$NON-NLS-1$
+        e3.setMinimumValue("2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        e3.setMaximumValue("2007-06-03 12:12:12.10"); //$NON-NLS-1$
         String critString = "pm3.g1.e3 <= {t'11:11:11'}"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 33, metadata);
@@ -594,10 +595,10 @@
      *  Timestamp Criteria - case using valid max and min timestamp strings
      */
     @Test public void testEstimateCostOfCriteriaTimestamp1() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e4 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Column e4 = metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
+        e4.setMinimumValue("2007-04-03 12:12:12.10"); //$NON-NLS-1$
+        e4.setMaximumValue("2007-04-03 12:12:12.10"); //$NON-NLS-1$
         String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 1, metadata);
@@ -607,10 +608,10 @@
      *  Timestamp Criteria - case using invalid max and min timestamp strings
      */
     @Test public void testEstimateCostOfCriteriaTimestamp2() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e4 = (FakeMetadataObject)metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MIN_VALUE,"2007-04-03"); //$NON-NLS-1$
-        e4.putProperty(FakeMetadataObject.Props.MAX_VALUE,"2007-06-03"); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Column e4 = metadata.getElementID("pm3.g1.e4"); //$NON-NLS-1$
+        e4.setMinimumValue("2007-04-03"); //$NON-NLS-1$
+        e4.setMaximumValue("2007-06-03"); //$NON-NLS-1$
         String critString = "pm3.g1.e4 <= {ts'2007-04-03 12:12:12.10'}"; //$NON-NLS-1$
         
         helpTestEstimateCost(critString, 100, 33, metadata);
@@ -739,7 +740,7 @@
     @Test public void testLimitWithUnknownChildCardinality() throws Exception {
         String query = "select e1 from pm1.g1 limit 2"; //$NON-NLS-1$
         
-        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, FakeMetadataFactory.example1Cached(), new String[] {"SELECT e1 FROM pm1.g1"}); //$NON-NLS-1$
+        RelationalPlan plan = (RelationalPlan)TestOptimizer.helpPlan(query, RealMetadataFactory.example1Cached(), new String[] {"SELECT e1 FROM pm1.g1"}); //$NON-NLS-1$
         
         assertEquals(new Float(2), plan.getRootNode().getEstimateNodeCardinality());
     }

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCapabilitiesUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,15 +22,18 @@
 
 package org.teiid.query.optimizer.relational.rules;
 
+import static org.junit.Assert.*;
+
 import java.util.ArrayList;
 import java.util.List;
 
-import junit.framework.TestCase;
-
+import org.junit.Test;
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.language.SQLConstants.NonReserved;
+import org.teiid.metadata.Schema;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
@@ -45,27 +48,18 @@
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 /**
  */
-public class TestCapabilitiesUtil extends TestCase {
+ at SuppressWarnings("nls")
+public class TestCapabilitiesUtil {
 
-    /**
-     * Constructor for TestCapabilitiesUtil.
-     * @param name
-     */
-    public TestCapabilitiesUtil(String name) {
-        super(name);
-    }
-    
     public void helpTestSupportsSelfJoin(boolean supportsSelfJoin, boolean supportsGroupAlias, boolean expectedValue) throws QueryMetadataException, TeiidComponentException {
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -79,22 +73,22 @@
         assertEquals("Got wrong answer for supports", expectedValue, actual); //$NON-NLS-1$
     }
     
-    public void testSupportsSelfJoin1() throws Exception {
+    @Test public void testSupportsSelfJoin1() throws Exception {
         helpTestSupportsSelfJoin(false, true, false);
     }
 
-    public void testSupportsSelfJoin2() throws Exception {
+    @Test public void testSupportsSelfJoin2() throws Exception {
         helpTestSupportsSelfJoin(true, false, false);
     }
 
-    public void testSupportsSelfJoin3() throws Exception {
+    @Test public void testSupportsSelfJoin3() throws Exception {
         helpTestSupportsSelfJoin(true, true, true);
     }
 
-    public void testSupportsSelfJoin4() throws Exception {        
+    @Test public void testSupportsSelfJoin4() throws Exception {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
         
         // Test capabilities util
         boolean actual = CapabilitiesUtil.supportsSelfJoins(modelID, metadata, new DefaultCapabilitiesFinder());
@@ -104,8 +98,8 @@
     
     public void helpTestSupportsOuterJoin(boolean capsSupportsOuterJoin, boolean capsSupportsFullOuterJoin, JoinType joinType, boolean expectedValue) throws QueryMetadataException, TeiidComponentException {
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
         
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -120,29 +114,29 @@
     }
     
     // Test where capabilities don't support outer joins
-    public void testSupportsOuterJoinFail1() throws Exception {        
+    @Test public void testSupportsOuterJoinFail1() throws Exception {        
         helpTestSupportsOuterJoin(false, false, JoinType.JOIN_RIGHT_OUTER, false); 
     }
 
     // Test where capabilities don't support full outer joins 
-    public void testSupportsOuterJoinFail3() throws Exception {        
+    @Test public void testSupportsOuterJoinFail3() throws Exception {        
         helpTestSupportsOuterJoin(true, false, JoinType.JOIN_FULL_OUTER, false); 
     }
 
     // Test where capabilities support outer joins 
-    public void testSupportsOuterJoin1() throws Exception {        
+    @Test public void testSupportsOuterJoin1() throws Exception {        
         helpTestSupportsOuterJoin(true, false, JoinType.JOIN_RIGHT_OUTER, true); 
     }
 
     // Test where capabilities support full outer joins 
-    public void testSupportsOuterJoin2() throws Exception {        
+    @Test public void testSupportsOuterJoin2() throws Exception {        
         helpTestSupportsOuterJoin(true, true, JoinType.JOIN_FULL_OUTER, true); 
     }
 
     public void helpTestSupportsAggregates(boolean capsSupportsAggregates, boolean supportsFunctionInGroupBy, List groupCols) throws QueryMetadataException, TeiidComponentException {
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
         
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -157,7 +151,7 @@
     }
     
     // Test where capabilities supports aggregates
-    public void testSupportsAggregates1() throws Exception {        
+    @Test public void testSupportsAggregates1() throws Exception {        
         helpTestSupportsAggregates(true, true, null); 
     }
         
@@ -166,7 +160,7 @@
      * be called supports expression in group by.  Thus the example below
      * is not supported.
      */
-    public void testSupportsFunctionInGroupBy() throws Exception {
+    @Test public void testSupportsFunctionInGroupBy() throws Exception {
         Function f = new Function("concat", new Expression[] { new Constant("a"), new Constant("b") }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
         ExpressionSymbol expr = new ExpressionSymbol("e", f); //$NON-NLS-1$
         List cols = new ArrayList();
@@ -176,8 +170,8 @@
 
     public void helpTestSupportsAggregateFunction(SourceCapabilities caps, AggregateSymbol aggregate, boolean expectedValue) throws QueryMetadataException, TeiidComponentException {
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
         
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -189,7 +183,7 @@
     }
     
     // Test where capabilities don't support aggregate functions
-    public void testSupportsAggregate1() throws Exception {        
+    @Test public void testSupportsAggregate1() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);
         
@@ -199,7 +193,7 @@
     }    
     
     // Test where capabilities don't support COUNT
-    public void testSupportsAggregate2() throws Exception {        
+    @Test public void testSupportsAggregate2() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
@@ -211,7 +205,7 @@
     }    
 
     // Test where capabilities support only COUNT(*)
-    public void testSupportsAggregate3() throws Exception {        
+    @Test public void testSupportsAggregate3() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
@@ -223,7 +217,7 @@
     }    
 
     // Test where capabilities support only COUNT(*)
-    public void testSupportsAggregate4() throws Exception {        
+    @Test public void testSupportsAggregate4() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, false);
@@ -235,7 +229,7 @@
     }    
 
     // Test where capabilities support only COUNT
-    public void testSupportsAggregate5() throws Exception {        
+    @Test public void testSupportsAggregate5() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
@@ -247,7 +241,7 @@
     }    
 
     // Test where capabilities support only COUNT
-    public void testSupportsAggregate6() throws Exception {        
+    @Test public void testSupportsAggregate6() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true);
@@ -259,7 +253,7 @@
     }    
 
     // Test where capabilities don't support SUM
-    public void testSupportsAggregate7() throws Exception {        
+    @Test public void testSupportsAggregate7() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, false);
@@ -270,7 +264,7 @@
     }    
 
     // Test where capabilities support SUM
-    public void testSupportsAggregate8() throws Exception {        
+    @Test public void testSupportsAggregate8() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
@@ -281,7 +275,7 @@
     }    
 
     // Test where capabilities don't support AVG
-    public void testSupportsAggregate9() throws Exception {        
+    @Test public void testSupportsAggregate9() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, false);
@@ -292,7 +286,7 @@
     }    
 
     // Test where capabilities support AVG
-    public void testSupportsAggregate10() throws Exception {        
+    @Test public void testSupportsAggregate10() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_AVG, true);
@@ -303,7 +297,7 @@
     }    
 
     // Test where capabilities don't support MIN
-    public void testSupportsAggregate11() throws Exception {        
+    @Test public void testSupportsAggregate11() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, false);
@@ -314,7 +308,7 @@
     }    
 
     // Test where capabilities support MIN
-    public void testSupportsAggregate12() throws Exception {        
+    @Test public void testSupportsAggregate12() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MIN, true);
@@ -325,7 +319,7 @@
     }    
 
     // Test where capabilities don't support MAX
-    public void testSupportsAggregate13() throws Exception {        
+    @Test public void testSupportsAggregate13() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, false);
@@ -336,7 +330,7 @@
     }    
 
     // Test where capabilities support MAX
-    public void testSupportsAggregate14() throws Exception {        
+    @Test public void testSupportsAggregate14() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
@@ -347,7 +341,7 @@
     }    
     
     // Test where capabilities don't support DISTINCT
-    public void testSupportsAggregate15() throws Exception {        
+    @Test public void testSupportsAggregate15() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
@@ -359,7 +353,7 @@
     }    
 
     // Test where capabilities support DISTINCT
-    public void testSupportsAggregate16() throws Exception {        
+    @Test public void testSupportsAggregate16() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true);
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
@@ -372,8 +366,8 @@
 
     public void helpTestSupportsScalar(SourceCapabilities caps, Function function, boolean expectedValue) throws QueryMetadataException, TeiidComponentException, QueryResolverException {
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
         
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -385,7 +379,7 @@
     }
 
     // Test where capabilities don't support scalar functions
-    public void testSupportsScalar1() throws Exception {        
+    @Test public void testSupportsScalar1() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
 
         Function func = new Function("+", new Expression[] { new Constant(1), new Constant(2) }); //$NON-NLS-1$
@@ -393,7 +387,7 @@
     }    
 
     // Test where capabilities doesn't support function
-    public void testSupportsScalar3() throws Exception {        
+    @Test public void testSupportsScalar3() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setFunctionSupport("now", false); //$NON-NLS-1$
 
@@ -402,7 +396,7 @@
     }    
 
     // Test where capabilities do support function
-    public void testSupportsScalar4() throws Exception {        
+    @Test public void testSupportsScalar4() throws Exception {        
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setFunctionSupport("now", true); //$NON-NLS-1$
 
@@ -410,10 +404,10 @@
         helpTestSupportsScalar(caps, func, true);        
     }    
 
-    public void testSupportsDistinct1() throws Exception {        
+    @Test public void testSupportsDistinct1() throws Exception {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -424,10 +418,10 @@
         assertTrue(CapabilitiesUtil.supportsSelectDistinct(modelID, metadata, finder));
     }    
 
-    public void testSupportsDistinct2() throws Exception {        
+    @Test public void testSupportsDistinct2() throws Exception {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -440,10 +434,10 @@
         assertEquals("Got wrong answer for supports", false, actual); //$NON-NLS-1$
     }    
     
-    public void testSupportsOrderBy1() throws Exception {        
+    @Test public void testSupportsOrderBy1() throws Exception {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -456,10 +450,10 @@
         assertEquals("Got wrong answer for supports", true, actual); //$NON-NLS-1$
     }    
 
-    public void testSupportsOrderBy2() throws Exception {        
+    @Test public void testSupportsOrderBy2() throws Exception {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -474,8 +468,8 @@
     
     public void helpTestSupportsUnion(boolean supports) throws QueryMetadataException, TeiidComponentException {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -488,18 +482,18 @@
         assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
     }    
     
-    public void testSupportsUnionTrue() throws Exception {
+    @Test public void testSupportsUnionTrue() throws Exception {
         helpTestSupportsUnion(true);
     }
 
-    public void testSupportsUnionFalse() throws Exception {
+    @Test public void testSupportsUnionFalse() throws Exception {
         helpTestSupportsUnion(false);
     }
 
     public void helpTestSupportsLiterals(boolean supports) throws QueryMetadataException, TeiidComponentException {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -512,18 +506,18 @@
         assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
     }    
     
-    public void testSupportsLiteralsTrue() throws Exception {
+    @Test public void testSupportsLiteralsTrue() throws Exception {
         helpTestSupportsLiterals(true);
     }
 
-    public void testSupportsLiteralsFalse() throws Exception {
+    @Test public void testSupportsLiteralsFalse() throws Exception {
         helpTestSupportsLiterals(false);
     }
 
     public void helpTtestSupportsCaseExpression(boolean supports, boolean searched) throws QueryMetadataException, TeiidComponentException {        
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
 
         // Set up capabilities
         FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
@@ -545,19 +539,19 @@
         assertEquals("Got wrong answer for supports", supports, actual); //$NON-NLS-1$
     }    
     
-    public void testSupportsCaseTrue() throws Exception {
+    @Test public void testSupportsCaseTrue() throws Exception {
         helpTtestSupportsCaseExpression(true, false);
     }
 
-    public void testSupportsCaseFalse() throws Exception {
+    @Test public void testSupportsCaseFalse() throws Exception {
         helpTtestSupportsCaseExpression(false, false);
     }
 
-    public void testSupportsSearchedCaseTrue() throws Exception {
+    @Test public void testSupportsSearchedCaseTrue() throws Exception {
         helpTtestSupportsCaseExpression(true, true);
     }
 
-    public void testSupportsSearchedCaseFalse() throws Exception {
+    @Test public void testSupportsSearchedCaseFalse() throws Exception {
         helpTtestSupportsCaseExpression(false, true);
     }
     
@@ -570,10 +564,10 @@
         return finder;
     }
 
-    public void testSupportRowLimit() throws Exception {
+    @Test public void testSupportRowLimit() throws Exception {
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
         // Set up capabilities
         FakeCapabilitiesFinder finder = getFinder(Capability.ROW_LIMIT, false);
         // Test capabilities util
@@ -584,10 +578,10 @@
         assertEquals(true, CapabilitiesUtil.supportsRowLimit(modelID, metadata, finder));
     }
     
-    public void testSupportRowOffset() throws Exception {
+    @Test public void testSupportRowOffset() throws Exception {
         // Set up metadata
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
         // Set up capabilities
         FakeCapabilitiesFinder finder = getFinder(Capability.ROW_OFFSET, false);
         // Test capabilities util

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestCriteriaCapabilityValidatorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,30 +22,32 @@
 
 package org.teiid.query.optimizer.relational.rules;
 
+import static org.junit.Assert.*;
+
 import org.junit.Test;
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.core.TeiidException;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Column.SearchType;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.optimizer.relational.rules.CriteriaCapabilityValidatorVisitor;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Criteria;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 
-import static org.junit.Assert.*;
 
-
 /**
  */
+ at SuppressWarnings("nls")
 public class TestCriteriaCapabilityValidatorVisitor {
 
-    public void helpTestVisitor(String sql, Object modelID, FakeMetadataFacade metadata, CapabilitiesFinder capFinder, boolean isValid, boolean expectException) {
+    public void helpTestVisitor(String sql, Object modelID, TransformationMetadata metadata, CapabilitiesFinder capFinder, boolean isValid, boolean expectException) throws Exception {
         try {
             Criteria criteria = QueryParser.getQueryParser().parseCriteria(sql);
             
@@ -56,13 +58,11 @@
         	if (!expectException) {
         		throw new RuntimeException(e);
         	}
-        } catch(TeiidException e) {
-        	throw new RuntimeException(e);
         }
     }
 
     // Assume there is a wrapped command - this will allow subqueries to be properly resolved
-    public void helpTestVisitorWithCommand(String sql, Object modelID, FakeMetadataFacade metadata, CapabilitiesFinder capFinder, boolean isValid, boolean expectException) {
+    public void helpTestVisitorWithCommand(String sql, Object modelID, TransformationMetadata metadata, CapabilitiesFinder capFinder, boolean isValid, boolean expectException) {
         try {
             Command command = QueryParser.getQueryParser().parseCommand(sql);
             
@@ -79,9 +79,9 @@
     }
     
     // has all capabilities
-    @Test public void testCompareCriteriaSuccess() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaSuccess() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -92,145 +92,145 @@
     }
 
     // does not have where capability
-    @Test public void testCompareCriteriaCapFail1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaCapFail1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false);         
     }
 
     // does not have = capability
-    @Test public void testCompareCriteriaOpCapFail1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaOpCapFail1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false);         
     }
     
     // does not have <> capability
-    @Test public void testCompareCriteriaOpCapFail2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaOpCapFail2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 <> 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 <> 'x'", modelID, metadata, capFinder, false, false);         
     }
 
     // does not have < capability
-    @Test public void testCompareCriteriaOpCapFail3() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaOpCapFail3() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 < 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 < 'x'", modelID, metadata, capFinder, false, false);         
     }
 
     // does not have <= capability
-    @Test public void testCompareCriteriaOpCapFail4() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaOpCapFail4() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 <= 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 <= 'x'", modelID, metadata, capFinder, false, false);         
     }
 
     // does not have > capability
-    @Test public void testCompareCriteriaOpCapFail5() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaOpCapFail5() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 > 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 > 'x'", modelID, metadata, capFinder, false, false);         
     }
 
     // does not have >= capability
-    @Test public void testCompareCriteriaOpCapFail6() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaOpCapFail6() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 >= 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 >= 'x'", modelID, metadata, capFinder, false, false);         
     }
     
     // element not searchable
-    @Test public void testCompareCriteriaSearchableFail() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject e1 = metadata.getStore().findObject("pm1.g1.e1", FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
+    @Test public void testCompareCriteriaSearchableFail() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
+        Column e1 = metadata.getElementID("pm1.g1.e1");
+        e1.setSearchType(SearchType.Like_Only);
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false);         
     }
 
     // no caps
-    @Test public void testCompareCriteriaNoCaps() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompareCriteriaNoCaps() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         
-        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, true, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x'", modelID, metadata, capFinder, true, false);         
     }
     
-    @Test public void testCompoundCriteriaAnd1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompoundCriteriaAnd1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 = 'x' AND 0 = 1", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x' AND 0 = 1", modelID, metadata, capFinder, true, false);                 
     }
 
-    @Test public void testCompoundCriteriaAnd4() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompoundCriteriaAnd4() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         
-        helpTestVisitor("pm1.g1.e1 = 'x' AND 0 = 1", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x' AND 0 = 1", modelID, metadata, capFinder, true, false);                 
     }
 
-    @Test public void testCompoundCriteriaOr1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompoundCriteriaOr1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -238,12 +238,12 @@
         caps.setCapabilitySupport(Capability.CRITERIA_OR, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 = 'x' OR 0 = 1", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x' OR 0 = 1", modelID, metadata, capFinder, true, false);                 
     }
 
-    @Test public void testCompoundCriteriaOr2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompoundCriteriaOr2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -251,134 +251,134 @@
         caps.setCapabilitySupport(Capability.CRITERIA_OR, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 = 'x' OR 0 = 1", modelID, metadata, capFinder, false, false);                 //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x' OR 0 = 1", modelID, metadata, capFinder, false, false);                 
     }
 
-    @Test public void testCompoundCriteriaOr4() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testCompoundCriteriaOr4() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         
-        helpTestVisitor("pm1.g1.e1 = 'x' OR 0 = 1", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 = 'x' OR 0 = 1", modelID, metadata, capFinder, true, false);                 
     }
 
-    @Test public void testScalarFunction1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testScalarFunction1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         caps.setFunctionSupport("curtime", true); //$NON-NLS-1$
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm1", caps); 
         
-        helpTestVisitor("curtime() = {t'10:00:00'}", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+        helpTestVisitor("curtime() = {t'10:00:00'}", modelID, metadata, capFinder, true, false); 
     }
 
     /** 
      * Since this will always get pre-evaluated, this should also be true 
      *  
      */ 
-    @Test public void testScalarFunction2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testScalarFunction2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         caps.setFunctionSupport("+", false); //$NON-NLS-1$
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm1", caps); 
         
-        helpTestVisitor("1 + 1 = 2", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+        helpTestVisitor("1 + 1 = 2", modelID, metadata, capFinder, true, false); 
     }
     
     /**
      * since curtime is command deterministic and not supported, it will be evaluated
      */
-    @Test public void testScalarFunction2a() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testScalarFunction2a() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         caps.setFunctionSupport("curtime", false); //$NON-NLS-1$
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm1", caps); 
         
-        helpTestVisitor("curtime() = '{t'10:00:00'}", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+        helpTestVisitor("curtime() = '{t'10:00:00'}", modelID, metadata, capFinder, true, false); 
     }
     
     /**
      * since rand is non-deterministic and not supported, it will be evaluated for every row
      */
-    @Test public void testScalarFunction2b() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testScalarFunction2b() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         caps.setFunctionSupport("rand", false); //$NON-NLS-1$
-        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        capFinder.addCapabilities("pm1", caps); 
         
-        helpTestVisitor("rand() = '1.0'", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+        helpTestVisitor("rand() = '1.0'", modelID, metadata, capFinder, false, false); 
     }
 
     
-    @Test public void testIsNull1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testIsNull1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_ISNULL, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, true, false); 
     }
 
-    @Test public void testIsNull2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testIsNull2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_ISNULL, false);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, false, false); 
     }
 
-    @Test public void testIsNull3() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testIsNull3() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         
-        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, true, false); 
     }
 
     /**
      * Is null is not a comparison operation
      */
-    @Test public void testIsNull4() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject e1 = metadata.getStore().findObject("pm1.g1.e1", FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
+    @Test public void testIsNull4() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
+        Column e1 = metadata.getElementID("pm1.g1.e1");
+        e1.setSearchType(SearchType.Like_Only);
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_ISNULL, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 IS NULL", modelID, metadata, capFinder, true, false); 
     }
     
-    @Test public void testIsNull6() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testIsNull6() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -386,37 +386,37 @@
         caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 IS NOT NULL", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 IS NOT NULL", modelID, metadata, capFinder, true, false); 
     }
     
-    @Test public void testIsNull6fails() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testIsNull6fails() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_ISNULL, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 IS NOT NULL", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 IS NOT NULL", modelID, metadata, capFinder, false, false); 
     }
 
     // has all capabilities
-    @Test public void testMatchCriteriaSuccess() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testMatchCriteriaSuccess() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         caps.setCapabilitySupport(Capability.CRITERIA_LIKE, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 LIKE 'x'", modelID, metadata, capFinder, true, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 LIKE 'x'", modelID, metadata, capFinder, true, false);         
     }
 
-    @Test public void testMatchCriteriaSuccess2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testMatchCriteriaSuccess2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -424,13 +424,13 @@
         caps.setCapabilitySupport(Capability.CRITERIA_LIKE_ESCAPE, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 LIKE 'x' ESCAPE '#'", modelID, metadata, capFinder, true, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 LIKE 'x' ESCAPE '#'", modelID, metadata, capFinder, true, false);         
     }
 
     // Test for NOT LIKE
-    @Test public void testMatchCriteriaSuccess3() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testMatchCriteriaSuccess3() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -438,12 +438,12 @@
         caps.setCapabilitySupport(Capability.CRITERIA_NOT, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         
-        helpTestVisitor("pm1.g1.e1 NOT LIKE 'x'", modelID, metadata, capFinder, true, false);         //$NON-NLS-1$
+        helpTestVisitor("pm1.g1.e1 NOT LIKE 'x'", modelID, metadata, capFinder, true, false);         
     }
     
-    @Test public void testMatchCriteriaSuccess3fails() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testMatchCriteriaSuccess3fails() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -454,9 +454,9 @@
     }
 
     // does not have compare capability
-    @Test public void testMatchCriteriaCapFail1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testMatchCriteriaCapFail1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -468,9 +468,9 @@
     }
 
     // does not have escape char capability
-    @Test public void testMatchCriteriaCapFail2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testMatchCriteriaCapFail2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -482,11 +482,11 @@
     }
         
     // element not searchable
-    @Test public void testMatchCriteriaMatchableFail() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject e1 = metadata.getStore().findObject("pm1.g1.e1", FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
+    @Test public void testMatchCriteriaMatchableFail() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
+        Column e1 = metadata.getElementID("pm1.g1.e1");
+        e1.setSearchType(SearchType.All_Except_Like);
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -498,18 +498,18 @@
     }
 
     // no caps
-    @Test public void testMatchCriteriaNoCaps() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testMatchCriteriaNoCaps() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         
         helpTestVisitor("pm1.g1.e1 LIKE 'x'", modelID, metadata, capFinder, true, false);         //$NON-NLS-1$
     }    
 
-    @Test public void testNotCriteria1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testNotCriteria1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -520,9 +520,9 @@
         helpTestVisitor("NOT pm1.g1.e1 = 'x'", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
     }
 
-    @Test public void testNotCriteria2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testNotCriteria2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -533,9 +533,9 @@
         helpTestVisitor("NOT pm1.g1.e1 = 'x'", modelID, metadata, capFinder, false, false);                 //$NON-NLS-1$
     }
 
-    @Test public void testSetCriteria1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSetCriteria1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -545,9 +545,9 @@
         helpTestVisitor("pm1.g1.e1 IN ('x')", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
     }
 
-    @Test public void testSetCriteria2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSetCriteria2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -557,20 +557,20 @@
         helpTestVisitor("pm1.g1.e1 IN ('x')", modelID, metadata, capFinder, false, false);                 //$NON-NLS-1$
     }
 
-    @Test public void testSetCriteria3() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSetCriteria3() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         
         helpTestVisitor("pm1.g1.e1 IN ('x')", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
     }
 
-    @Test public void testSetCriteria5() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject elementID = metadata.getStore().findObject("pm1.g1.e1" , FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        elementID.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
+    @Test public void testSetCriteria5() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
+        Column elementID = metadata.getElementID("pm1.g1.e1");
+        elementID.setSearchType(SearchType.Like_Only);
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -581,9 +581,9 @@
     }
 
     //Test for success NOT IN
-    @Test public void testSetCriteria7() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSetCriteria7() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -594,9 +594,9 @@
         helpTestVisitor("pm1.g1.e1 NOT IN ('x')", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
     }
     
-    @Test public void testSetCriteria7fails() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSetCriteria7fails() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -606,9 +606,9 @@
         helpTestVisitor("pm1.g1.e1 NOT IN ('x')", modelID, metadata, capFinder, false, false);                 //$NON-NLS-1$
     }
     
-    @Test public void testSetCriteria8() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSetCriteria8() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -619,9 +619,9 @@
         helpTestVisitor("pm1.g1.e1 IN ('x', 'y', 'z')", modelID, metadata, capFinder, false, false);                 //$NON-NLS-1$
     }
     
-    @Test public void testSetCriteria9() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSetCriteria9() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -632,9 +632,9 @@
         helpTestVisitor("pm1.g1.e1 IN ('x', 'y')", modelID, metadata, capFinder, true, false);                 //$NON-NLS-1$
     }
 
-    @Test public void testSubquerySetCriteria() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubquerySetCriteria() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -644,9 +644,9 @@
         helpTestVisitor("pm1.g1.e1 IN (SELECT 'xyz' FROM pm1.g1)", modelID, metadata, capFinder, false, false);                 //$NON-NLS-1$
     }
     
-    @Test public void testSearchCase() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSearchCase() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -658,9 +658,9 @@
     }
     
     // has all capabilities
-    @Test public void testSubqueryCompareCriteriaSuccess() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaSuccess() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -672,9 +672,9 @@
     }
 
     // does not have where capability
-    @Test public void testSubqueryCompareCriteriaCapFail1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaCapFail1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -685,9 +685,9 @@
     }
 
     // does not have compare capability
-    @Test public void testSubqueryCompareCriteriaCapFail2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaCapFail2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -698,9 +698,9 @@
     }
 
     // does not have subquery capability
-    @Test public void testSubqueryCompareCriteriaFail3() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaFail3() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -711,9 +711,9 @@
     }
 
     // does not have quantified subquery comparison capability
-    @Test public void testSubqueryCompareCriteriaFail4() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaFail4() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -726,9 +726,9 @@
     }
 
     // does not have quantified subquery comparison capability for ANY
-    @Test public void testSubqueryCompareCriteriaFail5() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaFail5() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -742,9 +742,9 @@
     }
 
     // does not have quantified subquery comparison capability for ALL
-    @Test public void testSubqueryCompareCriteriaFail6() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaFail6() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -758,9 +758,9 @@
     }
 
     // does not have = capability
-    @Test public void testSubqueryCompareCriteriaOpCapFail1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaOpCapFail1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -771,9 +771,9 @@
     }
     
     // does not have <> capability
-    @Test public void testSubqueryCompareCriteriaOpCapFail2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaOpCapFail2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -784,9 +784,9 @@
     }
 
     // does not have < capability
-    @Test public void testSubqueryCompareCriteriaOpCapFail3() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaOpCapFail3() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -797,9 +797,9 @@
     }
 
     // does not have <= capability
-    @Test public void testSubqueryCompareCriteriaOpCapFail4() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaOpCapFail4() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -810,9 +810,9 @@
     }
 
     // does not have > capability
-    @Test public void testSubqueryCompareCriteriaOpCapFail5() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaOpCapFail5() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -823,9 +823,9 @@
     }
 
     // does not have >= capability
-    @Test public void testSubqueryCompareCriteriaOpCapFail6() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testSubqueryCompareCriteriaOpCapFail6() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -836,11 +836,11 @@
     }
     
     // element not searchable
-    @Test public void testSubqueryCompareCriteriaSearchableFail() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject e1 = metadata.getStore().findObject("pm1.g1.e1", FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
+    @Test public void testSubqueryCompareCriteriaSearchableFail() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Schema modelID = metadata.getMetadataStore().getSchema("PM1");
+        Column e1 = metadata.getElementID("pm1.g1.e1");
+        e1.setSearchType(SearchType.Like_Only);
                 
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -850,9 +850,9 @@
         helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE pm1.g1.e1 = ANY (SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false);         //$NON-NLS-1$
     }
 
-    @Test public void testExistsCriteria1() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testExistsCriteria1() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -862,9 +862,9 @@
         helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS(SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, true, false); //$NON-NLS-1$
     }
 
-    @Test public void testExistsCriteria2() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testExistsCriteria2() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -874,9 +874,9 @@
         helpTestVisitorWithCommand("SELECT e1 FROM pm1.g1 WHERE EXISTS(SELECT e1 FROM pm1.g2)", modelID, metadata, capFinder, false, false); //$NON-NLS-1$
     }
 
-    @Test public void testExistsCriteria5() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-        Object modelID = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
+    @Test public void testExistsCriteria5() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1Cached();
+        Object modelID = metadata.getMetadataStore().getSchema("PM1");
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAccessPatternValidation.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,8 +40,7 @@
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 
@@ -50,7 +49,7 @@
  */
 public class TestRuleAccessPatternValidation {
 
-    private static final FakeMetadataFacade METADATA = FakeMetadataFactory.example1Cached();
+    private static final QueryMetadataInterface METADATA = RealMetadataFactory.example1Cached();
 
     private static final boolean DEBUG = false;
 

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleAssignOutputElements.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,30 +22,23 @@
 
 package org.teiid.query.optimizer.relational.rules;
 
-import org.teiid.query.optimizer.relational.plantree.*;
-import org.teiid.query.optimizer.relational.rules.RuleAssignOutputElements;
-import org.teiid.query.sql.lang.SetQuery.Operation;
+import static org.junit.Assert.*;
 
-import junit.framework.*;
-
+import org.junit.Test;
+import org.teiid.query.optimizer.relational.plantree.NodeConstants;
+import org.teiid.query.optimizer.relational.plantree.NodeFactory;
+import org.teiid.query.optimizer.relational.plantree.PlanNode;
+import org.teiid.query.sql.lang.SetQuery.Operation;
 /**
  */
-public class TestRuleAssignOutputElements extends TestCase {
+public class TestRuleAssignOutputElements {
 
-    /**
-     * Constructor for TestRuleAssignOutputElements.
-     * @param arg0
-     */
-    public TestRuleAssignOutputElements(String arg0) {
-        super(arg0);
-    }
-
     public void helpTestIsUnionNoAll(PlanNode node, boolean expected) {
         boolean actual = RuleAssignOutputElements.hasDupRemoval(node);
         assertEquals("Got incorrect answer finding no all union", expected, actual); //$NON-NLS-1$
     }
 
-    public void testFindNoAllUnion1() {
+    @Test public void testFindNoAllUnion1() {
         PlanNode projNode = NodeFactory.getNewNode(NodeConstants.Types.PROJECT);        
         PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);        
         projNode.addLastChild(accessNode);
@@ -53,7 +46,7 @@
         helpTestIsUnionNoAll(projNode, false);
     }    
 
-    public void testFindNoAllUnion2() {
+    @Test public void testFindNoAllUnion2() {
         PlanNode unionNode = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
         unionNode.setProperty(NodeConstants.Info.SET_OPERATION, Operation.UNION);
         unionNode.setProperty(NodeConstants.Info.USE_ALL, Boolean.TRUE);
@@ -70,7 +63,7 @@
         helpTestIsUnionNoAll(unionNode, false);
     }    
     
-    public void testFindNoAllUnion3() {
+    @Test public void testFindNoAllUnion3() {
         PlanNode unionNode = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
         unionNode.setProperty(NodeConstants.Info.SET_OPERATION, Operation.UNION);
         unionNode.setProperty(NodeConstants.Info.USE_ALL, Boolean.FALSE);
@@ -87,7 +80,7 @@
         helpTestIsUnionNoAll(unionNode, true);
     }    
 
-    public void testFindNoAllUnion4() {
+    @Test public void testFindNoAllUnion4() {
         PlanNode unionNode1 = NodeFactory.getNewNode(NodeConstants.Types.SET_OP);
         unionNode1.setProperty(NodeConstants.Info.SET_OPERATION, Operation.UNION);
         unionNode1.setProperty(NodeConstants.Info.USE_ALL, Boolean.TRUE);

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleChooseDependent.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -37,6 +37,7 @@
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.query.analysis.AnalysisRecord;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.relational.RuleStack;
@@ -44,6 +45,7 @@
 import org.teiid.query.optimizer.relational.plantree.NodeFactory;
 import org.teiid.query.optimizer.relational.plantree.PlanNode;
 import org.teiid.query.processor.relational.JoinNode.JoinStrategyType;
+import org.teiid.query.resolver.util.ResolverUtil;
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.CompareCriteria;
 import org.teiid.query.sql.lang.CompoundCriteria;
@@ -59,9 +61,7 @@
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 @SuppressWarnings("unchecked")
@@ -74,11 +74,11 @@
     /* Make Neither Side Dependent */
     private static final int NEITHER_SIDE = 3;
 
-    private FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+    private QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     
     // ################################## TEST HELPERS ################################
     
-    public PlanNode createAccessNode(Collection groupSymbols) {
+    public PlanNode createAccessNode(Collection groupSymbols) throws Exception {
         PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                        
         PlanNode joinNode = NodeFactory.getNewNode(NodeConstants.Types.JOIN);        
         PlanNode sourceNode = NodeFactory.getNewNode(NodeConstants.Types.SOURCE);        
@@ -97,58 +97,58 @@
         return accessNode;
     }
     
-    public GroupSymbol getVirtualGroup() { 
+    public GroupSymbol getVirtualGroup() throws Exception { 
         GroupSymbol gs = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
-        gs.setMetadataID(this.metadata.getStore().findObject("vm1.g1", FakeMetadataObject.GROUP));   //$NON-NLS-1$
+        ResolverUtil.resolveGroup(gs, metadata);
         return gs;
     }
 
-    public GroupSymbol getPhysicalGroup(int num) { 
+    public GroupSymbol getPhysicalGroup(int num) throws Exception { 
         String id = "pm1.g" + num; //$NON-NLS-1$
         GroupSymbol gs = new GroupSymbol(id);
-        gs.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.GROUP));  
+        ResolverUtil.resolveGroup(gs, metadata);
         return gs;
     }
     
-    public GroupSymbol getPhysicalGroup(int modelNum, int num) { 
+    public GroupSymbol getPhysicalGroup(int modelNum, int num) throws Exception { 
         String id = "pm" + modelNum + ".g" + num; //$NON-NLS-1$ //$NON-NLS-2$
         GroupSymbol gs = new GroupSymbol(id);
-        gs.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.GROUP));  
+        ResolverUtil.resolveGroup(gs, metadata);
         return gs;
     }    
 
-    public GroupSymbol getPhysicalGroupWithAlias(int num, String alias) { 
+    public GroupSymbol getPhysicalGroupWithAlias(int num, String alias) throws Exception { 
         String id = "pm1.g" + num; //$NON-NLS-1$
         GroupSymbol gs = new GroupSymbol(alias, id);
-        gs.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.GROUP));  
+        ResolverUtil.resolveGroup(gs, metadata);
         return gs;
     }
     
-    public ElementSymbol getElementSymbol(int groupNum, int elementNum) {
+    public ElementSymbol getElementSymbol(int groupNum, int elementNum) throws Exception {
         String id = "pm1.g" + groupNum + ".e" + elementNum; //$NON-NLS-1$ //$NON-NLS-2$
          ElementSymbol es = new ElementSymbol(id);
-         es.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.ELEMENT));
+         es.setMetadataID(this.metadata.getElementID(id));
          es.setGroupSymbol(getPhysicalGroup(groupNum));
          return es;
     }
 
-    public ElementSymbol getElementSymbol(int modelNum, int groupNum, int elementNum) {
+    public ElementSymbol getElementSymbol(int modelNum, int groupNum, int elementNum) throws Exception {
         String id = "pm" + modelNum + ".g" + groupNum + ".e" + elementNum; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
         ElementSymbol es = new ElementSymbol(id);
-        es.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.ELEMENT));
+        es.setMetadataID(this.metadata.getElementID(id));
         es.setGroupSymbol(getPhysicalGroup(modelNum, groupNum));
         return es;
     }
 
-    public ElementSymbol getElementSymbolWithGroupAlias(int groupNum, int elementNum, String alias) {
+    public ElementSymbol getElementSymbolWithGroupAlias(int groupNum, int elementNum, String alias) throws Exception {
         String id = "pm1.g" + groupNum + ".e" + elementNum; //$NON-NLS-1$ //$NON-NLS-2$
          ElementSymbol es = new ElementSymbol(id);
-         es.setMetadataID(this.metadata.getStore().findObject(id, FakeMetadataObject.ELEMENT));
+         es.setMetadataID(this.metadata.getElementID(id));
          es.setGroupSymbol(getPhysicalGroupWithAlias(groupNum, alias));
          return es;
     }
     
-    public Query createBaseQuery() {
+    public Query createBaseQuery() throws Exception {
         Query query = new Query();
         
         Select select = new Select();
@@ -404,7 +404,7 @@
     
     // ################################## ACTUAL TESTS ################################
     
-    @Test public void testValidJoin1() {
+    @Test public void testValidJoin1() throws Exception {
         PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
         accessNode.addGroup(getPhysicalGroup(1));
                         
@@ -415,7 +415,7 @@
         helpTestValidJoin(joinNode, accessNode, false);
     }
 
-    @Test public void testValidJoin2() {
+    @Test public void testValidJoin2() throws Exception {
         PlanNode accessNode = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
         accessNode.addGroup(getPhysicalGroup(1));
                         
@@ -427,7 +427,7 @@
         helpTestValidJoin(joinNode, accessNode, false);
     }
 
-    @Test public void testValidJoin3() {
+    @Test public void testValidJoin3() throws Exception {
         PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
         PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
         accessNode1.addGroup(getPhysicalGroup(1));                
@@ -444,7 +444,7 @@
         helpTestValidJoin(joinNode, accessNode1, true);
     }
 
-    @Test public void testValidJoin4() {
+    @Test public void testValidJoin4() throws Exception {
         PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
         PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
                         
@@ -459,7 +459,7 @@
         helpTestValidJoin(joinNode, accessNode2, false);
     }
 
-    @Test public void testValidJoin5() {
+    @Test public void testValidJoin5() throws Exception {
         PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
         PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
                         
@@ -474,7 +474,7 @@
         helpTestValidJoin(joinNode, accessNode1, false);
     }
 
-    @Test public void testValidJoin6() {
+    @Test public void testValidJoin6() throws Exception {
         PlanNode accessNode1 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);                       
         PlanNode accessNode2 = NodeFactory.getNewNode(NodeConstants.Types.ACCESS);
         accessNode1.addGroup(getPhysicalGroup(1));                
@@ -497,7 +497,7 @@
      */
     @Test public void testChooseKey() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(2,3);                    
         GroupSymbol group2 = getPhysicalGroup(3,3);                    
@@ -522,7 +522,7 @@
      */
     @Test public void testChooseKey2() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(2,3); //no key                 
         GroupSymbol group1a = null;                 
@@ -576,7 +576,7 @@
      */
     @Test public void testCardinality() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         GroupSymbol group2 = getPhysicalGroup(2,2);                    
@@ -607,7 +607,7 @@
      */
     @Test public void testCardinalityAndKey() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         GroupSymbol group2 = getPhysicalGroup(2,2);                    
@@ -633,7 +633,7 @@
     
     @Test public void testCardinalityAndKeyNestedLoop() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         GroupSymbol group2 = getPhysicalGroup(2,2);                    
@@ -659,7 +659,7 @@
     
     @Test public void testRejectDependentJoin() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(3,1);                    
         GroupSymbol group2 = getPhysicalGroup(3,2);                    
@@ -685,7 +685,7 @@
      */
     @Test public void testCardinalityWithKeyCrit() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -713,7 +713,7 @@
      */
     @Test public void testCardinalityWithKeyCompoundCritAND() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -745,7 +745,7 @@
      */
     @Test public void testCardinalityWithKeyCompoundCritOR() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -775,7 +775,7 @@
      */
     @Test public void testCardinalityWithKeySetCrit() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -806,7 +806,7 @@
      */
     @Test public void testCardinalityWithKeyMatchCrit() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -833,7 +833,7 @@
      */
     @Test public void testCardinalityWithKeyIsNullCrit() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -860,7 +860,7 @@
      */
     @Test public void testCardinalityWithKeyNotCrit() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -889,7 +889,7 @@
      */
     @Test public void testCardinalityWithKeyComplexCrit() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -918,7 +918,7 @@
 
     @Test public void testCardinalityWithKeyComplexCrit2() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -948,7 +948,7 @@
 
     @Test public void testCardinalityWithKeyComplexCrit3() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e2 = getElementSymbol(1,2,2);
@@ -982,7 +982,7 @@
      */
     @Test public void testCardinalityWithNonKeyCrit() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(1,2);                    
         ElementSymbol g1e1 = getElementSymbol(1,2,1);
@@ -1011,7 +1011,7 @@
      */
     @Test public void testCardinalityWithCriteriaAndJoin() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(2,2); //no key                 
         GroupSymbol group1a = null;                 
@@ -1062,7 +1062,7 @@
 
     @Test public void testCardinalityWithAtomicCrossJoin() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(2,2); //no key                 
         GroupSymbol group1a = null;                 
@@ -1108,7 +1108,7 @@
     
     @Test public void testCardinalityWithAtomicCrossJoin2() throws Exception {
         //override default metadata
-        this.metadata = FakeMetadataFactory.example4();
+        this.metadata = RealMetadataFactory.example4();
         
         GroupSymbol group1 = getPhysicalGroup(2,2); //no key                 
         GroupSymbol group1a = null;                 

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePlaceAccess.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,16 +32,16 @@
 import org.teiid.query.sql.lang.From;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.Select;
-import org.teiid.query.sql.symbol.AllSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 import junit.framework.TestCase;
 
 
 public class TestRulePlaceAccess extends TestCase {
 
-    private static final QueryMetadataInterface METADATA = FakeMetadataFactory.example1Cached();
+    private static final QueryMetadataInterface METADATA = RealMetadataFactory.example1Cached();
 
     // ################################## FRAMEWORK ################################
 
@@ -67,7 +67,7 @@
         query.setFrom(from);
         
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
 
         group.setMetadataID(METADATA.getGroupID("pm4.g2")); //$NON-NLS-1$

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRulePushSelectCriteria.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -48,7 +48,7 @@
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.util.SymbolMap;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 
@@ -67,7 +67,7 @@
     }
     
     @Test public void testPushAcrossFrameWithAccessNode() throws Exception {
-    	QueryMetadataInterface metadata = new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), new TempMetadataStore());
+    	QueryMetadataInterface metadata = new TempMetadataAdapter(RealMetadataFactory.example1Cached(), new TempMetadataStore());
     	Command command = TestOptimizer.helpGetCommand("select * from (select * from pm1.g1 union select * from pm1.g2) x where e1 = 1", metadata, null); //$NON-NLS-1$
     	Command subCommand = TestOptimizer.helpGetCommand("select * from pm1.g1 union select * from pm1.g2", metadata, null); //$NON-NLS-1$
     	RelationalPlanner p = new RelationalPlanner();

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/relational/rules/TestRuleValidateWhereAll.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,7 +32,7 @@
 import org.teiid.query.sql.lang.Insert;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 import junit.framework.TestCase;
 
@@ -70,7 +70,7 @@
     public void testDefect21982_3() {
         TestOptimizer.helpPlan(
                  "SELECT * FROM vm1.g38",   //$NON-NLS-1$
-                 FakeMetadataFactory.example1Cached(),
+                 RealMetadataFactory.example1Cached(),
                  null, getWhereAllCapabilities(),
                  new String[0],
                  false);       
@@ -79,7 +79,7 @@
     public void testWhereAll1() {
     	TestOptimizer.helpPlan(
             "SELECT * FROM pm6.g1",   //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, getWhereAllCapabilities(),
             new String[0],
             false);
@@ -88,7 +88,7 @@
     public void testWhereAll2() throws Exception {
     	TestOptimizer.helpPlan(
             "SELECT pm1.g1.e1 FROM pm1.g1, pm6.g1 WHERE pm1.g1.e1=pm6.g1.e1 OPTION MAKEDEP pm6.g1",   //$NON-NLS-1$
-            FakeMetadataFactory.example1Cached(),
+            RealMetadataFactory.example1Cached(),
             null, getWhereAllCapabilities(),
             new String[] {
                 "SELECT g_0.e1 AS c_0 FROM pm6.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0" //$NON-NLS-1$ //$NON-NLS-2$

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestMarkExcludeVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,33 +26,32 @@
 import java.io.StringWriter;
 import java.util.Collection;
 
+import junit.framework.TestCase;
+
 import org.teiid.query.mapping.xml.MappingDocument;
 import org.teiid.query.mapping.xml.MappingOutputter;
-import org.teiid.query.optimizer.xml.XMLPlanner;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.processor.xml.TestXMLProcessor;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
 
-import junit.framework.TestCase;
 
 
-
 /** 
  * 
  */
 public class TestMarkExcludeVisitor extends TestCase {
     
     void helpTest(String sql, String expected) throws Exception{
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata); 
 
-        Collection groups = GroupCollectorVisitor.getGroups(query, true);
-        GroupSymbol group = (GroupSymbol) groups.iterator().next();
+        Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(query, true);
+        GroupSymbol group = groups.iterator().next();
         
         MappingDocument docOrig = (MappingDocument)metadata.getMappingNode(metadata.getGroupID(group.getName())); 
-        MappingDocument doc = (MappingDocument)docOrig.clone(); 
+        MappingDocument doc = docOrig.clone(); 
         
         doc = XMLPlanner.preMarkExcluded(query, doc);       
         XMLPlanner.removeExcluded(doc);

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestNameInSourceResolverVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,7 +29,8 @@
 import java.util.List;
 import java.util.Map;
 
-import org.teiid.core.TeiidComponentException;
+import junit.framework.TestCase;
+
 import org.teiid.query.mapping.xml.MappingAttribute;
 import org.teiid.query.mapping.xml.MappingDocument;
 import org.teiid.query.mapping.xml.MappingElement;
@@ -38,9 +39,6 @@
 import org.teiid.query.mapping.xml.Navigator;
 import org.teiid.query.mapping.xml.ResultSetInfo;
 import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.xml.NameInSourceResolverVisitor;
-import org.teiid.query.optimizer.xml.SourceNodeGenaratorVisitor;
-import org.teiid.query.optimizer.xml.XMLPlannerEnvironment;
 import org.teiid.query.processor.xml.TestXMLProcessor;
 import org.teiid.query.sql.LanguageVisitor;
 import org.teiid.query.sql.lang.Command;
@@ -48,12 +46,9 @@
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
 
-import junit.framework.TestCase;
 
 
-
 /** 
  * 
  */
@@ -61,14 +56,14 @@
     static HashMap infos = new HashMap();
     
     XMLPlannerEnvironment getEnv(String sql) throws Exception{
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         Query query = (Query)TestXMLProcessor.helpGetCommand(sql, metadata); 
 
-        Collection groups = GroupCollectorVisitor.getGroups(query, true);
-        GroupSymbol group = (GroupSymbol) groups.iterator().next();
+        Collection<GroupSymbol> groups = GroupCollectorVisitor.getGroups(query, true);
+        GroupSymbol group = groups.iterator().next();
         
         MappingDocument docOrig = (MappingDocument)metadata.getMappingNode(metadata.getGroupID(group.getName())); 
-        MappingDocument doc = (MappingDocument)docOrig.clone(); 
+        MappingDocument doc = docOrig.clone(); 
 
         XMLPlannerEnvironment env = new XMLPlannerEnvironment(metadata);
         env.mappingDoc = doc;

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLNodeMappingVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,23 +22,21 @@
 
 package org.teiid.query.optimizer.xml;
 
+import junit.framework.TestCase;
+
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.query.mapping.xml.MappingDocument;
 import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.optimizer.xml.SourceNodeGenaratorVisitor;
-import org.teiid.query.optimizer.xml.XMLNodeMappingVisitor;
 import org.teiid.query.processor.xml.TestXMLProcessor;
+import org.teiid.query.resolver.util.ResolverVisitor;
 import org.teiid.query.sql.lang.CompareCriteria;
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
 
-import junit.framework.TestCase;
 
-
 /**
  */
 public class TestXMLNodeMappingVisitor extends TestCase {
@@ -59,19 +57,17 @@
 	}	
 			
 	public void testMappingCriteria() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata();
 
         GroupSymbol doc = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         doc.setMetadataID(metadata.getGroupID(doc.getName()));
             
-
         MappingDocument mappingDoc = (MappingDocument)metadata.getMappingNode(doc.getMetadataID());
         mappingDoc = SourceNodeGenaratorVisitor.extractSourceNodes(mappingDoc);
     
 		// Create criteria
-       	ElementSymbol es = new ElementSymbol("Catalogs.Catalog.Items.Item.Name"); //$NON-NLS-1$
-        es.setGroupSymbol(doc);
-        es.setMetadataID(metadata.getElementID("xmltest.doc1.Catalogs.Catalog.Items.Item.Name")); //$NON-NLS-1$
+       	ElementSymbol es = new ElementSymbol("Catalogs.Catalog.Items.Item.Name", null, doc); //$NON-NLS-1$
+        ResolverVisitor.resolveLanguageObject(es, metadata);
 		CompareCriteria crit = new CompareCriteria(es, CompareCriteria.EQ, new Constant("abc")); //$NON-NLS-1$
 	
 		helpTestMapping(crit, "xmltest.\"group\".items.itemName = 'abc'", mappingDoc, metadata); //$NON-NLS-1$

Modified: branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/optimizer/xml/TestXMLPlanner.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,16 +22,18 @@
 
 package org.teiid.query.optimizer.xml;
 
-import java.util.ArrayList;
-import java.util.List;
+import static org.junit.Assert.*;
 
+import org.junit.Test;
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryPlannerException;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.id.IDGenerator;
-import org.teiid.core.id.IntegerIDFactory;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.mapping.xml.MappingAttribute;
@@ -40,11 +42,9 @@
 import org.teiid.query.mapping.xml.MappingSequenceNode;
 import org.teiid.query.mapping.xml.Namespace;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
-import org.teiid.query.optimizer.xml.CriteriaPlanner;
-import org.teiid.query.optimizer.xml.XMLPlanner;
-import org.teiid.query.optimizer.xml.XMLPlannerEnvironment;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.processor.xml.BlockInstruction;
 import org.teiid.query.processor.xml.EndBlockInstruction;
@@ -58,23 +58,12 @@
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Query;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
-import junit.framework.TestCase;
+ at SuppressWarnings("nls")
+public class TestXMLPlanner {
 
-
-public class TestXMLPlanner extends TestCase {
-
-    // ################################## FRAMEWORK ################################
-
-    public TestXMLPlanner(String name) {
-        super(name);
-    }
-
     // ################################## TEST HELPERS ################################
 
     public static XMLPlan helpPlan(String sql, QueryMetadataInterface md) throws Exception {
@@ -93,26 +82,21 @@
         } 
     }
 
-    public static FakeMetadataFacade example1() {
+    public static TransformationMetadata example1() {
+    	MetadataStore metadataStore = new MetadataStore();
         // Create models
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject vm1 = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        Schema vm1 = RealMetadataFactory.createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
 
         // Create physical groups
-        FakeMetadataObject pm1g1 =
-            FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g2 =
-            FakeMetadataFactory.createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g3 =
-            FakeMetadataFactory.createPhysicalGroup("pm1.g3", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g4 =
-            FakeMetadataFactory.createPhysicalGroup("pm1.g4", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g5 =
-            FakeMetadataFactory.createPhysicalGroup("pm1.g5", pm1); //$NON-NLS-1$
+        Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+        Table pm1g2 = RealMetadataFactory.createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+        Table pm1g3 = RealMetadataFactory.createPhysicalGroup("g3", pm1); //$NON-NLS-1$
+        Table pm1g4 = RealMetadataFactory.createPhysicalGroup("g4", pm1); //$NON-NLS-1$
+        Table pm1g5 = RealMetadataFactory.createPhysicalGroup("g5", pm1); //$NON-NLS-1$
 
         // Create physical elements
-        List pm1g1e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 pm1g1,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -120,8 +104,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g2e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 pm1g2,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -129,8 +112,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g3e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 pm1g3,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -138,8 +120,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g4e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 pm1g4,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -147,8 +128,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g5e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 pm1g5,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -158,43 +138,36 @@
                     DataTypeManager.DefaultDataTypes.DOUBLE });
 
         // Create virtual groups
-        QueryNode vm1g1n1 = new QueryNode("SELECT * FROM tm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vm1g1n1 = new QueryNode("SELECT * FROM tm1.g1"); //$NON-NLS-1$ 
         //selects from temp group
-        FakeMetadataObject vm1g1 =
-            FakeMetadataFactory.createVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
+        Table vm1g1 = RealMetadataFactory.createVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
 
         QueryNode vm1g2n1 =
-            new QueryNode("SELECT * FROM pm1.g2 where pm1.g2.e1=?"); //$NON-NLS-1$ //$NON-NLS-2$
+            new QueryNode("SELECT * FROM pm1.g2 where pm1.g2.e1=?"); //$NON-NLS-1$ 
         vm1g2n1.addBinding("vm1.g1.e1"); //$NON-NLS-1$
-        FakeMetadataObject vm1g2 =
-            FakeMetadataFactory.createVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
+        Table vm1g2 = RealMetadataFactory.createVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
 
         QueryNode vm1g3n1 =
-            new QueryNode("SELECT * FROM pm1.g3 where pm1.g3.e1=?"); //$NON-NLS-1$ //$NON-NLS-2$
+            new QueryNode("SELECT * FROM pm1.g3 where pm1.g3.e1=?"); //$NON-NLS-1$ 
         vm1g3n1.addBinding("vm1.g2.e1"); //$NON-NLS-1$
-        FakeMetadataObject vm1g3 =
-            FakeMetadataFactory.createVirtualGroup("vm1.g3", vm1, vm1g3n1); //$NON-NLS-1$
+        Table vm1g3 = RealMetadataFactory.createVirtualGroup("g3", vm1, vm1g3n1); //$NON-NLS-1$
 
-        QueryNode vm1g4n1 = new QueryNode("SELECT * FROM pm1.g4"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g4 =
-            FakeMetadataFactory.createVirtualGroup("vm1.g4", vm1, vm1g4n1); //$NON-NLS-1$
+        QueryNode vm1g4n1 = new QueryNode("SELECT * FROM pm1.g4"); //$NON-NLS-1$ 
+        Table vm1g4 = RealMetadataFactory.createVirtualGroup("g4", vm1, vm1g4n1); //$NON-NLS-1$
 
         QueryNode vm1g5n1 =
             new QueryNode(
                 "SELECT * FROM pm1.g5 where pm1.g5.e1=? AND pm1.g5.e2=?"); //$NON-NLS-1$
         vm1g5n1.addBinding("vm1.g4.e1"); //$NON-NLS-1$
         vm1g5n1.addBinding("vm1.g1.e1"); //$NON-NLS-1$
-        FakeMetadataObject vm1g5 =
-            FakeMetadataFactory.createVirtualGroup("vm1.g5", vm1, vm1g5n1); //$NON-NLS-1$
+        Table vm1g5 = RealMetadataFactory.createVirtualGroup("g5", vm1, vm1g5n1); //$NON-NLS-1$
 
         QueryNode tempGroup1 =
-            new QueryNode("SELECT * FROM pm1.g1 where e2 < '5'"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject tm1g1 =
-            FakeMetadataFactory.createVirtualGroup("tm1.g1", vm1, tempGroup1); //$NON-NLS-1$
+            new QueryNode("SELECT * FROM pm1.g1 where e2 < '5'"); //$NON-NLS-1$ 
+        Table tm1g1 = RealMetadataFactory.createVirtualGroup("tm1.g1", vm1, tempGroup1); //$NON-NLS-1$
 
         // Create virtual elements
-        List vm1g1e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 vm1g1,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -202,8 +175,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g2e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 vm1g2,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -211,8 +183,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g3e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 vm1g3,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -220,8 +191,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g4e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 vm1g4,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -229,8 +199,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g5e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 vm1g5,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -238,8 +207,7 @@
                     DataTypeManager.DefaultDataTypes.INTEGER,
                     DataTypeManager.DefaultDataTypes.BOOLEAN,
                     DataTypeManager.DefaultDataTypes.DOUBLE });
-        List tm1g1e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 tm1g1,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -250,10 +218,8 @@
 
         // Create virtual documents
         // DOC 1
-        FakeMetadataObject doc1 =
-            FakeMetadataFactory.createVirtualGroup("vm1.doc1", vm1, doc1()); //$NON-NLS-1$
-        List docE1 =
-            FakeMetadataFactory.createElements(
+        Table doc1 = RealMetadataFactory.createXmlDocument("doc1", vm1, doc1()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(
                 doc1,
                 new String[] {
                     "a0", //$NON-NLS-1$
@@ -269,19 +235,15 @@
                     DataTypeManager.DefaultDataTypes.STRING });
 
         // DOC 2 
-        FakeMetadataObject doc2 =
-            FakeMetadataFactory.createVirtualGroup("vm1.doc2", vm1, doc2()); //$NON-NLS-1$
-        List docE2 =
-            FakeMetadataFactory.createElements(
+        Table doc2 = RealMetadataFactory.createXmlDocument("doc2", vm1, doc2()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(
                 doc2,
                 new String[] { "a1" }, //$NON-NLS-1$
                 new String[] { DataTypeManager.DefaultDataTypes.STRING });
 
         // DOC 3
-        FakeMetadataObject doc3 =
-            FakeMetadataFactory.createVirtualGroup("vm1.doc3", vm1, doc3()); //$NON-NLS-1$
-        List docE3 =
-            FakeMetadataFactory.createElements(
+        Table doc3 = RealMetadataFactory.createXmlDocument("doc3", vm1, doc3()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(
                 doc3,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -297,10 +259,8 @@
                     DataTypeManager.DefaultDataTypes.STRING });
 
         // DOC 4
-        FakeMetadataObject doc4 =
-            FakeMetadataFactory.createVirtualGroup("vm1.doc4", vm1, doc4()); //$NON-NLS-1$
-        List docE4 =
-            FakeMetadataFactory.createElements(
+        Table doc4 = RealMetadataFactory.createXmlDocument("doc4", vm1, doc4()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(
                 doc4,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -322,10 +282,8 @@
                     DataTypeManager.DefaultDataTypes.STRING });
 
         // DOC 5
-        FakeMetadataObject doc5 =
-            FakeMetadataFactory.createVirtualGroup("vm1.doc5", vm1, doc5()); //$NON-NLS-1$
-        List docE5 =
-            FakeMetadataFactory.createElements(
+        Table doc5 = RealMetadataFactory.createXmlDocument("doc5", vm1, doc5()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(
                 doc5,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -353,22 +311,18 @@
                     DataTypeManager.DefaultDataTypes.STRING });
 
         // DOC 6
-        FakeMetadataObject doc6 =
-            FakeMetadataFactory.createVirtualGroup("vm1.doc6", vm1, doc6()); //$NON-NLS-1$
-        List docE6 =
-            FakeMetadataFactory.createElements(
+        Table doc6 = RealMetadataFactory.createXmlDocument("doc6", vm1, doc6()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(
                 doc6,
                 new String[] { "tempGroupTest" }, //$NON-NLS-1$
                 new String[] { DataTypeManager.DefaultDataTypes.STRING });
 
         // DOC with excluded fragment
-        FakeMetadataObject docWithExcluded =
-            FakeMetadataFactory.createVirtualGroup(
+        Table docWithExcluded = RealMetadataFactory.createXmlDocument(
                 "vm1.docWithExcluded", //$NON-NLS-1$
                 vm1,
                 docWithExcluded());
-        List docWithExcludedElements =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 docWithExcluded,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -384,13 +338,11 @@
                     DataTypeManager.DefaultDataTypes.STRING });
 
         // DOC 2 with excluded fragment
-        FakeMetadataObject doc2WithExcluded =
-            FakeMetadataFactory.createVirtualGroup(
+        Table doc2WithExcluded = RealMetadataFactory.createXmlDocument(
                 "vm1.docWithExcluded2", //$NON-NLS-1$
                 vm1,
                 docWithExcluded2());
-        List doc2WithExcludedElements =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 doc2WithExcluded,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -407,18 +359,15 @@
 
 
         // DOC with attribute
-        FakeMetadataObject docWithAttribute =
-            FakeMetadataFactory.createVirtualGroup(
+        Table docWithAttribute = RealMetadataFactory.createXmlDocument(
                 "vm1.docWithAttribute", //$NON-NLS-1$
                 vm1,
                 docTestConvertCriteriaWithAttribute());
-        FakeMetadataObject docWithAttribute3 =
-            FakeMetadataFactory.createVirtualGroup(
+        Table docWithAttribute3 = RealMetadataFactory.createXmlDocument(
                 "vm1.docWithAttribute3", //$NON-NLS-1$
                 vm1,
                 docTestCriteriaWithAttribute());
-        List docWithAttributeElements =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                docWithAttribute,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -429,13 +378,11 @@
                     DataTypeManager.DefaultDataTypes.STRING,
                     DataTypeManager.DefaultDataTypes.STRING });
         // DOC with attribute2
-        FakeMetadataObject docWithAttribute2 =
-            FakeMetadataFactory.createVirtualGroup(
+        Table docWithAttribute2 = RealMetadataFactory.createXmlDocument(
                 "vm1.docWithAttribute2", //$NON-NLS-1$
                 vm1,
                 docTestConvertCriteriaWithAttribute2());
-        List docWithAttributeElements2 =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 docWithAttribute2,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -446,8 +393,7 @@
                     DataTypeManager.DefaultDataTypes.STRING,
                     DataTypeManager.DefaultDataTypes.STRING });
         
-        List docWithAttributeElements3 =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 docWithAttribute3,
                 new String[] {
                     "root", //$NON-NLS-1$
@@ -458,58 +404,8 @@
                     DataTypeManager.DefaultDataTypes.STRING,
                     DataTypeManager.DefaultDataTypes.STRING });
         
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);
-        store.addObjects(pm1g1e);
-        store.addObject(pm1g2);
-        store.addObjects(pm1g2e);
-        store.addObject(pm1g3);
-        store.addObjects(pm1g3e);
-        store.addObject(pm1g4);
-        store.addObjects(pm1g4e);
-        store.addObject(pm1g5);
-        store.addObjects(pm1g5e);
-
-        store.addObject(vm1);
-        store.addObject(vm1g1);
-        store.addObjects(vm1g1e);
-        store.addObject(vm1g2);
-        store.addObjects(vm1g2e);
-        store.addObject(vm1g3);
-        store.addObjects(vm1g3e);
-        store.addObject(vm1g4);
-        store.addObjects(vm1g4e);
-        store.addObject(vm1g5);
-        store.addObjects(vm1g5e);
-        store.addObject(tm1g1);
-        store.addObjects(tm1g1e);
-        store.addObject(doc1);
-        store.addObject(doc2);
-        store.addObject(doc3);
-        store.addObject(doc4);
-        store.addObject(doc5);
-        store.addObject(doc6);
-        store.addObject(docWithExcluded);
-        store.addObject(doc2WithExcluded);
-        store.addObject(docWithAttribute);
-        store.addObject(docWithAttribute2);
-        store.addObject(docWithAttribute3);
-        store.addObjects(docE1);
-        store.addObjects(docE2);
-        store.addObjects(docE3);
-        store.addObjects(docE4);
-        store.addObjects(docE5);
-        store.addObjects(docE6);
-        store.addObjects(docWithExcludedElements);
-        store.addObjects(doc2WithExcludedElements);
-        store.addObjects(docWithAttributeElements);
-        store.addObjects(docWithAttributeElements2);
-        store.addObjects(docWithAttributeElements3);
-
         // Create the facade from the store
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
     }
 
     private static MappingDocument doc1() {
@@ -709,7 +605,7 @@
    }
 
     
-    public void test1() throws Exception {
+    @Test public void test1() throws Exception {
         helpPlan("SELECT * FROM vm1.doc1", example1()); //$NON-NLS-1$
     }
 
@@ -718,7 +614,7 @@
      * (a node that is not mapped to data)
      * (Also duplicate defect 8130)
      */
-    public void test1_defect7341() throws Exception {
+    @Test public void test1_defect7341() throws Exception {
         helpPlanException("SELECT * FROM vm1.doc1 WHERE a0 = '3'", example1()); //$NON-NLS-1$
     }
 
@@ -727,17 +623,17 @@
      * (a node that is not mapped to data)
      * (Also duplicate defect 8130)
      */
-    public void test1_defect7341_a() throws Exception {
+    @Test public void test1_defect7341_a() throws Exception {
         helpPlanException(
             "SELECT * FROM vm1.doc3 WHERE context(m1, m1) = '3'", //$NON-NLS-1$
             example1());
     }
 
-    public void test2() throws Exception {
+    @Test public void test2() throws Exception {
         helpPlan("SELECT * FROM vm1.doc2", example1()); //$NON-NLS-1$
     }
 
-    public void test3() throws Exception {
+    @Test public void test3() throws Exception {
         helpPlan("SELECT * FROM vm1.doc1 where a0.a1.a1='x'", example1()); //$NON-NLS-1$
     }
 
@@ -746,11 +642,11 @@
      * be executed before the temp group tm1.g1 is, since it selects from that 
      * group but is not in it's scope
      */
-    public void test4() throws Exception {
+    @Test public void test4() throws Exception {
         helpPlan("SELECT * FROM vm1.doc3", example1()); //$NON-NLS-1$
     }
 
-    public void testTempGroupPlan() throws Exception {
+    @Test public void testTempGroupPlan() throws Exception {
         QueryMetadataInterface qmi = example1();
         
         XMLPlan plan = helpPlan("SELECT * FROM vm1.doc6", qmi); //$NON-NLS-1$
@@ -767,13 +663,13 @@
         assertTrue(program.getInstructionAt(i++) instanceof ExecStagingTableInstruction);
     }
 
-    public void testPreparePlan() throws Exception {
+    @Test public void testPreparePlan() throws Exception {
         helpPlan(
             "SELECT * FROM vm1.doc1 ORDER BY vm1.doc1.a0.a1.c1", //$NON-NLS-1$
             example1());
     }
 
-    public void testPreparePlan2() throws Exception {
+    @Test public void testPreparePlan2() throws Exception {
         helpPlan(
             "SELECT root. at myAttribute FROM vm1.docWithAttribute", //$NON-NLS-1$
             example1());
@@ -792,7 +688,6 @@
     public static XMLPlan preparePlan(Command command, QueryMetadataInterface metadata, CapabilitiesFinder capFinder, CommandContext context)
         throws QueryPlannerException, QueryMetadataException, TeiidComponentException {
         IDGenerator idGenerator = new IDGenerator();
-        idGenerator.setDefaultFactory(new IntegerIDFactory());
         AnalysisRecord analysis = new AnalysisRecord(false, DEBUG);
         try {
             if (DEBUG) {
@@ -806,7 +701,7 @@
         }
     }
 
-    public void testDefect18227() throws Exception {
+    @Test public void testDefect18227() throws Exception {
         QueryMetadataInterface metadata = example1();       
         String sql = "select * from vm1.docWithAttribute3 where root. at type = '3'"; //$NON-NLS-1$
         
@@ -820,7 +715,7 @@
         }
     }
     
-    public void testDefect21983() throws Exception {
+    @Test public void testDefect21983() throws Exception {
         QueryMetadataInterface metadata = example1();       
         String sql = "select root. at type from vm1.docWithAttribute3"; //$NON-NLS-1$
         
@@ -835,7 +730,7 @@
      * name is returned by XMLPlanner 
      * @throws Exception
      */
-    public void testRootStagingTableCase4308() throws Exception{
+    @Test public void testRootStagingTableCase4308() throws Exception{
         
         String sql = "select * from vm1.doc1 where stagingTable2.e1 IN ('a', 'b', 'c')"; //$NON-NLS-1$
         
@@ -844,26 +739,25 @@
         Query query = (Query)new QueryParser().parseCommand(sql);
         QueryResolver.resolveCommand(query, metadata);
         
-        String expectedStagingTableResultSet = "tm1.stagingTable2"; //$NON-NLS-1$
+        String expectedStagingTableResultSet = "vm1.doc1.stagingTable2"; //$NON-NLS-1$
         String actualStagingTableResultSet = CriteriaPlanner.getStagingTableForConjunct(query.getCriteria(), metadata);
         
         assertEquals(expectedStagingTableResultSet, actualStagingTableResultSet);
         
     }
     
-    private FakeMetadataFacade exampleCase4308(){
+    private TransformationMetadata exampleCase4308(){
+    	MetadataStore metadataStore = new MetadataStore();
         
         // Create models
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject vm1 = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        Schema vm1 = RealMetadataFactory.createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
 
         // Create physical groups
-        FakeMetadataObject pm1g1 =
-            FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
+        Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
 
         // Create physical elements
-        List pm1g1e =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 pm1g1,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -874,13 +768,10 @@
 
 
         QueryNode stagingTableNode =
-            new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject stagingTable =
-            FakeMetadataFactory.createVirtualGroup("tm1.stagingTable2", vm1, stagingTableNode); //$NON-NLS-1$
+            new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ 
+        Table stagingTable = RealMetadataFactory.createXmlStagingTable("doc1.stagingTable2", vm1, stagingTableNode); //$NON-NLS-1$
         
-        
-        List stagingTableElements =
-            FakeMetadataFactory.createElements(
+        RealMetadataFactory.createElements(
                 stagingTable,
                 new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                 new String[] {
@@ -893,30 +784,16 @@
         
         MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
         
-        List stagingTables = new ArrayList(1);
-        stagingTables.add("tm1.stagingTable2"); //$NON-NLS-1$
-        root.setStagingTables(stagingTables);
+        root.addStagingTable("vm1.doc1.stagingTable2");
 
-        
         // Create virtual documents
         // DOC 1
-        FakeMetadataObject doc1 =
-            FakeMetadataFactory.createVirtualGroup(
-                "vm1.doc1", //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument(
+                "doc1", //$NON-NLS-1$
                 vm1,
                 doc);
 
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);
-        store.addObjects(pm1g1e);
-        store.addObject(stagingTable);
-        store.addObjects(stagingTableElements);
-        store.addObject(doc1);
-
-        // Create the facade from the store
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "case4308");
     }
 
     private static final boolean DEBUG = false;

Copied: branches/as7/engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java (from rev 3382, trunk/engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java)
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java	                        (rev 0)
+++ branches/as7/engine/src/test/java/org/teiid/query/parser/TestLimitParsing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,145 @@
+/*
+ * 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 org.teiid.query.parser;
+
+import static org.teiid.query.parser.TestParser.*;
+
+import java.util.Arrays;
+
+import org.junit.Test;
+import org.teiid.query.sql.lang.From;
+import org.teiid.query.sql.lang.Limit;
+import org.teiid.query.sql.lang.Query;
+import org.teiid.query.sql.lang.Select;
+import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.UnaryFromClause;
+import org.teiid.query.sql.lang.SetQuery.Operation;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
+import org.teiid.query.sql.symbol.Constant;
+import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.Reference;
+
+public class TestLimitParsing {
+	
+    @Test public void testLimit() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(null, new Constant(new Integer(100))));
+        helpTest("Select * from a limit 100", "SELECT * FROM a LIMIT 100", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testLimitWithOffset() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(new Constant(new Integer(50)), new Constant(new Integer(100))));
+        helpTest("Select * from a limit 50,100", "SELECT * FROM a LIMIT 50, 100", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testLimitWithReferences1() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(new Reference(0), new Constant(new Integer(100))));
+        helpTest("Select * from a limit ?,100", "SELECT * FROM a LIMIT ?, 100", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testLimitWithReferences2() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(new Constant(new Integer(50)), new Reference(0)));
+        helpTest("Select * from a limit 50,?", "SELECT * FROM a LIMIT 50, ?", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testLimitWithReferences3() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(new Reference(0), new Reference(1)));
+        helpTest("Select * from a limit ?,?", "SELECT * FROM a LIMIT ?, ?", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testSetQueryLimit() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        SetQuery setQuery = new SetQuery(Operation.UNION, true, query, query);
+        setQuery.setLimit(new Limit(new Reference(0), new Reference(1)));
+        helpTest("Select * from a union all Select * from a limit ?,?", "SELECT * FROM a UNION ALL SELECT * FROM a LIMIT ?, ?", setQuery); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testOffset() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(new Reference(0), null));
+        helpTest("Select * from a offset ? rows", "SELECT * FROM a OFFSET ? ROWS", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testFetchFirst() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(null, new Constant(2)));
+        helpTest("Select * from a fetch first 2 rows only", "SELECT * FROM a LIMIT 2", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testFetchFirstRow() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(null, new Constant(1)));
+        helpTest("Select * from a fetch first row only", "SELECT * FROM a LIMIT 1", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testOffsetFetch() {
+        Query query = new Query();
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
+        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
+        query.setSelect(select);
+        query.setFrom(from);
+        query.setLimit(new Limit(new Constant(2), new Constant(5)));
+        helpTest("Select * from a offset 2 rows fetch first 5 rows only", "SELECT * FROM a LIMIT 2, 5", query); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+
+}

Modified: branches/as7/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/parser/TestOptionsAndHints.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -57,7 +57,7 @@
 import org.teiid.query.sql.proc.HasCriteria;
 import org.teiid.query.sql.proc.IfStatement;
 import org.teiid.query.sql.proc.Statement;
-import org.teiid.query.sql.symbol.AllSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
@@ -93,7 +93,7 @@
         query.setFrom(from);
         query.setCriteria(crit);
         TestParser.helpTest("Select a From db.g1 MAKENOTDEP, db.g2 AS c MAKENOTDEP WHERE a = b",  //$NON-NLS-1$
-                 "SELECT a FROM db.g1 MAKENOTDEP, db.g2 AS c MAKENOTDEP WHERE a = b",  //$NON-NLS-1$
+                 "SELECT a FROM /*+ MAKENOTDEP */ db.g1, /*+ MAKENOTDEP */ db.g2 AS c WHERE a = b",  //$NON-NLS-1$
                  query);
     }
 
@@ -118,7 +118,7 @@
         query.setSelect(select);
         query.setFrom(from);
         TestParser.helpTest("Select a From db.g1 JOIN db.g2 MAKEDEP ON a = b",  //$NON-NLS-1$
-                 "SELECT a FROM db.g1 INNER JOIN db.g2 MAKEDEP ON a = b",  //$NON-NLS-1$
+                 "SELECT a FROM db.g1 INNER JOIN /*+ MAKEDEP */ db.g2 ON a = b",  //$NON-NLS-1$
                  query);
     } 
     
@@ -143,7 +143,7 @@
         query.setSelect(select);
         query.setFrom(from);
         TestParser.helpTest("Select a From db.g1 MAKEDEP JOIN db.g2 ON a = b",  //$NON-NLS-1$
-                 "SELECT a FROM db.g1 MAKEDEP INNER JOIN db.g2 ON a = b",  //$NON-NLS-1$
+                 "SELECT a FROM /*+ MAKEDEP */ db.g1 INNER JOIN db.g2 ON a = b",  //$NON-NLS-1$
                  query);
     }
 
@@ -174,7 +174,7 @@
         query.setSelect(select);
         query.setFrom(from);
         TestParser.helpTest("Select a From (db.g1 MAKEDEP JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKEDEP ON a = c",  //$NON-NLS-1$
-                 "SELECT a FROM (db.g1 MAKEDEP INNER JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKEDEP ON a = c",  //$NON-NLS-1$
+                 "SELECT a FROM (/*+ MAKEDEP */ db.g1 INNER JOIN db.g2 ON a = b) LEFT OUTER JOIN /*+ MAKEDEP */ db.g3 ON a = c",  //$NON-NLS-1$
                  query);
     }
 
@@ -203,7 +203,7 @@
         query.setFrom(from);
         query.setCriteria(crit);
         TestParser.helpTest("Select a From db.g1 MAKEDEP, db.g2 AS c MAKEDEP WHERE a = b",  //$NON-NLS-1$
-                 "SELECT a FROM db.g1 MAKEDEP, db.g2 AS c MAKEDEP WHERE a = b",  //$NON-NLS-1$
+                 "SELECT a FROM /*+ MAKEDEP */ db.g1, /*+ MAKEDEP */ db.g2 AS c WHERE a = b",  //$NON-NLS-1$
                  query);
     }
 
@@ -237,7 +237,7 @@
         query.setSelect(select);
         query.setFrom(from);
         TestParser.helpTest("Select a From db.g1 JOIN db.g2 MAKENOTDEP ON a = b",  //$NON-NLS-1$
-                 "SELECT a FROM db.g1 INNER JOIN db.g2 MAKENOTDEP ON a = b",  //$NON-NLS-1$
+                 "SELECT a FROM db.g1 INNER JOIN /*+ MAKENOTDEP */ db.g2 ON a = b",  //$NON-NLS-1$
                  query);
     } 
     
@@ -262,7 +262,7 @@
         query.setSelect(select);
         query.setFrom(from);
         TestParser.helpTest("Select a From db.g1 MAKENOTDEP JOIN db.g2 ON a = b",  //$NON-NLS-1$
-                 "SELECT a FROM db.g1 MAKENOTDEP INNER JOIN db.g2 ON a = b",  //$NON-NLS-1$
+                 "SELECT a FROM /*+ MAKENOTDEP */ db.g1 INNER JOIN db.g2 ON a = b",  //$NON-NLS-1$
                  query);
     }
 
@@ -293,7 +293,7 @@
         query.setSelect(select);
         query.setFrom(from);
         TestParser.helpTest("Select a From (db.g1 MAKENOTDEP JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKENOTDEP ON a = c",  //$NON-NLS-1$
-                 "SELECT a FROM (db.g1 MAKENOTDEP INNER JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 MAKENOTDEP ON a = c",  //$NON-NLS-1$
+                 "SELECT a FROM (/*+ MAKENOTDEP */ db.g1 INNER JOIN db.g2 ON a = b) LEFT OUTER JOIN /*+ MAKENOTDEP */ db.g3 ON a = c",  //$NON-NLS-1$
                  query);
     }
 
@@ -308,11 +308,11 @@
         From from = new From(Arrays.asList(predicate));
         predicate.getLeftClause().setMakeNotDep(true);
         predicate.getRightClause().setMakeDep(true);
-        Select select = new Select(Arrays.asList(new Object[] {x, y}));
+        Select select = new Select(Arrays.asList(x, y));
         
         Query query = new Query(select, from, null, null, null, null, null);
         TestParser.helpTest("Select a.x, b.y From a MAKENOTDEP INNER JOIN b MAKEDEP ON a.x = func(b.y)",  //$NON-NLS-1$
-                 "SELECT a.x, b.y FROM a MAKENOTDEP INNER JOIN b MAKEDEP ON a.x = func(b.y)",  //$NON-NLS-1$
+                 "SELECT a.x, b.y FROM /*+ MAKENOTDEP */ a INNER JOIN /*+ MAKEDEP */ b ON a.x = func(b.y)",  //$NON-NLS-1$
                  query);
     }
 
@@ -434,7 +434,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -452,7 +452,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -470,7 +470,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -488,7 +488,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -506,7 +506,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -524,7 +524,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -542,7 +542,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
@@ -560,7 +560,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -578,7 +578,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
@@ -596,13 +596,13 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         
         Query query2 = new Query();
         select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query2.setSelect(select);
         From from2 = new From();
         from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
@@ -623,7 +623,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         
@@ -692,7 +692,7 @@
         
         Query query2 = new Query();
         select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         From from2 = new From();
         from2.addGroup(new GroupSymbol("t1")); //$NON-NLS-1$
         from2.addGroup(new GroupSymbol("t2")); //$NON-NLS-1$
@@ -996,7 +996,7 @@
         option.addDependentGroup("a"); //$NON-NLS-1$
         option.addNotDependentGroup("b"); //$NON-NLS-1$
         
-        Select select = new Select(Arrays.asList(new Object[] {x, y}));
+        Select select = new Select(Arrays.asList(x, y));
         
         Criteria criteria = new CompareCriteria(x, CompareCriteria.EQ, y);
         Query query = new Query(select, from, criteria, null, null, null, option);
@@ -1030,7 +1030,7 @@
         query.setSelect(select);
         query.setFrom(from);
         TestParser.helpTest("Select a From (db.g1 JOIN db.g2 ON a = b) makedep LEFT OUTER JOIN db.g3 ON a = c",  //$NON-NLS-1$
-                 "SELECT a FROM (db.g1 INNER JOIN db.g2 ON a = b) MAKEDEP LEFT OUTER JOIN db.g3 ON a = c",  //$NON-NLS-1$
+                 "SELECT a FROM /*+ MAKEDEP */ (db.g1 INNER JOIN db.g2 ON a = b) LEFT OUTER JOIN db.g3 ON a = c",  //$NON-NLS-1$
                  query);
         
         //ensure that the new string form is parsable
@@ -1042,7 +1042,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -1058,7 +1058,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -1087,7 +1087,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -1106,7 +1106,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         UnaryFromClause ufc = new UnaryFromClause();
@@ -1116,7 +1116,7 @@
         
         Query query1 = new Query();
         select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query1.setSelect(select);
         from = new From();
         ufc = new UnaryFromClause();

Modified: branches/as7/engine/src/test/java/org/teiid/query/parser/TestParseAlter.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/parser/TestParseAlter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/parser/TestParseAlter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -54,7 +54,7 @@
 		alterTrigger.setTarget(new GroupSymbol("x"));
 		alterTrigger.setEvent(TriggerEvent.UPDATE);
 		alterTrigger.setDefinition((TriggerAction) QueryParser.getQueryParser().parseUpdateProcedure("for each row begin end"));
-		helpTest("alter trigger on x instead of update as for each row begin end", "ALTER TRIGGER ON x INSTEAD OF UPDATE AS\nFOR EACH ROW\nBEGIN\nEND", alterTrigger);
+		helpTest("alter trigger on x instead of update as for each row begin end", "ALTER TRIGGER ON x INSTEAD OF UPDATE AS\nFOR EACH ROW\nBEGIN ATOMIC\nEND", alterTrigger);
 	}
 	
 	@Test public void testAlterDisabled() throws Exception {
@@ -71,7 +71,7 @@
 		alterTrigger.setTarget(new GroupSymbol("x"));
 		alterTrigger.setEvent(TriggerEvent.UPDATE);
 		alterTrigger.setDefinition((TriggerAction) QueryParser.getQueryParser().parseUpdateProcedure("for each row begin end"));
-		helpTest("create trigger on x instead of update as for each row begin end", "CREATE TRIGGER ON x INSTEAD OF UPDATE AS\nFOR EACH ROW\nBEGIN\nEND", alterTrigger);
+		helpTest("create trigger on x instead of update as for each row begin end", "CREATE TRIGGER ON x INSTEAD OF UPDATE AS\nFOR EACH ROW\nBEGIN ATOMIC\nEND", alterTrigger);
 	}
 	
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/parser/TestParser.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/parser/TestParser.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/parser/TestParser.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -61,7 +61,6 @@
 import org.teiid.query.sql.lang.IsNullCriteria;
 import org.teiid.query.sql.lang.JoinPredicate;
 import org.teiid.query.sql.lang.JoinType;
-import org.teiid.query.sql.lang.Limit;
 import org.teiid.query.sql.lang.MatchCriteria;
 import org.teiid.query.sql.lang.NotCriteria;
 import org.teiid.query.sql.lang.OrderBy;
@@ -87,9 +86,8 @@
 import org.teiid.query.sql.lang.TextTable.TextColumn;
 import org.teiid.query.sql.proc.AssignmentStatement;
 import org.teiid.query.sql.proc.Block;
-import org.teiid.query.sql.proc.BreakStatement;
+import org.teiid.query.sql.proc.BranchingStatement;
 import org.teiid.query.sql.proc.CommandStatement;
-import org.teiid.query.sql.proc.ContinueStatement;
 import org.teiid.query.sql.proc.CreateUpdateProcedureCommand;
 import org.teiid.query.sql.proc.CriteriaSelector;
 import org.teiid.query.sql.proc.DeclareStatement;
@@ -100,10 +98,9 @@
 import org.teiid.query.sql.proc.Statement;
 import org.teiid.query.sql.proc.TranslateCriteria;
 import org.teiid.query.sql.proc.WhileStatement;
+import org.teiid.query.sql.proc.BranchingStatement.BranchingMode;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.CaseExpression;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.DerivedColumn;
@@ -112,12 +109,15 @@
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.TestCaseExpression;
 import org.teiid.query.sql.symbol.TestSearchedCaseExpression;
 import org.teiid.query.sql.symbol.TextLine;
+import org.teiid.query.sql.symbol.WindowFunction;
+import org.teiid.query.sql.symbol.WindowSpecification;
 import org.teiid.query.sql.symbol.XMLAttributes;
 import org.teiid.query.sql.symbol.XMLElement;
 import org.teiid.query.sql.symbol.XMLForest;
@@ -172,7 +172,7 @@
     }
     
     private void helpBlockTest(String block, String expectedString, Block expectedBlock) throws ParseException {
-        Block actualBlock = new SQLParser(new StringReader(block)).block(new ParseInfo());
+        Block actualBlock = SQLParserUtil.asBlock(new SQLParser(new StringReader(block)).statement(new ParseInfo()));
         String actualString = actualBlock.toString();
         assertEquals("Parse string does not match: ", expectedString, actualString); //$NON-NLS-1$
         assertEquals("Block does not match: ", expectedBlock, actualBlock);              //$NON-NLS-1$
@@ -217,7 +217,7 @@
 		From from = new From();
 		from.addClause(jp);
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -237,7 +237,7 @@
 		From from = new From();
 		from.addClause(jp);	
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -259,7 +259,7 @@
 		from.addClause(jp);	
 		from.addClause(new UnaryFromClause(new GroupSymbol("g3"))); //$NON-NLS-1$
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -286,7 +286,7 @@
 		From from = new From();
 		from.addClause(jp2);	
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -311,7 +311,7 @@
 		From from = new From();
 		from.addClause(jp3);	
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -334,7 +334,7 @@
 		From from = new From();
 		from.addClause(jp2);	
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -358,7 +358,7 @@
 		from.addClause(jp2);
 		from.addClause(new UnaryFromClause(new GroupSymbol("g4")));	 //$NON-NLS-1$
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -387,7 +387,7 @@
 		from.addClause(g4);
 		from.addClause(jp3);	
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -416,7 +416,7 @@
 		from.addClause(g1);
 		from.addClause(jp);
 
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		Select select = new Select();
 		select.addSymbol(all);
 
@@ -1414,28 +1414,12 @@
 	@Test public void testFailAliasInHaving() {
 		helpException("SELECT a FROM m.g GROUP BY a, b AS x");		 //$NON-NLS-1$
 	}
- 
-	/** SELECT a FROM m.g GROUP BY count(a) */
-	@Test public void testFailAggregateInGroupBy() {
-		helpException("SELECT a FROM m.g GROUP BY count(a)");		 //$NON-NLS-1$
-	}
 	
-	
-	@Test public void testExceptionLength() {
+	@Test(expected=QueryParserException.class) public void testExceptionLength() throws Exception {
         String sql = "SELECT * FROM Customer where Customer.Name = (select lastname from CUSTOMER where acctid = 9"; ////$NON-NLS-1$
-        try {
-            QueryParser.getQueryParser().parseCommand(sql);
-            fail("Expected exception for parsing " + sql); //$NON-NLS-1$
-        } catch (TeiidException e) {
-            //e.printStackTrace();
-            //if (e.getMessage().length() > 1000) {
-            //    fail("Expected max length of message 1000; but received  " + e.getMessage().length()); //$NON-NLS-1$
-            //}
-        }
+        QueryParser.getQueryParser().parseCommand(sql);
     }
 
-	
-    
     @Test public void testFunctionOfAggregates() {
         GroupSymbol g = new GroupSymbol("m.g"); //$NON-NLS-1$
         From from = new From();
@@ -1934,7 +1918,7 @@
 		from.addGroup(h);
 
 		Select select = new Select();
-		AllInGroupSymbol myG = new AllInGroupSymbol("myG.*"); //$NON-NLS-1$
+		MultipleElementSymbol myG = new MultipleElementSymbol("myG"); //$NON-NLS-1$
 		select.addSymbol(myG);
 		select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
 
@@ -1955,7 +1939,7 @@
 		from.addGroup(h);
 
 		Select select = new Select();
-		AllInGroupSymbol myG = new AllInGroupSymbol("myG.*"); //$NON-NLS-1$
+		MultipleElementSymbol myG = new MultipleElementSymbol("myG"); //$NON-NLS-1$
 		select.addSymbol(myG);
 		select.addSymbol(new ElementSymbol("myH.b")); //$NON-NLS-1$
 
@@ -2325,7 +2309,7 @@
         from.addGroup(g);
 
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
 
         Query query = new Query();
         query.setSelect(select);
@@ -2343,7 +2327,7 @@
         from.addGroup(g);
 
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
 
         Query query = new Query();
         query.setSelect(select);
@@ -2361,7 +2345,7 @@
         from.addGroup(g);
 
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
 
         Query query = new Query();
         query.setSelect(select);
@@ -2692,10 +2676,10 @@
 
 	/** SELECT a FROM db.g WHERE b = aString order by c desc,d desc*/
 	@Test public void testOrderBysDesc(){
-		ArrayList elements = new ArrayList();
+		ArrayList<ElementSymbol> elements = new ArrayList<ElementSymbol>();
 		elements.add(new ElementSymbol("c")); //$NON-NLS-1$
 		elements.add(new ElementSymbol("d")); //$NON-NLS-1$
-		ArrayList orderTypes = new ArrayList();
+		ArrayList<Boolean> orderTypes = new ArrayList<Boolean>();
 		orderTypes.add(Boolean.FALSE);
 		orderTypes.add(Boolean.FALSE);
 		OrderBy orderBy = new OrderBy(elements, orderTypes);
@@ -2708,10 +2692,10 @@
 	
 	/** SELECT a FROM db.g WHERE b = aString order by c desc,d*/
 	@Test public void testMixedOrderBys(){
-		ArrayList elements = new ArrayList();
+		ArrayList<ElementSymbol> elements = new ArrayList<ElementSymbol>();
 		elements.add(new ElementSymbol("c")); //$NON-NLS-1$
 		elements.add(new ElementSymbol("d")); //$NON-NLS-1$
-		ArrayList orderTypes = new ArrayList();
+		ArrayList<Boolean> orderTypes = new ArrayList<Boolean>();
 		orderTypes.add(Boolean.FALSE);
 		orderTypes.add(Boolean.TRUE);
 		OrderBy orderBy = new OrderBy(elements, orderTypes);
@@ -2806,7 +2790,7 @@
 	}
 	
     @Test public void testLikeWithEscapeException(){
-        helpException("SELECT a from db.g where b like '#String' escape '#1'", "Parsing error: LIKE ESCAPE value must be a single character: [#1].");  //$NON-NLS-1$ //$NON-NLS-2$
+        helpException("SELECT a from db.g where b like '#String' escape '#1'", "Parsing error: LIKE/SIMILAR TO ESCAPE value must be a single character: [#1].");  //$NON-NLS-1$ //$NON-NLS-2$
     }   
 
 	/** SELECT "date"."time" from db.g */
@@ -3201,32 +3185,6 @@
              stmt);     
     }    
 
-    /*@Test public void testIfStatement1(){
-        ElementSymbol a = new ElementSymbol("a");
-        String shortType = new String("short");
-        Statement ifStmt = new DeclareStatement(a, shortType);
-
-        ElementSymbol b = new ElementSymbol("b");
-        Statement elseStmt = new DeclareStatement(b, shortType);
-              
-        Block ifBlock = new Block();
-        ifBlock.addStatement(ifStmt); 
-      
-        Block elseBlock = new Block();
-        elseBlock.addStatement(elseStmt);
-    
-        ElementSymbol c = new ElementSymbol("c");    
-        Criteria crit = new CompareCriteria(c, CompareCriteria.EQ, 
-            new Constant(new Integer(5)));
-            
-        IfStatement stmt = new IfStatement(crit, ifBlock, elseBlock);
-                        
-        helpStmtTest("IF(c = 5) BEGIN DECLARE short a; END ELSE ",
-             "IF(c = 5)"+"\n"+ "BEGIN"+"\n"+"DECLARE short a;"+"\n"+"END"+"\n"+
-             "ELSE"+"\n"+"BEGIN"+"\n"+"DECLARE short b;"+"\n"+"END",
-             stmt);     
-    }*/   
-    
     @Test public void testCriteriaSelector0() throws Exception {
         ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
         
@@ -3374,7 +3332,7 @@
             
     @Test public void testHasEQCriteria() throws Exception {
         ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-        List elements = new ArrayList();
+        List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
         elements.add(a);
         
         CriteriaSelector critSelector = new CriteriaSelector();
@@ -3407,7 +3365,7 @@
     /**HAS IN CRITERIA ON (a)*/    
     @Test public void testHasInCriteria() throws Exception {
         ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-        List elements = new ArrayList();
+        List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
         elements.add(a);
         
         CriteriaSelector critSelector = new CriteriaSelector();
@@ -3424,7 +3382,7 @@
     /**HAS COMPARE_LT CRITERIA ON (a)*/    
     @Test public void testHasLTCriteria() throws Exception {
         ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-        List elements = new ArrayList();
+        List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
         elements.add(a);
         
         CriteriaSelector critSelector = new CriteriaSelector();
@@ -3441,7 +3399,7 @@
     /**HAS COMPARE_LE CRITERIA ON (a)*/    
     @Test public void testHasLECriteria() throws Exception {
         ElementSymbol a = new ElementSymbol("a"); //$NON-NLS-1$
-        List elements = new ArrayList();
+        List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
         elements.add(a);
         
         CriteriaSelector critSelector = new CriteriaSelector();
@@ -3620,7 +3578,7 @@
      * @return
      */
     private Query sampleQuery() {
-        List symbols = new ArrayList();
+        List<ElementSymbol> symbols = new ArrayList<ElementSymbol>();
         symbols.add(new ElementSymbol("a1"));  //$NON-NLS-1$
         Select select = new Select(symbols);
            
@@ -3661,7 +3619,7 @@
     
     //sql is a variable, also uses the as, into, and update clauses
     @Test public void testDynamicCommandStatement1() throws Exception {
-        List symbols = new ArrayList();
+        List<ElementSymbol> symbols = new ArrayList<ElementSymbol>();
         
         ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
         a1.setType(DataTypeManager.DefaultDataClasses.STRING);
@@ -3753,7 +3711,7 @@
         Statement declStmt = new DeclareStatement(var1, shortType);
         
         //ifblock
-        List symbols = new ArrayList();
+        List<ElementSymbol> symbols = new ArrayList<ElementSymbol>();
         symbols.add(new ElementSymbol("a1"));  //$NON-NLS-1$
         Select select = new Select(symbols);       
         
@@ -3777,7 +3735,7 @@
         ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
         Statement elseDeclStmt = new DeclareStatement(var2, shortType);     
         
-        List elseSymbols = new ArrayList();
+        List<ElementSymbol> elseSymbols = new ArrayList<ElementSymbol>();
         elseSymbols.add(new ElementSymbol("b1"));  //$NON-NLS-1$
         Select elseSelect = new Select(elseSymbols); 
     
@@ -3786,7 +3744,6 @@
         elseQuery.setFrom(from);
         elseQuery.setCriteria(criteria);
         
-        Command elseQueryCmd = elseQuery;
         AssignmentStatement elseQueryStmt = new AssignmentStatement(var2, elseQuery);
         
         Block elseBlock = new Block();
@@ -3883,7 +3840,7 @@
         ElementSymbol var2 = new ElementSymbol("var2"); //$NON-NLS-1$
         Statement elseDeclStmt = new DeclareStatement(var2, shortType);     
         
-        List elseSymbols = new ArrayList();
+        List<ElementSymbol> elseSymbols = new ArrayList<ElementSymbol>();
         elseSymbols.add(new ElementSymbol("b1"));  //$NON-NLS-1$
         Select elseSelect = new Select(elseSymbols); 
 
@@ -5027,7 +4984,7 @@
               
         StoredProcedure exec = new StoredProcedure();
         exec.setProcedureName("m.sq1");               //$NON-NLS-1$
-        Query query = new Query(new Select(Arrays.asList(new AllSymbol())), new From(Arrays.asList(new SubqueryFromClause("x", exec))), null, null, null);
+        Query query = new Query(new Select(Arrays.asList(new MultipleElementSymbol())), new From(Arrays.asList(new SubqueryFromClause("x", exec))), null, null, null);
         SubquerySetCriteria subCrit = new SubquerySetCriteria(expr, query);
        
         Query outer = new Query();
@@ -5095,7 +5052,7 @@
     @Test public void testExecSubquery(){
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addClause(new UnaryFromClause(new GroupSymbol("newModel2.Table1")));         //$NON-NLS-1$
@@ -5118,7 +5075,7 @@
 
             Query query = new Query();
             Select select = new Select();
-            select.addSymbol(new AllSymbol());
+            select.addSymbol(new MultipleElementSymbol());
             query.setSelect(select);
             From from = new From();
             from.addGroup(new GroupSymbol("TestDocument.TestDocument")); //$NON-NLS-1$
@@ -5138,7 +5095,7 @@
 
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addGroup(new GroupSymbol("TestDocument.TestDocument")); //$NON-NLS-1$
@@ -5181,7 +5138,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
@@ -5200,7 +5157,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
@@ -5219,7 +5176,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
@@ -5236,7 +5193,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         from.addGroup(new GroupSymbol("a.thing")); //$NON-NLS-1$
@@ -5281,7 +5238,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         
@@ -5323,7 +5280,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         
@@ -5369,7 +5326,7 @@
         
         Query query = new Query();
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         query.setSelect(select);
         From from = new From();
         
@@ -5480,16 +5437,41 @@
                      +"\n"+"END", whileStmt); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
+    @Test public void testWhileStatement1() throws Exception {
+        ElementSymbol x = new ElementSymbol("x", false); //$NON-NLS-1$
+        Function f = new Function("+", new Expression[] { x, new Constant(new Integer(1)) }); //$NON-NLS-1$
+        Statement assignmentStmt = new AssignmentStatement(x, f);
+        Block block = new Block();
+        block.setAtomic(true);
+        block.setLabel("1y");
+        block.addStatement(assignmentStmt);
+        BranchingStatement bs = new BranchingStatement(BranchingMode.CONTINUE);
+        bs.setLabel("1y");
+        block.addStatement(bs);
+        Criteria crit = new CompareCriteria(x, CompareCriteria.LT, 
+                    new Constant(new Integer(100)));
+        WhileStatement whileStmt = new WhileStatement(crit, block);
+        helpStmtTest("WHILE (x < 100) \"1y\": BEGIN ATOMIC x=x+1; CONTINUE \"1y\"; END", //$NON-NLS-1$
+                     "WHILE(x < 100)"+"\n"+ "\"1y\" : BEGIN ATOMIC"+"\n"+"x = (x + 1);\nCONTINUE \"1y\";" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+                     +"\n"+"END", whileStmt); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
     @Test public void testBreakStatement() throws Exception {
-        Statement breakStmt = new BreakStatement();
+        Statement breakStmt = new BranchingStatement();
         helpStmtTest("break;", "BREAK;", breakStmt); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testContinueStatement() throws Exception {
-        Statement contStmt = new ContinueStatement();
+    	BranchingStatement contStmt = new BranchingStatement(BranchingMode.CONTINUE);
         helpStmtTest("continue;", "CONTINUE;", contStmt); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
+    @Test public void testContinueStatement1() throws Exception {
+    	BranchingStatement contStmt = new BranchingStatement(BranchingMode.CONTINUE);
+	    contStmt.setLabel("x");
+        helpStmtTest("continue x;", "CONTINUE x;", contStmt); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
     @Test public void testVirtualProcedure(){        
         ElementSymbol x = new ElementSymbol("x"); //$NON-NLS-1$
         String intType = new String("integer"); //$NON-NLS-1$
@@ -5515,7 +5497,7 @@
         block.addStatement(assignmentStmt);
         
         Block ifBlock = new Block();
-        Statement continueStmt = new ContinueStatement();
+        Statement continueStmt = new BranchingStatement(BranchingMode.CONTINUE);
         ifBlock.addStatement(continueStmt);
         Criteria crit = new CompareCriteria(x, CompareCriteria.GT, 
         new Constant(new Integer(5)));
@@ -6014,7 +5996,7 @@
 
     @Test public void testAndOrPrecedence_1575() {
         Select s = new Select();
-        s.addSymbol(new AllSymbol());
+        s.addSymbol(new MultipleElementSymbol());
         From f = new From();
         f.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
         CompareCriteria c1 = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(0))); //$NON-NLS-1$
@@ -6033,7 +6015,7 @@
 
     @Test public void testAndOrPrecedence2_1575() {
         Select s = new Select();
-        s.addSymbol(new AllSymbol());
+        s.addSymbol(new MultipleElementSymbol());
         From f = new From();
         f.addGroup(new GroupSymbol("m.g1")); //$NON-NLS-1$
         CompareCriteria c1 = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(0))); //$NON-NLS-1$
@@ -6056,7 +6038,7 @@
      */
     private void helpTestCompoundNonJoinCriteria(String sqlPred, PredicateCriteria predCrit) {
         Select s = new Select();
-        s.addSymbol(new AllSymbol());
+        s.addSymbol(new MultipleElementSymbol());
         From f = new From();
         
         CompareCriteria c1 = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(0))); //$NON-NLS-1$
@@ -6426,64 +6408,6 @@
         }
     }
     
-    @Test public void testExceptionMessageWithoutLocation() {
-        try {
-            QueryParser.getQueryParser().parseCommand("SELECT COUNT(*) FROM a WHERE COUNT(*) > 1"); //$NON-NLS-1$
-        } catch(QueryParserException e) {
-            assertTrue(e.getMessage().startsWith("Parsing error: Aggregate expressions are allowed only as top level functions in the SELECT and HAVING clauses.")); //$NON-NLS-1$
-        }        
-    }
-    
-    @Test public void testLimit() {
-        Query query = new Query();
-        Select select = new Select(Arrays.asList(new Object[] {new AllSymbol()}));
-        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
-        query.setSelect(select);
-        query.setFrom(from);
-        query.setLimit(new Limit(null, new Constant(new Integer(100))));
-        helpTest("Select * from a limit 100", "SELECT * FROM a LIMIT 100", query); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testLimitWithOffset() {
-        Query query = new Query();
-        Select select = new Select(Arrays.asList(new Object[] {new AllSymbol()}));
-        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
-        query.setSelect(select);
-        query.setFrom(from);
-        query.setLimit(new Limit(new Constant(new Integer(50)), new Constant(new Integer(100))));
-        helpTest("Select * from a limit 50,100", "SELECT * FROM a LIMIT 50, 100", query); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testLimitWithReferences1() {
-        Query query = new Query();
-        Select select = new Select(Arrays.asList(new Object[] {new AllSymbol()}));
-        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
-        query.setSelect(select);
-        query.setFrom(from);
-        query.setLimit(new Limit(new Reference(0), new Constant(new Integer(100))));
-        helpTest("Select * from a limit ?,100", "SELECT * FROM a LIMIT ?, 100", query); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testLimitWithReferences2() {
-        Query query = new Query();
-        Select select = new Select(Arrays.asList(new Object[] {new AllSymbol()}));
-        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
-        query.setSelect(select);
-        query.setFrom(from);
-        query.setLimit(new Limit(new Constant(new Integer(50)), new Reference(0)));
-        helpTest("Select * from a limit 50,?", "SELECT * FROM a LIMIT 50, ?", query); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
-    @Test public void testLimitWithReferences3() {
-        Query query = new Query();
-        Select select = new Select(Arrays.asList(new Object[] {new AllSymbol()}));
-        From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
-        query.setSelect(select);
-        query.setFrom(from);
-        query.setLimit(new Limit(new Reference(0), new Reference(1)));
-        helpTest("Select * from a limit ?,?", "SELECT * FROM a LIMIT ?, ?", query); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
     @Test public void testEmptyOuterJoinCriteria() {
         helpException("select a from b left outer join c on ()"); //$NON-NLS-1$
     }
@@ -6560,7 +6484,7 @@
         Query query = new Query();
         Select select = new Select();
         query.setSelect(select);
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         From from = new From();
         query.setFrom(from);
         Criteria compareCriteria = new CompareCriteria(new ElementSymbol("A.x"), CompareCriteria.EQ, new ElementSymbol("B.x")); //$NON-NLS-1$ //$NON-NLS-2$
@@ -6596,7 +6520,7 @@
         String expected = "SELECT * FROM pm1.g1 UNION JOIN pm1.g2 WHERE g1.e1 = 1"; //$NON-NLS-1$
         
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         
         From from = new From();
         from.addClause(new JoinPredicate(new UnaryFromClause(new GroupSymbol("pm1.g1")), new UnaryFromClause(new GroupSymbol("pm1.g2")), JoinType.JOIN_UNION)); //$NON-NLS-1$ //$NON-NLS-2$
@@ -6618,9 +6542,9 @@
         String expected = "CREATE PROCEDURE\nBEGIN\nIF(x > 1)\nBEGIN\nSELECT 1;\nEND\nIF(x > 1)\nBEGIN\nSELECT 1;\nEND\nELSE\nBEGIN\nSELECT 1;\nEND\nEND"; //$NON-NLS-1$
         
         Query query = new Query();
-        query.setSelect(new Select(Arrays.asList(new Object[] {new ExpressionSymbol("expr", new Constant(new Integer(1)))}))); //$NON-NLS-1$
+        query.setSelect(new Select(Arrays.asList(new ExpressionSymbol("expr", new Constant(1))))); //$NON-NLS-1$
         CommandStatement commandStmt = new CommandStatement(query);
-        CompareCriteria criteria = new CompareCriteria(new ElementSymbol("x"), CompareCriteria.GT, new Constant(new Integer(1))); //$NON-NLS-1$
+        CompareCriteria criteria = new CompareCriteria(new ElementSymbol("x"), CompareCriteria.GT, new Constant(1)); //$NON-NLS-1$
         Block block = new Block();
         block.addStatement(commandStmt);
         IfStatement ifStmt = new IfStatement(criteria, block);
@@ -6648,7 +6572,7 @@
         Function convert = new Function("convert", new Expression[] {new Constant(null), new Constant("blob")}); //$NON-NLS-1$ //$NON-NLS-2$
         Function convert1 = new Function("convert", new Expression[] {new Constant(null), new Constant("clob")}); //$NON-NLS-1$ //$NON-NLS-2$
         Function convert2 = new Function("convert", new Expression[] {new Constant(null), new Constant("xml")}); //$NON-NLS-1$ //$NON-NLS-2$
-        Select select = new Select(Arrays.asList(new Object[] {new ExpressionSymbol("expr", convert), new ExpressionSymbol("expr1", convert1), new ExpressionSymbol("expr2", convert2)})); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Select select = new Select(Arrays.asList(new ExpressionSymbol("expr", convert), new ExpressionSymbol("expr1", convert1), new ExpressionSymbol("expr2", convert2))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
         Query query = new Query();
         query.setSelect(select);
         
@@ -6770,7 +6694,7 @@
     @Test public void testNestedTable() throws Exception {
         String sql = "SELECT * from TABLE(exec foo()) as x"; //$NON-NLS-1$
         Query query = new Query();
-        query.setSelect(new Select(Arrays.asList(new AllSymbol())));
+        query.setSelect(new Select(Arrays.asList(new MultipleElementSymbol())));
         StoredProcedure sp = new StoredProcedure();
         sp.setProcedureName("foo");
         SubqueryFromClause sfc = new SubqueryFromClause("x", sp);
@@ -6782,12 +6706,12 @@
     @Test public void testTextTable() throws Exception {
     	String sql = "SELECT * from texttable(file columns x string WIDTH 1, y date width 10 skip 10) as x"; //$NON-NLS-1$
         Query query = new Query();
-        query.setSelect(new Select(Arrays.asList(new AllSymbol())));
+        query.setSelect(new Select(Arrays.asList(new MultipleElementSymbol())));
         TextTable tt = new TextTable();
         tt.setFile(new ElementSymbol("file"));
         List<TextTable.TextColumn> columns = new ArrayList<TextTable.TextColumn>();
-        columns.add(new TextTable.TextColumn("x", "string", 1));
-        columns.add(new TextTable.TextColumn("y", "date", 10));
+        columns.add(new TextTable.TextColumn("x", "string", 1, false));
+        columns.add(new TextTable.TextColumn("y", "date", 10, false));
         tt.setColumns(columns);
         tt.setSkip(10);
         tt.setName("x");
@@ -6812,7 +6736,7 @@
     @Test public void testXMLTable() throws Exception {
     	String sql = "SELECT * from xmltable(xmlnamespaces(no default), '/' columns x for ordinality, y date default {d'2000-01-01'} path '@date') as x"; //$NON-NLS-1$
         Query query = new Query();
-        query.setSelect(new Select(Arrays.asList(new AllSymbol())));
+        query.setSelect(new Select(Arrays.asList(new MultipleElementSymbol())));
         XMLTable xt = new XMLTable();
         xt.setName("x");
         xt.setNamespaces(new XMLNamespaces(Arrays.asList(new XMLNamespaces.NamespaceItem())));
@@ -6876,7 +6800,7 @@
     	Query query = new Query();
         Select select = new Select();
         query.setSelect(select);
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("X"))));
         query.setFrom(from);
     	helpTest("TABLE X", "SELECT * FROM X", query);
@@ -6885,7 +6809,7 @@
     @Test public void testArrayTable() throws Exception {
     	String sql = "SELECT * from arraytable(null columns x string, y date) as x"; //$NON-NLS-1$
         Query query = new Query();
-        query.setSelect(new Select(Arrays.asList(new AllSymbol())));
+        query.setSelect(new Select(Arrays.asList(new MultipleElementSymbol())));
         ArrayTable tt = new ArrayTable();
         tt.setArrayValue(new Constant(null, DataTypeManager.DefaultDataClasses.OBJECT));
         List<TableFunctionReference.ProjectedColumn> columns = new ArrayList<TableFunctionReference.ProjectedColumn>();
@@ -6903,5 +6827,40 @@
     	query.setSelect(new Select(Arrays.asList(new ExpressionSymbol("foo", new Reference(0)))));
         helpTest(sql, "SELECT ?", query);
     }
+    
+    @Test public void testNonReserved() throws Exception {
+    	String sql = "select count";
+    	Query query = new Query();
+    	query.setSelect(new Select(Arrays.asList(new ElementSymbol("count"))));
+        helpTest(sql, "SELECT count", query);
+    }
+    
+    @Test public void testAggFilter() throws Exception {
+    	String sql = "select count(*) filter (where x = 1) from g";
+    	Query query = new Query();
+    	AggregateSymbol aggregateSymbol = new AggregateSymbol("count", AggregateSymbol.Type.COUNT.name(), false, null);
+    	aggregateSymbol.setCondition(new CompareCriteria(new ElementSymbol("x"), CompareCriteria.EQ, new Constant(1)));
+    	query.setSelect(new Select(Arrays.asList(aggregateSymbol)));
+    	query.setFrom(new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("g")))));
+        helpTest(sql, "SELECT COUNT(*) FILTER(WHERE x = 1) FROM g", query);
+    }
+    
+    @Test public void testWindowFunction() throws Exception {
+    	String sql = "select row_number() over (partition by x order by y) from g";
+    	Query query = new Query();
+    	WindowFunction wf = new WindowFunction("expr");
+    	wf.setFunction(new AggregateSymbol("expr", "ROW_NUMBER", false, null));
+    	WindowSpecification ws = new WindowSpecification();
+    	ws.setPartition(new ArrayList<Expression>(Arrays.asList(new ElementSymbol("x"))));
+    	ws.setOrderBy(new OrderBy(Arrays.asList(new ElementSymbol("y"))));
+    	wf.setWindowSpecification(ws);
+    	query.setSelect(new Select(Arrays.asList(wf)));
+    	query.setFrom(new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("g")))));
+        helpTest(sql, "SELECT ROW_NUMBER() OVER (PARTITION BY x ORDER BY y) FROM g", query);
+    }
+    
+    @Test public void testTrim1() {
+    	helpException("select trim('xy' from e1) from pm1.g1");
+    }
 
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/parser/TestSetQueryParsing.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/parser/TestSetQueryParsing.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/parser/TestSetQueryParsing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,7 +28,7 @@
 import org.teiid.query.sql.lang.Select;
 import org.teiid.query.sql.lang.SetQuery;
 import org.teiid.query.sql.lang.SetQuery.Operation;
-import org.teiid.query.sql.symbol.AllSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
@@ -81,7 +81,7 @@
         from.addGroup(g);
 
         Select select = new Select();
-        select.addSymbol(new AllSymbol());
+        select.addSymbol(new MultipleElementSymbol());
         
         Query query1 = new Query();
         query1.setSelect(select);

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -49,6 +49,7 @@
 import org.teiid.query.sql.lang.ProcedureContainer;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.lang.SetQuery;
+import org.teiid.query.sql.lang.StoredProcedure;
 import org.teiid.query.sql.lang.TranslatableProcedureContainer;
 import org.teiid.query.sql.lang.Update;
 import org.teiid.query.sql.symbol.AliasSymbol;
@@ -61,7 +62,9 @@
 
 
 public class FakeDataManager implements ProcessorDataManager {
-	private Map tuples = new HashMap();
+	private Map<String, Object[]> tuples = new HashMap<String, Object[]>();
+	private Map<String, List<List<?>>[]> procTuples = new HashMap<String, List<List<?>>[]>();
+	
     private static final String LOG_CONTEXT = "FAKE_DATA_MANAGER"; //$NON-NLS-1$
     
     //used to test blocked exception. If true,
@@ -72,13 +75,13 @@
     // ---- Cached code table stuff ---- 
     	
     // upper table name + upper key col name + upper ret col name -> map of values
-    private Map codeTableValues = new HashMap();
+    private Map<String, Map> codeTableValues = new HashMap<String, Map>();
     
     // throw Blocked on first request
     private boolean throwBlocked = false;
     
     // upper table name + upper key col name + upper ret col name -> flag of whether this table has blocked yet
-    private Map blockedState = new HashMap();
+    private Map<String, Boolean> blockedState = new HashMap<String, Boolean>();
 
     // Track history to verify it later
     private List<String> queries = new ArrayList<String>();
@@ -101,11 +104,11 @@
     	this.queries.clear();
     	return rc;
     }
+    
+	public void registerProcTuples(String proc, List[] data) {
+		procTuples.put(proc, data);
+	}
 	        
-	public void registerTuples(Object groupID, List elements, List[] data) {
-		tuples.put(groupID, new Object[] { elements, data });
-	}
-	
 	public TupleSource registerRequest(CommandContext context, Command command, String modelName, String connectorBindingId, int nodeID, int limit)
 		throws TeiidComponentException {
         
@@ -127,6 +130,17 @@
         }else if(command instanceof SetQuery) {
             SetQuery union = (SetQuery) command;            
             group = getQueryGroup(union.getProjectedQuery());
+        } else if (command instanceof StoredProcedure) {
+        	Object id = ((StoredProcedure) command).getProcedureID();
+        	List<List<?>>[] data = procTuples.get(id);
+        	if (data == null) {
+        		throw new AssertionError("Undefined results for " + command); //$NON-NLS-1$
+        	}
+            FakeTupleSource ts= new FakeTupleSource(command.getProjectedSymbols(), data);
+    		if(this.blockOnce){
+                ts.setBlockOnce();
+    		}
+    		return ts;
 		} else if (command instanceof ProcedureContainer) {
 			group = ((ProcedureContainer) command).getGroup();
 		} else if ( command instanceof BatchedUpdateCommand ) {
@@ -141,13 +155,11 @@
     		}
 		}
 		
-		Object groupID = group.getMetadataID();
-		
-		Object[] tupleInfo = (Object[]) tuples.get(groupID);
-		List elements = (List) tupleInfo[0];
+		Object[] tupleInfo = tuples.get(group.getNonCorrelationName().toUpperCase());
+		List<SingleElementSymbol> elements = (List) tupleInfo[0];
 		List[] tuples = (List[]) tupleInfo[1];
 		
-		List projectedSymbols = command.getProjectedSymbols();
+		List<SingleElementSymbol> projectedSymbols = command.getProjectedSymbols();
 		int[] columnMap = getColumnMap(elements, projectedSymbols);
 		
 		/* 
@@ -164,12 +176,12 @@
 			    // Build lookupMap from BOTH all the elements and the projected symbols - both may be needed here
 	            Map lookupMap = new HashMap();
 	            for(int i=0; i<elements.size(); i++) { 
-	                Object element = elements.get(i);
-                    mapElementToIndex(lookupMap, element, new Integer(i), group);        
+	                SingleElementSymbol element = elements.get(i);
+                    mapElementToIndex(lookupMap, element, i, group);        
 	            }
 	            for(int i=0; i<projectedSymbols.size(); i++) { 
-	            	Object element = projectedSymbols.get(i);
-                    mapElementToIndex(lookupMap, element, new Integer(columnMap[i]), group);
+	            	SingleElementSymbol element = projectedSymbols.get(i);
+                    mapElementToIndex(lookupMap, element, columnMap[i], group);
 	            }
 			    
 			    List filteredTuples = new ArrayList();
@@ -205,11 +217,11 @@
 					    // Build lookupMap from BOTH all the elements and the projected symbols - both may be needed here
 			            Map<Object, Integer> lookupMap = new HashMap<Object, Integer>();
 			            for(int i=0; i<elements.size(); i++) { 
-			                Object element = elements.get(i);
+			            	SingleElementSymbol element = elements.get(i);
 		                    mapElementToIndex(lookupMap, element, new Integer(i), group);        
 			            }
 			            for(int i=0; i<projectedSymbols.size(); i++) { 
-			            	Object element = projectedSymbols.get(i);
+			            	SingleElementSymbol element = projectedSymbols.get(i);
 		                    mapElementToIndex(lookupMap, element, new Integer(columnMap[i]), group);
 			            }
 					    
@@ -233,7 +245,7 @@
 			}
 		    tuples = new List[filteredTuples.size()];
 		    filteredTuples.toArray(tuples);
-		    elements = new ArrayList<Object>(projectedSymbols);
+		    elements = new ArrayList<SingleElementSymbol>(projectedSymbols);
 		    columnMap[0] = 0;
 		}		
 				
@@ -277,16 +289,14 @@
      * @param integer
      * @param group
      */
-    private void mapElementToIndex(Map lookupMap, Object element, Integer index, GroupSymbol group) {
+    private void mapElementToIndex(Map lookupMap, SingleElementSymbol element, Integer index, GroupSymbol group) {
+    	ElementSymbol elementSymbol = (ElementSymbol)SymbolMap.getExpression(element);
         if (group.getDefinition() != null){
             String groupAlias = group.getCanonicalName();
-            ElementSymbol elementSymbol = (ElementSymbol)SymbolMap.getExpression((SingleElementSymbol)element);
-            ElementSymbol aliasedElement = (ElementSymbol)elementSymbol.clone();
-            aliasedElement.getGroupSymbol().setName(groupAlias);
-            lookupMap.put(aliasedElement, index);
-        } else {
-            lookupMap.put(element, index);
+            elementSymbol = elementSymbol.clone();
+            elementSymbol.getGroupSymbol().setName(groupAlias);
         }
+        lookupMap.put(elementSymbol, index);
     }    
 	
 	//   columnMap[expectedElementIndex] = allElementIndex
@@ -352,7 +362,7 @@
                 }
             }
         
-            Map values = (Map) codeTableValues.get(tableKey);
+            Map values = codeTableValues.get(tableKey);
             return values.get(keyValue);
     }
 
@@ -384,11 +394,11 @@
 		this.recordingCommands = shouldRecord;
 	}
 
-	public void registerTuples(QueryMetadataInterface metadata, String groupName, List[] tuples) throws QueryResolverException, TeiidComponentException {
+	public void registerTuples(QueryMetadataInterface metadata, String groupName, List[] data) throws QueryResolverException, TeiidComponentException {
 	    GroupSymbol group = new GroupSymbol(groupName);
 	    ResolverUtil.resolveGroup(group, metadata);
 	    List<ElementSymbol> elementSymbols = ResolverUtil.resolveElementsInGroup(group, metadata);
-		this.registerTuples(group.getMetadataID(), elementSymbols, tuples);
+		tuples.put(group.getName().toUpperCase(), new Object[] { elementSymbols, data });
 	}
 
 	@Override


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/FakeDataManager.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,92 +22,34 @@
 
 package org.teiid.query.processor;
 
-import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Iterator;
 import java.util.List;
 
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.StoredProcedureInfo;
-import org.teiid.query.metadata.TempMetadataStore;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.unittest.RealMetadataFactory;
 
-
-
 /** 
  * This is sample data go along with FakeMetaDataFactory and FakeDataManager
  */
 @SuppressWarnings("nls")
 public class FakeDataStore {
     
-    // Helper to create a list of elements - used in creating sample data
-    public static List createElements(List elementIDs) { 
-        List elements = new ArrayList();
-        for(int i=0; i<elementIDs.size(); i++) {
-            FakeMetadataObject elementID = (FakeMetadataObject) elementIDs.get(i);            
-            ElementSymbol element = new ElementSymbol(elementID.getName());
-            elements.add(element);
-        }        
-        
-        return elements;
-    }
-    
-    public static List createElements(List elementIDs, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException { 
-        List elements = new ArrayList();
-        for(int i=0; i<elementIDs.size(); i++) {
-            Object elementID = elementIDs.get(i);            
-            ElementSymbol element = new ElementSymbol(metadata.getFullName(elementID));
-            elements.add(element);
-        }        
-        
-        return elements;
-    }
-    
-    private static List getProcResultSetSymbols(List params){
-        List result = new ArrayList();
-        Iterator iter = params.iterator();
-        while(iter.hasNext()){
-            SPParameter param = (SPParameter)iter.next();
-            if(param.getResultSetColumns() != null){
-                result.addAll(param.getResultSetColumns());
-            }
-        }
-        iter = params.iterator();
-        while(iter.hasNext()){
-            SPParameter param = (SPParameter)iter.next();
-            if(param.getParameterType() == ParameterInfo.INOUT || param.getParameterType() == ParameterInfo.RETURN_VALUE) {
-                result.add(param.getParameterSymbol());
-            }
-        }
-        return result;
-    }
-    
-    public static void sampleData1(FakeDataManager dataMgr, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+    public static void sampleData1(FakeDataManager dataMgr, QueryMetadataInterface metadata) throws TeiidException {
 		addTable("pm1.g1", dataMgr, metadata);    
 		addTable("pm1.g2", dataMgr, metadata);
 		addTable("pm1.g3", dataMgr, metadata);    
 		addTable("pm2.g1", dataMgr, metadata);
 		addTable("pm2.g2", dataMgr, metadata);
 		addTable("pm2.g3", dataMgr, metadata);
-		addTable("tm1.g1", dataMgr, metadata);
+		//addTable("tm1.g1", dataMgr, metadata);
 
         //stored procedure pm1.sp1
-        TempMetadataStore tempStore = new TempMetadataStore();          
         StoredProcedureInfo procInfo = metadata.getStoredProcedureInfoForProcedure("pm1.sp1"); //$NON-NLS-1$
-        List elementSymbols = getProcResultSetSymbols(procInfo.getParameters());
-        tempStore.addTempGroup("pm1.sp1", elementSymbols); //$NON-NLS-1$
-        Object procID = tempStore.getTempGroupID("pm1.sp1"); //$NON-NLS-1$
-        dataMgr.registerTuples(
-            procID,
-            elementSymbols,
-            
+        dataMgr.registerProcTuples(
+            procInfo.getProcedureCallableName().toUpperCase(),
             new List[] { 
                 Arrays.asList(new Object[] { "a",   new Integer(0) }), //$NON-NLS-1$
                 Arrays.asList(new Object[] { null,  new Integer(1)}),
@@ -119,38 +61,23 @@
     }
 
 	public static void addTable(String name, FakeDataManager dataMgr,
-			QueryMetadataInterface metadata) throws TeiidComponentException,
-			QueryMetadataException {
-		Object groupID = metadata.getGroupID(name);
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = createElements(elementIDs, metadata);
-    
-        dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
+			QueryMetadataInterface metadata) throws TeiidException {
+		List[] tuples =  new List[] { 
                 Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
                 Arrays.asList(new Object[] { null,  new Integer(1),     Boolean.FALSE,  new Double(1.0) }),
                 Arrays.asList(new Object[] { "a",   new Integer(3),     Boolean.TRUE,   new Double(7.0) }), //$NON-NLS-1$
                 Arrays.asList(new Object[] { "c",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
                 Arrays.asList(new Object[] { "b",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
                 Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }) //$NON-NLS-1$
-                } );
+                };
+		
+		dataMgr.registerTuples(metadata, name, tuples);
 	}
 
-    public static void sampleData2(FakeDataManager dataMgr) throws QueryMetadataException, TeiidComponentException {
-		FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+    public static void sampleData2(FakeDataManager dataMgr) throws TeiidException {
+		TransformationMetadata metadata = RealMetadataFactory.example1Cached();
 
-		// Group pm1.g1
-		FakeMetadataObject groupID = (FakeMetadataObject) metadata
-				.getGroupID("pm1.g1"); //$NON-NLS-1$
-		List elementIDs = metadata.getElementIDsInGroupID(groupID);
-		List elementSymbols = createElements(elementIDs, metadata);
-
-		dataMgr.registerTuples(groupID, elementSymbols,
-
-		new List[] {
+		dataMgr.registerTuples(metadata, "pm1.g1", new List[] {
 				Arrays.asList(new Object[] {
 						"a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
 				Arrays.asList(new Object[] {
@@ -160,13 +87,7 @@
 		});
 
 		// Group pm1.g2
-		groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g2"); //$NON-NLS-1$
-		elementIDs = metadata.getElementIDsInGroupID(groupID);
-		elementSymbols = createElements(elementIDs, metadata);
-
-		dataMgr.registerTuples(groupID, elementSymbols,
-
-		new List[] {
+		dataMgr.registerTuples(metadata, "pm1.g2", new List[] {
 				Arrays.asList(new Object[] {
 						"a", new Integer(1), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
 				Arrays.asList(new Object[] {
@@ -180,13 +101,7 @@
 		});
 
 		// Group pm2.g1
-		groupID = (FakeMetadataObject) metadata.getGroupID("pm2.g1"); //$NON-NLS-1$
-		elementIDs = metadata.getElementIDsInGroupID(groupID);
-		elementSymbols = createElements(elementIDs, metadata);
-
-		dataMgr.registerTuples(groupID, elementSymbols,
-
-		new List[] {
+		dataMgr.registerTuples(metadata, "pm2.g1", new List[] {
 				Arrays.asList(new Object[] {
 						"b", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
 				Arrays.asList(new Object[] {
@@ -196,13 +111,7 @@
 		});
 
 		// Group pm2.g2
-		groupID = (FakeMetadataObject) metadata.getGroupID("pm2.g2"); //$NON-NLS-1$
-		elementIDs = metadata.getElementIDsInGroupID(groupID);
-		elementSymbols = createElements(elementIDs, metadata);
-
-		dataMgr.registerTuples(groupID, elementSymbols,
-
-		new List[] {
+		dataMgr.registerTuples(metadata, "pm2.g2", new List[] {
 				Arrays.asList(new Object[] {
 						"a", new Integer(1), Boolean.TRUE, new Double(2.0) }), //$NON-NLS-1$
 				Arrays.asList(new Object[] {
@@ -216,13 +125,7 @@
 		});
 
 		// Group pm1.table1
-		groupID = (FakeMetadataObject) metadata.getGroupID("pm1.table1"); //$NON-NLS-1$
-		elementIDs = metadata.getElementIDsInGroupID(groupID);
-		elementSymbols = createElements(elementIDs, metadata);
-
-		dataMgr.registerTuples(groupID, elementSymbols,
-
-		new List[] {
+		dataMgr.registerTuples(metadata, "pm1.table1", new List[] {
 				Arrays.asList(new Object[] {
 						"a", new Integer(0), Boolean.FALSE, new Double(2.0) }), //$NON-NLS-1$
 				Arrays.asList(new Object[] {


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/FakeDataStore.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -31,20 +31,23 @@
 import java.util.List;
 
 import org.junit.Test;
+import org.teiid.common.buffer.BufferManagerFactory;
+import org.teiid.common.buffer.impl.BufferManagerImpl;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestAggregatePushdown;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
+import org.teiid.query.util.CommandContext;
 import org.teiid.translator.SourceSystemFunctions;
 
- at SuppressWarnings("nls")
+ at SuppressWarnings({"nls", "unchecked"})
 public class TestAggregateProcessing {
 
 	static void sampleDataBQT3(FakeDataManager dataMgr) throws Exception {
-		QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+		QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
 		// Group bqt1.smalla
 
@@ -74,7 +77,7 @@
 	}
 
 	private void sampleDataBQT_defect9842(FakeDataManager dataMgr) throws Exception {
-		QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+		QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
 		List[] tuples = new List[5];
 		for (int i = 0; i < tuples.length; i++) {
@@ -123,7 +126,7 @@
 		sampleDataBQT3(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory
 				.exampleBQTCached());
 
 		// Run query
@@ -162,7 +165,7 @@
 		sampleDataBQT3(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory
 				.exampleBQTCached());
 
 		// Run query
@@ -187,7 +190,7 @@
 		sampleDataBQT_defect9842(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory
 				.exampleBQTCached());
 
 		// Run query
@@ -213,13 +216,12 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
     }
     
-    @SuppressWarnings("unchecked")
 	@Test public void testAggregatePushdown() {
     	Command command = helpParse("select e1, count(e2), max(e2) from (select e1, e2, e3 from pm1.g1 union all select e1, e2, e3 from pm1.g2 union all select e1, e2, e3 from pm2.g1) z group by e1"); //$NON-NLS-1$
     	
@@ -243,7 +245,7 @@
     				Arrays.asList(null, Integer.valueOf(5)),
     			});
     	
-    	ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+    	ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
     	
     	List[] expected = new List[] { 
                 Arrays.asList(null, Integer.valueOf(1), Integer.valueOf(5)),
@@ -264,17 +266,17 @@
     	capFinder.addCapabilities("pm2", bac); //$NON-NLS-1$
     	HardcodedDataManager dataManager = new HardcodedDataManager();
     	
-    	dataManager.addData("SELECT v_0.c_1, v_0.c_0, COUNT(*), MAX(v_0.c_2) FROM (SELECT g_0.e2 AS c_0, g_0.e1 AS c_1, g_0.e3 AS c_2 FROM pm1.g1 AS g_0) AS v_0 GROUP BY v_0.c_0, v_0.c_1", //$NON-NLS-1$ 
+    	dataManager.addData("SELECT v_0.c_0, v_0.c_1, COUNT(*), MAX(v_0.c_2) FROM (SELECT g_0.e1 AS c_0, g_0.e2 AS c_1, g_0.e3 AS c_2 FROM pm1.g1 AS g_0) AS v_0 GROUP BY v_0.c_0, v_0.c_1", //$NON-NLS-1$ 
     			new List[] {
     				Arrays.asList("2", Integer.valueOf(2), Integer.valueOf(2), Boolean.FALSE), //$NON-NLS-1$
     				Arrays.asList("1", Integer.valueOf(1), Integer.valueOf(3), Boolean.TRUE), //$NON-NLS-1$
     			});
-    	dataManager.addData("SELECT v_0.c_1, v_0.c_0, COUNT(*), MAX(v_0.c_2) FROM (SELECT g_0.e2 AS c_0, convert(g_0.e2, string) AS c_1, g_0.e3 AS c_2 FROM pm2.g2 AS g_0 ORDER BY c_1 LIMIT 10) AS v_0 GROUP BY v_0.c_0, v_0.c_1", //$NON-NLS-1$ 
+    	dataManager.addData("SELECT v_0.c_0, v_0.c_1, COUNT(*), MAX(v_0.c_2) FROM (SELECT convert(g_0.e2, string) AS c_0, g_0.e2 AS c_1, g_0.e3 AS c_2 FROM pm2.g2 AS g_0 ORDER BY c_0 LIMIT 10) AS v_0 GROUP BY v_0.c_0, v_0.c_1", //$NON-NLS-1$ 
     			new List[] {
     				Arrays.asList("1", Integer.valueOf(1), Integer.valueOf(4), Boolean.FALSE), //$NON-NLS-1$
     			});
     	
-    	ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+    	ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
     	
     	List[] expected = new List[] { 
                 Arrays.asList(Integer.valueOf(7), Boolean.TRUE),
@@ -292,7 +294,7 @@
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm1", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$
         
-        ProcessorPlan plan = helpGetPlan(helpParse("select max(e2), count(*), stddev_pop(e2), var_samp(e2) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm2.g2) z"), FakeMetadataFactory.example1Cached(), capFinder); //$NON-NLS-1$
+        ProcessorPlan plan = helpGetPlan(helpParse("select max(e2), count(*), stddev_pop(e2), var_samp(e2) from (select e1, e2 from pm1.g1 union all select e1, e2 from pm2.g2) z"), RealMetadataFactory.example1Cached(), capFinder); //$NON-NLS-1$
         
         HardcodedDataManager dataManager = new HardcodedDataManager();
         dataManager.addData("SELECT g_0.e2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList(1), Arrays.asList(2)});
@@ -315,7 +317,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -330,7 +332,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -345,9 +347,94 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
+    
+	@Test public void testJira1621() throws Exception {
+		// Create query
+		String sql = "SELECT sum(t2.e4) as s, max(t1.e1 || t2.e1) FROM pm1.g1 as t1, pm1.g2 as t2, pm1.g3 as t3 WHERE t1.e1 = coalesce(t2.e1, 'b') AND t2.e2 = t3.e2 GROUP BY t2.e2, t2.e3, t3.e2 ORDER BY s"; //$NON-NLS-1$
 
+		// Create expected results
+		List[] expected = new List[] {
+				Arrays.asList(null, "cc"),
+				Arrays.asList(0.0, "bb"),
+				Arrays.asList(2.0, null),
+				Arrays.asList(21.0, "aa"),
+				Arrays.asList(24.0, "aa")
+		};
+
+		// Construct data manager with data
+		FakeDataManager dataManager = new FakeDataManager();
+		sampleData1(dataManager);
+
+		// Plan query
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+
+		// Run query
+		helpProcess(plan, dataManager, expected);
+	}
+	
+	@Test public void testArrayAggOrderByPersistence() throws Exception {
+		// Create query
+		String sql = "SELECT array_agg(e2 order by e1) from pm1.g1 group by e3"; //$NON-NLS-1$
+
+		// Create expected results
+		List[] expected = new List[] {
+				Arrays.asList((Object)new Integer[] {1, 0, 0, 2}),
+				Arrays.asList((Object)new Integer[] {3, 1}),
+		};
+
+		// Construct data manager with data
+		FakeDataManager dataManager = new FakeDataManager();
+		sampleData1(dataManager);
+
+		// Plan query
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+		CommandContext cc = TestProcessor.createCommandContext();
+		BufferManagerImpl impl = BufferManagerFactory.getTestBufferManager(0, 2);
+		impl.setUseWeakReferences(false);
+		cc.setBufferManager(impl);
+		// Run query
+		helpProcess(plan, cc, dataManager, expected);
+	}
+	
+	@Test public void testDupGroupCombination() throws Exception {
+        String sql = "select count(e2), e1 from (select distinct e1, e2, e3 from pm1.g1) x group by e1"; //$NON-NLS-1$
+
+        List[] expected = new List[] {
+				Arrays.asList(2, "a"),
+		};
+
+		HardcodedDataManager dataManager = new HardcodedDataManager();
+		dataManager.addData("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g1.e3 FROM pm1.g1", new List[] {
+				Arrays.asList("a", 0, Boolean.TRUE),
+				Arrays.asList("a", 0, Boolean.FALSE),
+		});
+
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+		helpProcess(plan, dataManager, expected);
+	}
+	
+	@Test public void testAggFilter() throws Exception {
+		// Create query
+		String sql = "SELECT e2, count(*) filter (where e3) from pm1.g1 group by e2 order by e2"; //$NON-NLS-1$
+
+		// Create expected results
+		List[] expected = new List[] {
+				Arrays.asList(0, 0),
+				Arrays.asList(1, 1),
+				Arrays.asList(2, 0),
+				Arrays.asList(3, 1),
+		};
+
+		// Construct data manager with data
+		FakeDataManager dataManager = new FakeDataManager();
+		sampleData1(dataManager);
+
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
+		helpProcess(plan, dataManager, expected);
+	}
+
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java:3149-3217,3220-3275
/trunk/engine/src/test/java/org/teiid/query/processor/TestAggregateProcessing.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -31,6 +31,7 @@
 import org.junit.Test;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
@@ -40,9 +41,7 @@
 import org.teiid.query.processor.relational.RelationalNode;
 import org.teiid.query.processor.relational.RelationalPlan;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 @SuppressWarnings({"unchecked", "nls"})
@@ -62,7 +61,7 @@
         
         // Plan query
         ProcessorPlan plan = TestProcessor.helpGetPlan(TestProcessor.helpParse(sql),
-                                                       FakeMetadataFactory.example1Cached(),
+                                                       RealMetadataFactory.example1Cached(),
                                                        capFinder);
         return plan;
     }
@@ -88,7 +87,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -141,7 +140,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -168,7 +167,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -195,7 +194,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -221,7 +220,7 @@
         TestProcessor.sampleData1(dataManager);
        
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -246,7 +245,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -273,7 +272,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -300,7 +299,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -370,7 +369,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -395,7 +394,7 @@
        TestProcessor.sampleData1(dataManager);
        
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -419,10 +418,6 @@
              Arrays.asList(new Object[] { "cc  ", "cc  ", new Integer(2)}) //$NON-NLS-1$ //$NON-NLS-2$
         };    
 
-        // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        TestProcessor.sampleData2b(dataManager);
-
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
@@ -442,7 +437,7 @@
 
         // Slightly modify metadata to set max set size to just a few rows - this
         // will allow us to test the dependent overflow case
-        FakeMetadataFacade fakeMetadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
         
         Command command = TestProcessor.helpParse(sql);   
         ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
@@ -454,6 +449,10 @@
         RelationalNode join = project.getChildren()[0];
         assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
 
+        // Construct data manager with data
+        FakeDataManager dataManager = new FakeDataManager();
+        TestProcessor.sampleData2b(dataManager, fakeMetadata);
+
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);          
     }
@@ -467,7 +466,7 @@
         String sql = "select a.intkey from bqt1.smalla a, bqt1.smallb b where concat(a.stringkey, 't') = b.stringkey option makedep a"; //$NON-NLS-1$ 
          
         // Plan query 
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, new String[] {"SELECT a.stringkey, a.intkey FROM bqt1.smalla AS a", "SELECT b.stringkey FROM bqt1.smallb AS b"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, new String[] {"SELECT a.stringkey, a.intkey FROM bqt1.smalla AS a", "SELECT b.stringkey FROM bqt1.smallb AS b"}, TestOptimizer.SHOULD_SUCCEED); //$NON-NLS-1$ //$NON-NLS-2$
  
         TestOptimizer.checkNodeTypes(plan, new int[] { 
             2,      // Access 
@@ -527,7 +526,7 @@
         String sql = "select a.intkey from bqt1.smalla a, bqt2.smallb b where concat(a.stringkey, 't') = b.stringkey and a.intkey = b.intkey option makedep a"; //$NON-NLS-1$ 
          
         // Plan query 
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), null, capFinder, 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), null, capFinder, 
                                                     new String[] {"SELECT g_0.stringkey, g_0.intkey FROM bqt1.smalla AS g_0 WHERE g_0.intkey IN (<dependent values>)", "SELECT g_0.stringkey, g_0.intkey FROM bqt2.smallb AS g_0"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
  
         TestOptimizer.checkNodeTypes(plan, new int[] { 
@@ -564,37 +563,23 @@
 	}
     
     static void sampleData4(FakeDataManager dataMgr) throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     
-        // Group pm1.g1
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = FakeDataStore.createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
+        		metadata,
+            "pm1.g1", new List[] { 
+				    Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { "b",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { "c",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
+				    } );       
             
-            new List[] { 
-                Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { "b",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { "c",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
-                } );       
-            
-        // Group pm6.g1
-        groupID = (FakeMetadataObject) metadata.getGroupID("pm6.g1"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = FakeDataStore.createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList(new Object[] { "b",   new Integer(0) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { "d",   new Integer(3) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { "e",   new Integer(1) }), //$NON-NLS-1$
-                } );      
+        		metadata,
+            "pm6.g1", new List[] { 
+				    Arrays.asList(new Object[] { "b",   new Integer(0) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { "d",   new Integer(3) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { "e",   new Integer(1) }), //$NON-NLS-1$
+				    } );      
     }
 
     /** SELECT pm1.g1.e1 FROM pm1.g1, pm6.g1 WHERE pm1.g1.e1=pm6.g1.e1 OPTION MAKEDEP pm6.g1 */
@@ -608,7 +593,7 @@
 
         // Slightly modify metadata to set max set size to just a few rows - this
         // will allow us to test the dependent overflow case
-        FakeMetadataFacade fakeMetadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
 
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
@@ -665,7 +650,7 @@
 
         // Slightly modify metadata to set max set size to just a few rows - this
         // will allow us to test the dependent overflow case
-        FakeMetadataFacade fakeMetadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
 
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
@@ -722,10 +707,6 @@
                 "cc  ", "cc  ", new Integer(2)}) //$NON-NLS-1$ //$NON-NLS-2$
         };
 
-        // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        TestProcessor.sampleData2b(dataManager);
-
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
@@ -740,7 +721,7 @@
         capFinder.addCapabilities("pm4", depcaps); //$NON-NLS-1$
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade fakeMetadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1Cached();
 
         Command command = TestProcessor.helpParse(sql);
         ProcessorPlan plan = TestProcessor.helpGetPlan(command, fakeMetadata, capFinder);
@@ -752,6 +733,10 @@
         RelationalNode join = project.getChildren()[0];
         assertTrue("Expected instance of JoinNode (for dep join) but got " + join.getClass(), join instanceof JoinNode); //$NON-NLS-1$
 
+        // Construct data manager with data
+        FakeDataManager dataManager = new FakeDataManager();
+        TestProcessor.sampleData2b(dataManager, fakeMetadata);
+
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
     }
@@ -770,7 +755,7 @@
        TestProcessor.sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -806,7 +791,7 @@
        capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
        
        Command command = TestProcessor.helpParse(sql);   
-       ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+       ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
        // Run query
        TestProcessor.helpProcess(plan, dataManager, expected);
@@ -820,10 +805,10 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData4(dataManager);
 
-        FakeMetadataFacade fakeMetadata = FakeMetadataFactory.example1();
+        QueryMetadataInterface fakeMetadata = RealMetadataFactory.example1();
 
-        FakeMetadataFactory.setCardinality("pm1.g1", 1, fakeMetadata);
-        FakeMetadataFactory.setCardinality("pm6.g1", 1000, fakeMetadata);
+        RealMetadataFactory.setCardinality("pm1.g1", 1, fakeMetadata);
+        RealMetadataFactory.setCardinality("pm6.g1", 1000, fakeMetadata);
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities depcaps = new BasicSourceCapabilities();
@@ -854,4 +839,56 @@
         		new HashSet<String>(dataManager.getQueries()));
     }
     
+    @Test public void testDjHint() { 
+        // Create query 
+        String sql = "SELECT pm1.g1.e1 FROM pm1.g1 WHERE e1 IN /*+ DJ */ (select e1 from pm2.g1) order by pm1.g1.e1"; //$NON-NLS-1$
+        
+        // Create expected results
+        List[] expected = new List[] { 
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "c" }) //$NON-NLS-1$
+        };    
+        
+        // Construct data manager with data
+        FakeDataManager dataManager = new FakeDataManager();
+        TestProcessor.sampleData1(dataManager);
+        
+        // Plan query
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+        TestOptimizer.checkDependentJoinCount(plan, 1);
+
+        // Run query
+        TestProcessor.helpProcess(plan, dataManager, expected);
+    }
+    
+    @Test public void testMakeIndHint() { 
+        // Create query 
+        String sql = "SELECT pm1.g1.e1 FROM /*+ MAKEIND */ pm1.g1, pm2.g1 WHERE pm1.g1.e1 = pm2.g1.e1 AND pm1.g1.e2=pm2.g1.e2 order by pm1.g1.e1"; //$NON-NLS-1$
+        
+        // Create expected results
+        List[] expected = new List[] { 
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "c" }) //$NON-NLS-1$
+        };    
+        
+        // Construct data manager with data
+        FakeDataManager dataManager = new FakeDataManager();
+        TestProcessor.sampleData1(dataManager);
+        
+        // Plan query
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
+        TestOptimizer.checkDependentJoinCount(plan, 1);
+
+        // Run query
+        TestProcessor.helpProcess(plan, dataManager, expected);
+    }
+    
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java:3149-3171
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestDependentJoins.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -9,27 +9,28 @@
 
 import org.junit.Test;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.sql.lang.BatchedUpdateCommand;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.Insert;
 import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.SourceSystemFunctions;
 
-
+ at SuppressWarnings("nls")
 public class TestInsertProcessing {
 	
     @Test public void testSelectIntoWithTypeConversion() {
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); 
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); 
@@ -37,17 +38,12 @@
         caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ 
 
-        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
+        RealMetadataFactory.createElements(pm1g1, 
                                     new String[] { "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
                                     new String[] { DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.FLOAT, DataTypeManager.DefaultDataTypes.FLOAT});
                                 
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
-        FakeMetadataFacade metadata = new FakeMetadataFacade(store);
-        
         HardcodedDataManager dataManager = new HardcodedDataManager();
         dataManager.addData("BatchedUpdate{I}",  //$NON-NLS-1$ 
                             new List[] { Arrays.asList(new Object[] { new Integer(1) })}); 
@@ -103,7 +99,7 @@
 
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ 
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         HardcodedDataManager dataManager = new HardcodedDataManager();
 
@@ -150,10 +146,10 @@
     
 
     @Test public void testSelectInto_Case5412a() {
-        
+        MetadataStore metadataStore = new MetadataStore();
         // test setting BULK_INSERT capability to true
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); 
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); 
@@ -161,17 +157,12 @@
         caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ 
 
-        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
+        RealMetadataFactory.createElements(pm1g1, 
                                     new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
                                     new String[] { DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.FLOAT});
                                 
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
-        FakeMetadataFacade metadata = new FakeMetadataFacade(store);
-        
         HardcodedDataManager dataManager = new HardcodedDataManager();
         dataManager.addData("INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2) VALUES (?, ?)",  //$NON-NLS-1$ 
                             new List[] { Arrays.asList(new Object[] { new Integer(1) })}); 
@@ -190,27 +181,22 @@
 
     
     @Test public void testSelectInto_Case5412b() {
-        
+        MetadataStore metadataStore = new MetadataStore();
         // test setting BULK_INSERT capability to false
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        Table pm1g1 = RealMetadataFactory.createPhysicalGroup("g1", pm1); //$NON-NLS-1$
         
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); 
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); 
         caps.setCapabilitySupport(Capability.BULK_UPDATE, false); 
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ 
         caps.setFunctionSupport(SourceSystemFunctions.CONVERT, true);
-        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
+        RealMetadataFactory.createElements(pm1g1, 
                                     new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
                                     new String[] { DataTypeManager.DefaultDataTypes.BIG_INTEGER, DataTypeManager.DefaultDataTypes.FLOAT});
                                 
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
-        FakeMetadataFacade metadata = new FakeMetadataFacade(store);
-        
         HardcodedDataManager dataManager = new HardcodedDataManager();
         dataManager.addData("INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2) VALUES (1, 1.0)",  //$NON-NLS-1$ 
                             new List[] { Arrays.asList(new Object[] { new Integer(1) })}); 
@@ -261,7 +247,7 @@
 
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ 
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         HardcodedDataManager dataManager = new HardcodedDataManager();
 
@@ -342,7 +328,7 @@
 
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ 
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         HardcodedDataManager dataManager = new HardcodedDataManager();
 
@@ -399,7 +385,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestInsertProcessing.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -31,7 +31,7 @@
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 import junit.framework.TestCase;
 
@@ -57,7 +57,7 @@
 	 * @throws TeiidComponentException 
 	 * @throws QueryMetadataException 
 	 */
-	public void testNonDeterministicPostJoin() throws QueryMetadataException, TeiidComponentException {
+	public void testNonDeterministicPostJoin() throws Exception {
 		// source query for one side of a JOIN
 		String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 " //$NON-NLS-1$
 				+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -105,7 +105,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -127,7 +127,7 @@
 	 * @throws TeiidComponentException 
 	 * @throws QueryMetadataException 
 	 */
-	public void testNonDeterministicPreJoin() throws QueryMetadataException, TeiidComponentException {
+	public void testNonDeterministicPreJoin() throws Exception {
 		// source query for one side of a JOIN
 		String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, RAND() AS RandomLeft " //$NON-NLS-1$
 				+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -176,7 +176,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -192,7 +192,7 @@
 	 * @throws TeiidComponentException 
 	 * @throws QueryMetadataException 
 	 */
-	public void testNonDeterministicPrePostJoin() throws TeiidComponentException, QueryMetadataException {
+	public void testNonDeterministicPrePostJoin() throws Exception {
 		// source query for one side of a JOIN
 		String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, RAND() AS RandomLeft " //$NON-NLS-1$
 				+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -241,7 +241,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -256,7 +256,7 @@
 	 * @throws TeiidComponentException
 	 * @throws QueryMetadataException
 	 */
-	public void testDeterministicPostJoin() throws TeiidComponentException, QueryMetadataException {
+	public void testDeterministicPostJoin() throws Exception {
 		// source query for one side of a JOIN
 		String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 " //$NON-NLS-1$
 				+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -303,7 +303,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -322,7 +322,7 @@
 	 * @throws TeiidComponentException 
 	 * @throws QueryMetadataException 
 	 */
-	public void testDeterministicPreJoin() throws QueryMetadataException, TeiidComponentException {
+	public void testDeterministicPreJoin() throws Exception {
 		// source query for one side of a JOIN
 		String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, SQRT(100) AS SqrtLeft " //$NON-NLS-1$
 				+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -368,7 +368,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -384,7 +384,7 @@
 	 * @see #testDeterministicPostJoin
 	 * @see #testDeterministicPreJoin
 	 */
-	public void testDeterministicPrePostJoin() throws QueryMetadataException, TeiidComponentException {
+	public void testDeterministicPrePostJoin() throws Exception {
 		// sub-query for one side of a JOIN
 		String leftQuery = "SELECT pm1.g1.e1 as ID, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4, SQRT(100) AS SqrtLeft " //$NON-NLS-1$
 				+ "FROM pm1.g1"; //$NON-NLS-1$
@@ -431,7 +431,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestJoinWithFunction.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -27,7 +27,7 @@
 
 import org.junit.Test;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TestOptionalJoins {
@@ -48,7 +48,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -76,7 +76,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -101,7 +101,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -126,7 +126,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -157,7 +157,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -188,7 +188,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -213,7 +213,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -238,7 +238,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -263,7 +263,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -288,7 +288,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -313,7 +313,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -338,7 +338,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -358,7 +358,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -383,7 +383,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -408,7 +408,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -432,7 +432,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -457,7 +457,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -482,7 +482,7 @@
         TestProcessor.sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestOptionalJoins.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,12 +28,12 @@
 import java.util.List;
 
 import org.junit.Test;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.ExecutionFactory.NullOrder;
 
 @SuppressWarnings({"nls", "unchecked"})
@@ -49,7 +49,7 @@
 	    FakeDataManager dataManager = new FakeDataManager();
 	    sampleData1(dataManager);
 	    
-	    ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+	    ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
 	    
 	    helpProcess(plan, dataManager, expected);
 	}
@@ -74,7 +74,7 @@
 	    sampleData1(dataManager);
 	    
 	    // Plan query
-	    ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+	    ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
 	    
 	    // Run query
 	    helpProcess(plan, dataManager, expected);
@@ -90,7 +90,7 @@
 	    FakeDataManager dataManager = new FakeDataManager();
 	    sampleData1(dataManager);
 	    
-	    ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+	    ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
 	    
 	    helpProcess(plan, dataManager, expected);
 	}
@@ -101,7 +101,7 @@
 	@Test public void testOrderByWithDuplicateExpressions() throws Exception {
 	    String sql = "select e1 as x, e1 as y from pm1.g1 order by y ASC"; //$NON-NLS-1$
 	    
-	    FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+	    QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 	    
 	    ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
 	    
@@ -122,7 +122,7 @@
 	@Test public void testExplicitNullOrdering() throws Exception {
 		String sql = "select e1, case when e4 = 2.0 then null else e4 end as x from pm1.g1 order by e1 ASC NULLS LAST, x DESC NULLS FIRST"; //$NON-NLS-1$
 
-		FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+		QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 		ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
 
 		List[] expected = new List[] { Arrays.asList("a", null),
@@ -145,7 +145,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan("select e1 from pm1.g1 order by e1 desc, e2 asc", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), null, capFinder, 
+        		RealMetadataFactory.example1Cached(), null, capFinder, 
     			new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0 DESC NULLS LAST, g_0.e2 NULLS FIRST"},  //$NON-NLS-1$
     			TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
         
@@ -160,7 +160,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan("select e1 from pm1.g1 order by e1 desc, e2 asc", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), null, capFinder, 
+        		RealMetadataFactory.example1Cached(), null, capFinder, 
     			new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0 DESC, g_0.e2 NULLS FIRST"},  //$NON-NLS-1$
     			TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
         
@@ -174,7 +174,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan("select e1 from pm1.g1 order by e1 desc NULLS FIRST, e2 asc NULLS LAST", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), null, capFinder, 
+        		RealMetadataFactory.example1Cached(), null, capFinder, 
     			new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0 DESC NULLS FIRST, g_0.e2 NULLS LAST"},  //$NON-NLS-1$
     			TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
         
@@ -192,7 +192,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
         ProcessorPlan plan = TestOptimizer.helpPlan("select e1 from pm1.g1 order by e1 desc, e2 asc NULLS LAST", //$NON-NLS-1$ 
-        		FakeMetadataFactory.example1Cached(), null, capFinder, 
+        		RealMetadataFactory.example1Cached(), null, capFinder, 
     			new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0 DESC, g_0.e2"},  //$NON-NLS-1$
     			TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING);
         


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestOrderByProcessing.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -33,7 +33,13 @@
 import org.teiid.common.buffer.TupleSource;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.Schema;
 import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.processor.proc.CreateCursorResultSetInstruction;
 import org.teiid.query.processor.proc.ProcedurePlan;
@@ -45,19 +51,16 @@
 import org.teiid.query.sql.lang.SPParameter;
 import org.teiid.query.sql.lang.StoredProcedure;
 import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
-
+ at SuppressWarnings("nls")
 public class TestProcedureRelational {
 
     @Test public void testProcInExistsSubquery() throws Exception {
         String sql = "select pm1.g1.e1 from pm1.g1 where exists (select * from (EXEC pm1.vsp9(pm1.g1.e2 + 1)) x where x.e1 = pm1.g1.e1)"; //$NON-NLS-1$
 
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
             Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
         };    
@@ -65,7 +68,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);
 
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         TestProcessor.helpProcess(plan, dataManager, expected);
     }
@@ -73,7 +76,7 @@
     @Test public void testProcInSelectScalarSubquery() throws Exception {
         String sql = "select (EXEC pm1.vsp36(pm1.g1.e2)) from pm1.g1 where pm1.g1.e1 = 'a'"; //$NON-NLS-1$
 
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(0) }), 
             Arrays.asList(new Object[] { new Integer(6) }),
             Arrays.asList(new Object[] { new Integer(0) }), 
@@ -82,7 +85,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);
 
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         TestProcessor.helpProcess(plan, dataManager, expected);
     }
@@ -91,14 +94,14 @@
         String sql = "select param1, param2, e1, e2 from pm1.vsp26 where param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(1), "a", "a", new Integer(3)}), //$NON-NLS-1$  //$NON-NLS-2$
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -108,14 +111,14 @@
         String sql = "select param1, param2, e1, e2 from pm1.vsp26 as x where param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(1), "a", "a", new Integer(3)}), //$NON-NLS-1$  //$NON-NLS-2$
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -124,14 +127,14 @@
         String sql = "select x.param1, x.param2, y.param1, y.param2, x.e1 from pm1.vsp26 as x, pm1.vsp26 as y where x.param1=1 and x.param2='a' and y.param1 = 2 and y.param2 = 'b'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(1), "a", new Integer(2), "b", "a"}), //$NON-NLS-1$  //$NON-NLS-2$ //$NON-NLS-3$
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -141,14 +144,14 @@
         String sql = "select x.param1, x.param2, y.param1, y.param2, x.e1 from pm1.vsp26 as x, pm1.vsp26 as y where x.param1=1 and x.param2='a' and y.param1 = x.param1 and y.param2 = x.param2"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(1), "a", new Integer(1), "a", "a"}), //$NON-NLS-1$  //$NON-NLS-2$ //$NON-NLS-3$
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -159,7 +162,7 @@
     @Test public void testProcAsTable1(){
         String sql = "select param1, param2, e1, e2 from pm1.vsp26 where param1=1"; //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
     }
 
     /**
@@ -168,14 +171,14 @@
     @Test public void testProcAsTable2(){
         String sql = "select param1, param2, e1, e2 from pm1.vsp26 where param1<1 and param2='a'"; //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false); 
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false); 
     }
     
     @Test public void testProcAsTable3(){
         String sql = "select param1, param2, e1, e2 from pm1.vsp26 where param1 in (1,2,3) and param2 in ('a', 'b') order by param1, param2"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(1), "a", "a", new Integer(3)}), //$NON-NLS-1$  //$NON-NLS-2$
             Arrays.asList(new Object[] { new Integer(1), "b", "b", new Integer(2)}), //$NON-NLS-1$  //$NON-NLS-2$
             Arrays.asList(new Object[] { new Integer(2), "a", "a", new Integer(3)}), //$NON-NLS-1$  //$NON-NLS-2$
@@ -186,7 +189,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -197,7 +200,7 @@
     @Test public void testProcAsTable4(){
         String sql = "select param1, param2, e1, e2 from pm1.vsp26 where param1=1 and not(param2 = 'a')"; //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
     }
     
     /**
@@ -206,14 +209,14 @@
     @Test public void testProcAsTable5(){
         String sql = "select param1, param2, e1, e2 from pm1.vsp26 where param1=e2 and param2 = 'a'"; //$NON-NLS-1$
 
-        TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
+        TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, TestOptimizer.getGenericFinder(), null, false);
     }
     
     @Test public void testProcAsTableInJoin(){
         String sql = "select param1, param2, pm1.vsp26.e2 from pm1.vsp26, pm1.g1 where param1 = pm1.g1.e2 and param2 = pm1.g1.e1 order by param1, param2, e2"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0)}), //$NON-NLS-1$
             Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0)}), //$NON-NLS-1$
             Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0)}), //$NON-NLS-1$
@@ -228,7 +231,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -237,7 +240,7 @@
         String sql = "select param1, param2, pm1.vsp26.e2, (select count(e1) from pm1.vsp26 where param1 = 1 and param2 = 'a') x from pm1.vsp26, pm1.g1 where param1 = pm1.g1.e2 and param2 = pm1.g1.e1 order by param1, param2, e2"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0), new Integer(1)}), //$NON-NLS-1$
             Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0), new Integer(1)}), //$NON-NLS-1$
             Arrays.asList(new Object[] { new Integer(0), "a", new Integer(0), new Integer(1)}), //$NON-NLS-1$
@@ -252,7 +255,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -260,7 +263,7 @@
     private void helpTestProcRelational(String userQuery,
                                         String inputCriteria,
                                         String atomicQuery) {
-        ProcessorPlan plan = TestOptimizer.helpPlan(userQuery, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(userQuery, RealMetadataFactory.example1Cached(), 
             new String[] {} ); 
         
         RelationalPlan rplan = (RelationalPlan)plan;
@@ -295,7 +298,7 @@
         
         String userQuery = "select e1 from pm1.vsp26 where param1=1 and param2='a'"; //$NON-NLS-1$
         String inputCriteria = "(pm1.vsp26.param1 = 1) AND (pm1.vsp26.param2 = 'a')"; //$NON-NLS-1$
-        String atomicQuery = "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0 WHERE (g_0.e2 >= PM1.VSP26.param1) AND (g_0.e1 = PM1.VSP26.param2)"; //$NON-NLS-1$
+        String atomicQuery = "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0 WHERE (g_0.e2 >= pm1.vsp26.param1) AND (g_0.e1 = pm1.vsp26.param2)"; //$NON-NLS-1$
         
         helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
     }
@@ -304,7 +307,7 @@
     @Test public void testCase3403() {        
         String userQuery = "select e1 from pm1.vsp26 where param1=2 and param2='a' and 'x'='x'"; //$NON-NLS-1$
         String inputCriteria = "(pm1.vsp26.param1 = 2) AND (pm1.vsp26.param2 = 'a')"; //$NON-NLS-1$
-        String atomicQuery = "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0 WHERE (g_0.e2 >= PM1.VSP26.param1) AND (g_0.e1 = PM1.VSP26.param2)"; //$NON-NLS-1$
+        String atomicQuery = "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0 WHERE (g_0.e2 >= pm1.vsp26.param1) AND (g_0.e1 = pm1.vsp26.param2)"; //$NON-NLS-1$
         
         helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
     }
@@ -312,7 +315,7 @@
     @Test public void testCase3448() {
         String userQuery = "select e1 from pm1.vsp26 where (param1=1 and e2=2) and param2='a'"; //$NON-NLS-1$
         String inputCriteria = "(pm1.vsp26.param1 = 1) AND (pm1.vsp26.param2 = 'a')"; //$NON-NLS-1$
-        String atomicQuery = "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0 WHERE (g_0.e2 >= PM1.VSP26.param1) AND (g_0.e1 = PM1.VSP26.param2)"; //$NON-NLS-1$
+        String atomicQuery = "SELECT g_0.e1, g_0.e2 FROM pm1.g1 AS g_0 WHERE (g_0.e2 >= pm1.vsp26.param1) AND (g_0.e1 = pm1.vsp26.param2)"; //$NON-NLS-1$
         
         helpTestProcRelational(userQuery, inputCriteria, atomicQuery);
     }
@@ -321,14 +324,14 @@
         String sql = "select e1 from (SELECT * FROM pm1.vsp26 as P where P.e1='a') x where param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
         };        
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -337,14 +340,14 @@
         String sql = "select e1 from (SELECT * FROM pm1.vsp26 as P where P.e1='a') x where param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
         };        
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -353,7 +356,7 @@
         String sql = "SELECT P.e1 as ve3 FROM pm1.vsp26 as P, pm1.g2 where P.e1=g2.e1 and param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
             Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
             Arrays.asList(new Object[] { "a"}) //$NON-NLS-1$ 
@@ -362,7 +365,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -371,14 +374,14 @@
         String sql = "select e1 from (SELECT * FROM pm1.vsp26 as P where P.e1='a') x where param1=1 and param2='a' and e1='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
         };        
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -387,7 +390,7 @@
         String sql = "SELECT P.e1 as ve3 FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1 and param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
                 Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
                 Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
                 Arrays.asList(new Object[] { "a"}) //$NON-NLS-1$ 
@@ -396,7 +399,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -405,7 +408,7 @@
         String sql = "SELECT e1 FROM (SELECT p.e1, param1, param2 FROM pm1.vsp26 as P, vm1.g1 where P.e1=g1.e1) x where param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
                 Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
                 Arrays.asList(new Object[] { "a"}), //$NON-NLS-1$ 
                 Arrays.asList(new Object[] { "a"}) //$NON-NLS-1$ 
@@ -414,7 +417,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -423,12 +426,12 @@
         String sql = "select e1 from (SELECT * FROM pm1.vsp26 as P where P.e1='a') x where (param1=1 and param2='a') and e1='c'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[0];
+        List<?>[] expected = new List[0];
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
     }
@@ -437,14 +440,14 @@
         String sql = "SELECT P.e1 as ve3, P.e2 as ve4 FROM pm1.vsp26 as P where param1=1 and param2='a' and e2=3"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { "a", new Integer(3)}), //$NON-NLS-1$ 
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -454,14 +457,14 @@
         String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(1), "FOO" }), //$NON-NLS-1$ 
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }    
@@ -475,14 +478,14 @@
         String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(2112), "a" }), //$NON-NLS-1$ 
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }    
@@ -496,14 +499,14 @@
         String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(2112), null }) 
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -512,32 +515,27 @@
      *  test for defect 22376
      */
     @Test public void testParameterPassing() throws Exception {
-        FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$NON-NLS-1$
         
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("v1.rs1", v1, new String[] {"e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject rs1p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
+        ColumnSet<Procedure> rs1 = RealMetadataFactory.createResultSet("v1.rs1", new String[] {"e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
 
-        QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string VARIABLES.x = '1'; SELECT e1 FROM v1.vp2 where v1.vp2.in = VARIABLES.x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vt1 = FakeMetadataFactory.createVirtualProcedure("v1.vp1", v1, Arrays.asList(new FakeMetadataObject[] { rs1p1 }), n1); //$NON-NLS-1$
+        QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string VARIABLES.x = '1'; SELECT e1 FROM v1.vp2 where v1.vp2.in = VARIABLES.x; END"); //$NON-NLS-1$ 
+        Procedure vt1 = RealMetadataFactory.createVirtualProcedure("vp1", v1, null, n1); //$NON-NLS-1$
+        vt1.setResultSet(rs1);
         
-        FakeMetadataObject p1 = FakeMetadataFactory.createParameter("v1.vp2.in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode n2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string VARIABLES.x; declare string VARIABLES.y; VARIABLES.x = '2'; VARIABLES.y = v1.vp2.in; select VARIABLES.y; end"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vt2 = FakeMetadataFactory.createVirtualProcedure("v1.vp2", v1, Arrays.asList(new FakeMetadataObject[] { rs1p1, p1 }), n2); //$NON-NLS-1$
+        ProcedureParameter p1 = RealMetadataFactory.createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode n2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string VARIABLES.x; declare string VARIABLES.y; VARIABLES.x = '2'; VARIABLES.y = v1.vp2.in; select VARIABLES.y; end"); //$NON-NLS-1$ 
+        Procedure vt2 = RealMetadataFactory.createVirtualProcedure("vp2", v1, Arrays.asList(p1), n2); //$NON-NLS-1$
+        vt2.setResultSet(RealMetadataFactory.createResultSet("v1.rs1", new String[] {"e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }));
                 
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(v1);
-        store.addObject(rs1);
-        store.addObject(vt1);
-        store.addObject(vt2);
-        store.addObject(vt2);
-        
         String sql = "select * from (exec v1.vp1()) foo"; //$NON-NLS-1$
         
-        List[] expected = new List[] {  
+        List<?>[] expected = new List[] {  
             Arrays.asList(new Object[] { "1" }), //$NON-NLS-1$ 
         };        
         
-        FakeMetadataFacade metadata = new FakeMetadataFacade(store);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
         // Construct data manager with data 
         // Plan query 
@@ -552,14 +550,14 @@
         String sql = "SELECT P.e2 as ve3, P.e1 as ve4 FROM pm1.vsp47 as P where param1=1 and param2='a'"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
             Arrays.asList(new Object[] { new Integer(1), "FOO" }), //$NON-NLS-1$ 
         };       
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }    
@@ -572,14 +570,14 @@
         String sql = "select e1 from (SELECT * FROM pm1.vsp26 as P where P.e1='a') x where param1=1 and param2 is null"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
         };        
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
         try {
-        	ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());  
+        	ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());  
             // Run query
             TestProcessor.doProcess(plan, dataManager, expected, TestProcessor.createCommandContext()); 
             fail("QueryPlannerException was expected.");  //$NON-NLS-1$
@@ -596,14 +594,14 @@
         String sql = "select * from pm1.vsp47 where param1 is null and param2 is null"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
                 Arrays.asList(new Object[] { null, new Integer(2112), null, null }) 
         };        
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());  
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());  
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -615,13 +613,13 @@
         String sql = "select e1 from (SELECT * FROM pm1.vsp26 as P where P.e1='a') x where param1=1 and param2 = commandpayload()"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
+        List<?>[] expected = new List[] { 
         };        
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());  
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());  
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected); 
     }
@@ -632,51 +630,51 @@
      * access patterns and access patterns have a wider range of semantics.
      * 
     @Test public void testProcInVirtualGroupDefect14609_1() throws Exception{
-        helpValidate("select ve3 from vm1.vgvp1 where ve1=1.1 and ve2='a'", new String[] {"ve1 = 1.1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("select ve3 from vm1.vgvp1 where ve1=1.1 and ve2='a'", new String[] {"ve1 = 1.1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
    
     @Test public void testProcInVirtualGroupDefect14609_2() throws Exception{
-        helpValidate("select ve3 from vm1.vgvp1 where convert(ve1, integer)=1 and ve2='a'", new String[] {"convert(ve1, integer) = 1" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("select ve3 from vm1.vgvp1 where convert(ve1, integer)=1 and ve2='a'", new String[] {"convert(ve1, integer) = 1" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testProcInVirtualGroupDefect14609_3() throws Exception{
-        helpValidate("select ve3 from vm1.vgvp1 where 1.1=ve1 and ve2='a'", new String[] {"1.1 = ve1" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("select ve3 from vm1.vgvp1 where 1.1=ve1 and ve2='a'", new String[] {"1.1 = ve1" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testProcInVirtualGroupDefect14609_4() throws Exception{
-        helpValidate("select ve3 from vm1.vgvp1 where 1=convert(ve1, integer) and ve2='a'", new String[] {"1 = convert(ve1, integer)" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("select ve3 from vm1.vgvp1 where 1=convert(ve1, integer) and ve2='a'", new String[] {"1 = convert(ve1, integer)" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }    
 
     @Test public void testDefect15861() throws Exception{
-        helpValidate("select ve3 from vm1.vgvp1 where (ve1=1 or ve1=2) and ve2='a'", new String[] {"(ve1 = 1) OR (ve1 = 2)", "ve1 = 2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        helpValidate("select ve3 from vm1.vgvp1 where (ve1=1 or ve1=2) and ve2='a'", new String[] {"(ve1 = 1) OR (ve1 = 2)", "ve1 = 2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     }
 
     @Test public void testProcInVirtualGroup1_Defect20164() {
-        helpFailProcedure("select ve3 from vm1.vgvp2 where (ve1=1 and ve2='a') or ve3='c'", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpFailProcedure("select ve3 from vm1.vgvp2 where (ve1=1 and ve2='a') or ve3='c'", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     @Test public void testProcInVirtualGroup2_Defect20164() {
-        helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 or ve2='a'", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 or ve2='a'", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     @Test public void testProcInVirtualGroup3_Defect20164() {
-        helpFailProcedure("select ve3 from vm1.vgvp2, pm1.g1 where ve1=pm1.g1.e2 and ve2='a'", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpFailProcedure("select ve3 from vm1.vgvp2, pm1.g1 where ve1=pm1.g1.e2 and ve2='a'", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     @Test public void testProcInVirtualGroup4_Defect20164() {
-        helpValidate("select ve3 from vm1.vgvp2 where (ve1=1 and ve2='a') and (ve3='a' OR ve3='c')", new String[0], FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpValidate("select ve3 from vm1.vgvp2 where (ve1=1 and ve2='a') and (ve3='a' OR ve3='c')", new String[0], RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     @Test public void testProcInVirtualGroup5_Defect20164() {
-        helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 and NOT(ve2='a')", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 and NOT(ve2='a')", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     @Test public void testProcInVirtualGroup6_Defect20164() {
-        helpValidate("select ve3 from vm1.vgvp2 where ve1=1 and ve2 is null", new String[0], FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpValidate("select ve3 from vm1.vgvp2 where ve1=1 and ve2 is null", new String[0], RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     @Test public void testProcInVirtualGroup7_Defect20164() {
-        helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 and ve2 is not null", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpFailProcedure("select ve3 from vm1.vgvp2 where ve1=1 and ve2 is not null", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }*/
     
     /**
@@ -684,28 +682,22 @@
      * are set correctly.
      */
     @Test public void testIssue119() throws Exception {
-        FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$NON-NLS-1$
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
         
-        FakeMetadataObject in = FakeMetadataFactory.createParameter("v1.vp1.in1", 2, SPParameter.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("v1.vp1.rs1", v1, new String[] {"e1", "e2", "e3", "e4", "e5"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
-        FakeMetadataObject rs1p1 = FakeMetadataFactory.createParameter("ret", 1, SPParameter.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
+        ProcedureParameter in = RealMetadataFactory.createParameter("in1", SPParameter.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        ColumnSet<Procedure> rs1 = RealMetadataFactory.createResultSet("v1.vp1.rs1", new String[] {"e1", "e2", "e3", "e4", "e5"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
 
-        QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT vp1.in1 e1, x.in1 e2, x.e1 e3, y.in1 e4, y.e1 e5 FROM pm1.sp119 x, pm1.sp119 y where x.in1 = vp1.in1 and y.in1 = x.e1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vt1 = FakeMetadataFactory.createVirtualProcedure("v1.vp1", v1, Arrays.asList(new FakeMetadataObject[] { rs1p1, in }), n1); //$NON-NLS-1$
+        QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT vp1.in1 e1, x.in1 e2, x.e1 e3, y.in1 e4, y.e1 e5 FROM pm1.sp119 x, pm1.sp119 y where x.in1 = vp1.in1 and y.in1 = x.e1; END"); //$NON-NLS-1$ 
+        Procedure vt1 = RealMetadataFactory.createVirtualProcedure("vp1", v1, Arrays.asList(in), n1); //$NON-NLS-1$
+        vt1.setResultSet(rs1);
         
-        FakeMetadataObject in1 = FakeMetadataFactory.createParameter("pm1.sp119.in1", 2, SPParameter.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-		FakeMetadataObject rs3 = FakeMetadataFactory.createResultSet("pm1.sp119.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject rs3p1 = FakeMetadataFactory.createParameter("ret", 1, SPParameter.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs3);  //$NON-NLS-1$
-		FakeMetadataObject sp1 = FakeMetadataFactory.createStoredProcedure("pm1.sp119", pm1, Arrays.asList(new FakeMetadataObject[] { rs3p1, in1 }));  //$NON-NLS-1$ //$NON-NLS-2$
-
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(v1);
-        store.addObject(rs1);
-        store.addObject(vt1);
-        store.addObject(sp1);
-        
+        ProcedureParameter in1 = RealMetadataFactory.createParameter("in1", SPParameter.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+		ColumnSet<Procedure> rs3 = RealMetadataFactory.createResultSet("pm1.sp119.rs1", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ 
+		Procedure sp1 = RealMetadataFactory.createStoredProcedure("sp119", pm1, Arrays.asList(in1));  //$NON-NLS-1$ 
+		sp1.setResultSet(rs3);
+		
         String sql = "select * from (exec v1.vp1(1)) foo order by e4, e5"; //$NON-NLS-1$
         
         List<?>[] expected = new List[] {
@@ -715,7 +707,7 @@
         	Arrays.asList(1, 1, 6, 6, 11),
         };
         
-        FakeMetadataFacade metadata = new FakeMetadataFacade(store);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
         // Construct data manager with data 
         // Plan query 
@@ -749,14 +741,14 @@
     	String sql = "select e1 from pm1.vsp2 order by e1 desc limit 1"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] {
+        List<?>[] expected = new List[] {
         		Arrays.asList("c") //$NON-NLS-1$
         };        
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         TestProcessor.sampleData1(dataManager);       
         // Plan query
-        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, FakeMetadataFactory.example1Cached());  
+        ProcessorPlan plan = TestProcessor.helpGetPlan(sql, RealMetadataFactory.example1Cached());  
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
     }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestProcedureRelational.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcessor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -59,13 +59,18 @@
 import org.teiid.dqp.internal.process.PreparedPlan;
 import org.teiid.dqp.internal.process.QueryProcessorFactoryImpl;
 import org.teiid.dqp.internal.process.SessionAwareCache;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.analysis.AnalysisRecord;
-import org.teiid.query.function.FunctionLibrary;
 import org.teiid.query.function.FunctionTree;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.FakeFunctionMetadataSource;
 import org.teiid.query.optimizer.QueryOptimizer;
 import org.teiid.query.optimizer.TestOptimizer;
@@ -85,16 +90,12 @@
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.util.VariableContext;
 import org.teiid.query.sql.visitor.ReferenceCollectorVisitor;
 import org.teiid.query.tempdata.TempTableDataManager;
 import org.teiid.query.tempdata.TempTableStore;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.unittest.TimestampUtil;
 import org.teiid.query.util.CommandContext;
 import org.teiid.query.validator.Validator;
@@ -105,7 +106,16 @@
 
 	// ################################## TEST HELPERS ################################
 
-    static Command helpParse(String sql) { 
+    private static final List[] SP1RS = new List[] { 
+	            Arrays.asList(new Object[] { "a",   new Integer(0) }), //$NON-NLS-1$
+	                    Arrays.asList(new Object[] { null,  new Integer(1)}),
+	                    Arrays.asList(new Object[] { "a",   new Integer(3) }), //$NON-NLS-1$
+	                    Arrays.asList(new Object[] { "c",   new Integer(1)}), //$NON-NLS-1$
+	                    Arrays.asList(new Object[] { "b",   new Integer(2)}), //$NON-NLS-1$
+	                    Arrays.asList(new Object[] { "a",   new Integer(0) }) //$NON-NLS-1$
+	        };
+
+	static Command helpParse(String sql) { 
         // parse
         try { 
             return QueryParser.getQueryParser().parseCommand(sql);
@@ -310,7 +320,7 @@
             List record = ts.nextTuple();
             
             //handle xml
-            if(record.size() == 1){
+            if(record.size() == 1 && expectedResults[i].size() == 1){
             	Object cellValue = record.get(0);
             	if(cellValue instanceof XMLType){
                     XMLType id =  (XMLType)cellValue; 
@@ -319,6 +329,9 @@
                 		compareDocuments((String)expectedResults[i].get(0), actualDoc);
                         continue;
                 	}
+            	} else if (cellValue instanceof Object[]) {
+            		assertArrayEquals((Object[])expectedResults[i].get(0), (Object[])cellValue);
+            		continue;
             	}
             }
             
@@ -347,7 +360,7 @@
 		Properties props = new Properties();
 		props.setProperty("soap_host", "my.host.com"); //$NON-NLS-1$ //$NON-NLS-2$
 		props.setProperty("soap_port", "12345"); //$NON-NLS-1$ //$NON-NLS-2$
-		CommandContext context = new CommandContext("0", "test", "user", null, "myvdb", 1, props, false); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		CommandContext context = new CommandContext("0", "test", "user", null, "myvdb", 1, props, DEBUG); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
         context.setProcessorBatchSize(BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE);
         context.setConnectorBatchSize(BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE);
         context.setBufferManager(BufferManagerFactory.getStandaloneBufferManager());
@@ -357,7 +370,7 @@
     	
     public static void sampleData1(FakeDataManager dataMgr) {
         try { 
-        	FakeDataStore.sampleData1(dataMgr, FakeMetadataFactory.example1Cached());
+        	FakeDataStore.sampleData1(dataMgr, RealMetadataFactory.example1Cached());
         } catch(Throwable e) { 
         	throw new RuntimeException(e);
         }
@@ -372,164 +385,71 @@
     }                  
 
     private void sampleData2a(FakeDataManager dataMgr) {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     
         try { 
-            // Group pm1.g1
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = FakeDataStore.createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
+                metadata,
+                "pm1.g1", new List[] { 
+					    Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "b",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "c",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
+					    } );       
                 
-                new List[] { 
-                    Arrays.asList(new Object[] { "a",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "b",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "c",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
-                    } );       
-                
-            // Group pm2.g1
-            groupID = (FakeMetadataObject) metadata.getGroupID("pm2.g1"); //$NON-NLS-1$
-            elementIDs = metadata.getElementIDsInGroupID(groupID);
-            elementSymbols = FakeDataStore.createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList(new Object[] { "b",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "b",   new Integer(7),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "d",   new Integer(3),     Boolean.TRUE,   new Double(7.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "e",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                    } );      
+                metadata,
+                "pm2.g1", new List[] { 
+					    Arrays.asList(new Object[] { "b",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "b",   new Integer(7),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "d",   new Integer(3),     Boolean.TRUE,   new Double(7.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "e",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+					    } );      
 
-            // Group pm4.g1
-            groupID = (FakeMetadataObject) metadata.getGroupID("pm4.g1"); //$NON-NLS-1$
-            elementIDs = metadata.getElementIDsInGroupID(groupID);
-            elementSymbols = FakeDataStore.createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList(new Object[] { "aa",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "bb",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "cc",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
-                    } );              
+                metadata,
+                "pm4.g1", new List[] { 
+					    Arrays.asList(new Object[] { "aa",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "bb",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "cc",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
+					    } );              
             
         } catch(TeiidException e) { 
         	throw new RuntimeException(e);
         }
     }    
     
-    public static void sampleData2b(FakeDataManager dataMgr) {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-    
+    public static void sampleData2b(FakeDataManager dataMgr, QueryMetadataInterface metadata) {
         try { 
-            // Group pm1.g1
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = FakeDataStore.createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
+                metadata,
+                "pm1.g1", new List[] { 
+					    Arrays.asList(new Object[] { "aa ",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "bb   ",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "cc  ",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
+					    } );       
                 
-                new List[] { 
-                    Arrays.asList(new Object[] { "aa ",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "bb   ",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "cc  ",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
-                    } );       
-                
-            // Group pm2.g1
-            groupID = (FakeMetadataObject) metadata.getGroupID("pm2.g1"); //$NON-NLS-1$
-            elementIDs = metadata.getElementIDsInGroupID(groupID);
-            elementSymbols = FakeDataStore.createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList(new Object[] { "b",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "d",   new Integer(3),     Boolean.TRUE,   new Double(7.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "e",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                    } );      
+                metadata,
+                "pm2.g1", new List[] { 
+					    Arrays.asList(new Object[] { "b",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "d",   new Integer(3),     Boolean.TRUE,   new Double(7.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "e",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+					    } );      
 
-            // Group pm4.g1
-            groupID = (FakeMetadataObject) metadata.getGroupID("pm4.g1"); //$NON-NLS-1$
-            elementIDs = metadata.getElementIDsInGroupID(groupID);
-            elementSymbols = FakeDataStore.createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList(new Object[] { "aa ",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "bb   ",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "cc  ",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
-                    } );       
-            
-            
+                metadata,
+                "pm4.g1", new List[] { 
+					    Arrays.asList(new Object[] { "aa ",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "bb   ",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "cc  ",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
+					    } );       
         } catch(TeiidException e) { 
         	throw new RuntimeException(e);
         }
     }    
     
-    private void sampleData3(FakeDataManager dataMgr) {
-    	FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-    
-        try { 
-            // Group pm1.g1
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-            List elementSymbols = new ArrayList(1);
-            ElementSymbol count = new ElementSymbol("Count"); //$NON-NLS-1$
-            count.setType(Integer.class);
-            elementSymbols.add(count);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList(new Object[] { new Integer(1) }),                    
-                    } );    
-        }catch(TeiidException e) { 
-        	throw new RuntimeException(e);
-        }
-    }
-
-    private void sampleDataStringTimestamps(FakeDataManager dataMgr) {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
-    
-        try { 
-            // Group pm1.g1
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = FakeDataStore.createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                new List[] { 
-                    Arrays.asList(new Object[] { "Jan 01 2004 12:00:00",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "Dec 31 2004 12:00:00",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "Aug 01 2004 12:00:00",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
-                    } );       
-
-                                     
-        } catch(TeiidException e) { 
-        	throw new RuntimeException(e);
-        }
-    }     
-    
     private void sampleDataBQT1(FakeDataManager dataMgr) {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     
         try { 
             // Group bqt1.smalla
@@ -562,7 +482,7 @@
     }
 
 	private void sampleDataBQT2(FakeDataManager dataMgr) {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     
         String[] groups = new String[] {"bqt1.smalla", "bqt2.smalla", "bqt3.smalla" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     
@@ -593,7 +513,7 @@
      * @since 4.2
      */
     private void sampleDataBQT_defect11682(FakeDataManager dataMgr) {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     
         try { 
             List[] tuples = new List[2];
@@ -627,7 +547,7 @@
     }    
 
     private void sampleDataBQTSmall(FakeDataManager dataMgr) {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     
         try { 
             List[] tuples = new List[1];
@@ -655,7 +575,7 @@
     }
             
     private void sampleDataBQT_case1566(FakeDataManager dataMgr) throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     
         dataMgr.registerTuples(metadata, "bqt1.smalla", new List[] { //$NON-NLS-1$ 
                 createRowWithTimestamp("2002-01-01 10:00:00"), //$NON-NLS-1$
@@ -704,7 +624,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -724,7 +644,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -744,7 +664,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -765,7 +685,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -785,7 +705,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -810,7 +730,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -840,7 +760,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -871,7 +791,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -893,7 +813,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -914,7 +834,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -939,7 +859,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -962,7 +882,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -987,7 +907,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1012,7 +932,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1038,7 +958,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1064,7 +984,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1088,7 +1008,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1112,7 +1032,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1133,7 +1053,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1158,10 +1078,10 @@
         CommandContext context = createCommandContext();
         context.setProcessorBatchSize(2);
         context.setConnectorBatchSize(2);
-        context.setMetadata(FakeMetadataFactory.example1Cached());
+        context.setMetadata(RealMetadataFactory.example1Cached());
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
 
         // Run query
         helpProcess(plan, context, dataManager, expected);
@@ -1182,7 +1102,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1211,7 +1131,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1231,7 +1151,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1254,7 +1174,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1277,7 +1197,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1302,7 +1222,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1325,7 +1245,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1353,7 +1273,7 @@
         		Arrays.asList(4),
         		
         });
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
         CommandContext cc = createCommandContext();
         cc.setProcessorBatchSize(2);
         helpProcess(plan, cc, hdm, expected);
@@ -1379,7 +1299,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1402,7 +1322,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1428,7 +1348,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -1454,7 +1374,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -1480,7 +1400,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -1506,7 +1426,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -1532,7 +1452,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -1558,7 +1478,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -1577,7 +1497,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1597,34 +1517,12 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
     }
 
-    @Test public void testTempGroup() { 
-        // Create query 
-        String sql = "SELECT e1 FROM tm1.g1 WHERE e1 = 'a'"; //$NON-NLS-1$
-        
-        // Create expected results
-        List[] expected = new List[] { 
-            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "a" }), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "a" }) //$NON-NLS-1$
-        };    
-    
-        // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        sampleData1(dataManager);
-        
-        // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
-        
-        // Run query
-        helpProcess(plan, dataManager, expected);
-    }
-    
     @Test public void testSubquery1() {
    		// Create query
    		String sql = "SELECT e1 FROM (SELECT e1 FROM pm1.g1) AS x"; //$NON-NLS-1$
@@ -1644,7 +1542,7 @@
    		sampleData1(dataManager);
    		
     	// Plan query
-    	ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+    	ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
    		// Run query
    		helpProcess(plan, dataManager, expected);
@@ -1669,7 +1567,7 @@
 		sampleData1(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1691,7 +1589,7 @@
 		sampleData1(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1713,7 +1611,7 @@
 		sampleData1(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1743,7 +1641,7 @@
 		sampleData1(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1768,7 +1666,7 @@
 		sampleData1(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1793,7 +1691,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1816,7 +1714,7 @@
 		sampleData2(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1840,7 +1738,7 @@
 		sampleData2(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1863,7 +1761,7 @@
 		sampleData2(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1885,7 +1783,7 @@
 		sampleData2(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1908,7 +1806,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -1931,7 +1829,7 @@
 		sampleData2(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1953,7 +1851,7 @@
 		sampleData2(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -1976,7 +1874,7 @@
 		sampleData1(dataManager);
 
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
 		// Run query
 		helpProcess(plan, dataManager, expected);
@@ -2000,7 +1898,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2021,7 +1919,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2044,7 +1942,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2067,7 +1965,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2087,7 +1985,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2109,7 +2007,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2133,7 +2031,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2156,7 +2054,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2179,7 +2077,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2192,7 +2090,7 @@
         String sql = "SELECT e1 FROM pm1.g1 WHERE e2 < SOME (SELECT e2 FROM pm2.g1 WHERE EXISTS (SELECT e2 FROM pm2.g1))"; //$NON-NLS-1$
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         // Construct data manager with data
@@ -2235,7 +2133,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2259,7 +2157,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2277,7 +2175,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcessException(plan, dataManager);
@@ -2301,7 +2199,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2325,7 +2223,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2358,7 +2256,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         // Plan query
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.exampleBQTCached(), capFinder);
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.exampleBQTCached(), capFinder);
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2376,7 +2274,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2413,7 +2311,7 @@
         String sql = "Select e1, e2, e4 from pm2.g1 where 1=2 " + //$NON-NLS-1$
            "UNION ALL Select e1, e2, e4 from vm1.g1 outg1 where outg1.e2 in (select ing1.e2 FROM vm1.g1 ing1 WHERE outg1.e4 = ing1.e4)";//$NON-NLS-1$
         Command command = helpParse(sql);   
-        ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
         
         // Run query
         List[] expected = new List[] {
@@ -2449,7 +2347,7 @@
         // Plan query
         String sql = "Select e1, e2, e4 from vm1.g1 outg1 where outg1.e2 in (select ing1.e2 FROM vm1.g1 ing1 WHERE outg1.e4 = ing1.e4)";//$NON-NLS-1$
         Command command = helpParse(sql);   
-        ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
         
         // Run query
         List[] expected = new List[] {
@@ -2475,7 +2373,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2497,7 +2395,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2518,7 +2416,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2539,7 +2437,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2560,7 +2458,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2579,7 +2477,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2598,7 +2496,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2617,7 +2515,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2636,7 +2534,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2655,7 +2553,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2675,7 +2573,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2698,7 +2596,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2720,7 +2618,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2747,7 +2645,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2774,7 +2672,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2797,7 +2695,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2822,7 +2720,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2840,7 +2738,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2857,7 +2755,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2881,7 +2779,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2905,7 +2803,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2930,7 +2828,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2954,7 +2852,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2971,7 +2869,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -2996,7 +2894,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3013,7 +2911,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3032,7 +2930,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3055,7 +2953,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3079,7 +2977,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3106,7 +3004,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3134,7 +3032,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3153,7 +3051,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3175,7 +3073,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3197,7 +3095,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3221,7 +3119,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3244,7 +3142,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3267,7 +3165,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3290,7 +3188,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3314,7 +3212,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3338,7 +3236,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3359,7 +3257,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3384,7 +3282,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3405,7 +3303,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3430,7 +3328,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3455,7 +3353,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3489,7 +3387,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3514,7 +3412,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(query, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(query, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3536,7 +3434,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -3556,7 +3454,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -3581,7 +3479,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -3603,7 +3501,7 @@
         sampleData2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -3626,7 +3524,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3637,21 +3535,14 @@
         String sql = "EXEC pm1.sq1()"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
-            Arrays.asList(new Object[] { "a",   new Integer(0) }), //$NON-NLS-1$
-            Arrays.asList(new Object[] { null,  new Integer(1) }),
-            Arrays.asList(new Object[] { "a",   new Integer(3) }), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "c",   new Integer(1) }), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "b",   new Integer(2) }), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "a",   new Integer(0) }) //$NON-NLS-1$
-        };    
+        List[] expected = SP1RS;    
 
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3673,7 +3564,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3698,7 +3589,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3720,7 +3611,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3731,21 +3622,14 @@
         String sql = "EXEC pm1.sp1()"; //$NON-NLS-1$
 
         // Create expected results
-        List[] expected = new List[] { 
-            Arrays.asList(new Object[] { "a",   new Integer(0) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { null,  new Integer(1)}),
-                    Arrays.asList(new Object[] { "a",   new Integer(3) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "c",   new Integer(1)}), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "b",   new Integer(2)}), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { "a",   new Integer(0) }) //$NON-NLS-1$
-        };    
+        List[] expected = SP1RS;    
 
         // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        sampleData1(dataManager);
+        HardcodedDataManager dataManager = new HardcodedDataManager();
+        dataManager.addData("EXEC pm1.sp1()", expected);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3766,11 +3650,11 @@
         };    
 
         // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        sampleData1(dataManager);
+        HardcodedDataManager dataManager = new HardcodedDataManager();
+        dataManager.addData("EXEC pm1.sp1()", SP1RS);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3793,7 +3677,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3813,7 +3697,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3836,7 +3720,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3859,7 +3743,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3875,11 +3759,11 @@
         };    
 
         // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        sampleData3(dataManager);
+        HardcodedDataManager dataManager = new HardcodedDataManager();
+        dataManager.addData("INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2) VALUES ('MyString', 1)", new List[] {Arrays.asList(1)});
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3910,7 +3794,7 @@
         sampleDataBQT1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3941,7 +3825,7 @@
         sampleDataBQT1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3972,7 +3856,7 @@
         sampleDataBQT1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -3997,7 +3881,7 @@
         sampleData1(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4026,7 +3910,7 @@
         sampleDataBQT2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4065,7 +3949,7 @@
        sampleDataBQT1(dataManager);
 
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
 
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4085,7 +3969,7 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4107,7 +3991,7 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4141,7 +4025,7 @@
        sampleData1(dataManager);
 
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4171,7 +4055,7 @@
        sampleData1(dataManager);
 
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4205,7 +4089,7 @@
        sampleData1(dataManager);
 
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4235,7 +4119,7 @@
        sampleData1(dataManager);
 
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4257,7 +4141,7 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4277,7 +4161,7 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4297,7 +4181,7 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4327,7 +4211,7 @@
        Command command = QueryParser.getQueryParser().parseCommand(sql);
 
        // Plan query
-       ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.exampleBQTCached(), capFinder);
+       ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.exampleBQTCached(), capFinder);
 
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4350,7 +4234,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);       
@@ -4373,7 +4257,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);       
@@ -4396,7 +4280,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);       
@@ -4421,7 +4305,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);       
@@ -4444,7 +4328,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);       
@@ -4562,7 +4446,7 @@
                dataManager = hardCoded;
            }
             
-           FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+           QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
            FakeCapabilitiesFinder finder = new FakeCapabilitiesFinder();
            BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
            caps.setCapabilitySupport(Capability.CRITERIA_IN, pushDown);    
@@ -4595,12 +4479,36 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
    }
    
+    @Test public void testSortGroupCombination() throws Exception {
+        String sql = "select e2, max(e1) from pm1.g1 x group by e2 order by e2 desc"; //$NON-NLS-1$
+
+        FakeDataManager dataManager = new FakeDataManager();
+        sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, new List[] {
+                        Arrays.asList(3, "a"),
+                        Arrays.asList(2, "b"),
+                        Arrays.asList(1, "c"),
+                        Arrays.asList(0, "a")});
+    }
+    
+    @Test public void testUnorderedLimitWithProc() throws Exception {
+            String sql = "select e1 from (exec pm1.sq1()) x limit 1";
+        
+        FakeDataManager dataManager = new FakeDataManager();
+        sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, new List[] {Arrays.asList("a")});
+    }
+    
    @Test public void testCase3() { 
        // Create query 
        String sql = "SELECT e2, CASE e2 WHEN 1 THEN 2 ELSE null END FROM pm1.g1 WHERE e2 BETWEEN 1 AND 2"; //$NON-NLS-1$
@@ -4617,7 +4525,7 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4641,7 +4549,7 @@
        sampleData1(dataManager);
         
        // Plan query
-       ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+       ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
        // Run query
        helpProcess(plan, dataManager, expected);
@@ -4668,7 +4576,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4697,7 +4605,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);          
@@ -4725,7 +4633,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);          
@@ -4752,7 +4660,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);          
@@ -4779,7 +4687,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);          
@@ -4801,7 +4709,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);          
@@ -4827,7 +4735,7 @@
 		sampleData2(dataManager);
     
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4843,7 +4751,7 @@
 		};    
            
 		// Plan query
-		ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+		ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
 		// Run query
 		helpProcess(plan, new FakeDataManager(), expected);
@@ -4865,7 +4773,7 @@
         sampleDataBQT_defect11682(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4886,7 +4794,7 @@
         sampleData2(dataManager);
     
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4905,7 +4813,7 @@
         sampleData2(dataManager);
     
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4925,7 +4833,7 @@
         sampleData2(dataManager);
     
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4945,7 +4853,7 @@
         sampleData2(dataManager);
     
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4966,7 +4874,7 @@
         sampleData2(dataManager);
     
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -4994,7 +4902,7 @@
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
         Command command = helpParse(sql);   
-        ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.example1Cached(), capFinder);
+        ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.example1Cached(), capFinder);
 
         // Run query
         helpProcess(plan, dataManager, expected);        
@@ -5007,7 +4915,7 @@
         };    
            
         // Plan query
-        ProcessorPlan plan = helpGetPlan("EXEC pm1.vsp36(5)", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        ProcessorPlan plan = helpGetPlan("EXEC pm1.vsp36(5)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         
         // Run query
         helpProcess(plan, new FakeDataManager(), expected);
@@ -5024,11 +4932,17 @@
         
         Command command = helpParse("SELECT e5, e2, e3, e4 FROM vm1.g1c WHERE e5 >= {ts'2004-08-01 00:00:00.0'}");   //$NON-NLS-1$
         ProcessorPlan plan = helpGetPlan(command,  
-            FakeMetadataFactory.example1Cached(), capFinder);
+            RealMetadataFactory.example1Cached(), capFinder);
 
         // Construct data manager with data
         FakeDataManager dataManager = new FakeDataManager();
-        sampleDataStringTimestamps(dataManager);
+        dataManager.registerTuples(
+                RealMetadataFactory.example1Cached(),
+                "pm1.g1", new List[] { 
+					    Arrays.asList(new Object[] { "Jan 01 2004 12:00:00",   new Integer(0),     Boolean.FALSE,  new Double(2.0) }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "Dec 31 2004 12:00:00",   new Integer(1),     Boolean.TRUE,   null }), //$NON-NLS-1$
+					    Arrays.asList(new Object[] { "Aug 01 2004 12:00:00",   new Integer(2),     Boolean.FALSE,  new Double(0.0) }), //$NON-NLS-1$
+					    } );       
 
         Calendar cal = Calendar.getInstance();
         cal.set(2004, Calendar.DECEMBER, 31, 0, 0, 0);
@@ -5060,10 +4974,6 @@
             Arrays.asList(new Object[] { "bb   ", "b", new Integer(0) }) //$NON-NLS-1$ //$NON-NLS-2$ 
         };    
 
-        // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        sampleData2b(dataManager);
-    
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -5075,12 +4985,14 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm1.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm2.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
+        RealMetadataFactory.setCardinality("pm2.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata);
         
+        // Construct data manager with data
+        FakeDataManager dataManager = new FakeDataManager();
+        sampleData2b(dataManager, metadata);
+
         Command command = helpParse(sql);   
         CommandContext context = createCommandContext();
         context.setMetadata(metadata);
@@ -5107,10 +5019,6 @@
             Arrays.asList(new Object[] { "bb   ", "b", new Integer(0) }) //$NON-NLS-1$ //$NON-NLS-2$ 
         };    
 
-        // Construct data manager with data
-        FakeDataManager dataManager = new FakeDataManager();
-        sampleData2b(dataManager);
-    
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
@@ -5122,12 +5030,14 @@
         capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject g1 = metadata.getStore().findObject("pm4.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000));
-        FakeMetadataObject g2 = metadata.getStore().findObject("pm2.g1", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1));
+        QueryMetadataInterface metadata = RealMetadataFactory.example1();
+        RealMetadataFactory.setCardinality("pm4.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata);
+        RealMetadataFactory.setCardinality("pm2.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata);
         
+        // Construct data manager with data
+        FakeDataManager dataManager = new FakeDataManager();
+        sampleData2b(dataManager, metadata);
+        
         Command command = helpParse(sql);   
         CommandContext context = createCommandContext();
         context.setMetadata(metadata);
@@ -5169,7 +5079,7 @@
         sampleDataBQT2(dataManager);
 
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.exampleBQTCached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.exampleBQTCached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -5199,7 +5109,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT_STAR, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5235,7 +5145,7 @@
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5264,10 +5174,9 @@
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true);
         caps.setFunctionSupport("myrtrim", true); //$NON-NLS-1$
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
-
-        FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new FakeFunctionMetadataSource(), true));
-        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
         
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.example1Cached().getMetadataStore(), "example1", new FunctionTree("foo", new FakeFunctionMetadataSource(), true));
+        
         processPreparedStatement(sql, expected, dataManager, capFinder,
 				metadata, Arrays.asList("a    "));        
     }
@@ -5313,8 +5222,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("pm4", caps); //$NON-NLS-1$
 
-        FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new FakeFunctionMetadataSource(), true));
-        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.example1Cached().getMetadataStore(), "example1", new FunctionTree("foo", new FakeFunctionMetadataSource(), true));
         
         processPreparedStatement(sql, expected, dataManager, capFinder,
 				metadata, Arrays.asList("a")); 
@@ -5332,7 +5240,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5363,7 +5271,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5411,7 +5319,7 @@
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5459,7 +5367,7 @@
         caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5495,7 +5403,7 @@
         caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_ORDERED, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5533,7 +5441,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5572,7 +5480,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_SUM, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5605,7 +5513,7 @@
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5644,7 +5552,7 @@
         caps.setCapabilitySupport(Capability.QUERY_UNION, true);
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
 
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -5685,7 +5593,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         helpProcess(plan, dataManager, expected);         
         
@@ -5703,7 +5611,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         helpProcess(plan, dataManager, expected);         
         
@@ -5722,7 +5630,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         helpProcess(plan, dataManager, expected);         
         
@@ -5741,7 +5649,7 @@
         caps.setFunctionSupport("concat", true); //$NON-NLS-1$
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,         
                                       metadata,
@@ -5803,7 +5711,7 @@
         BasicSourceCapabilities caps = new BasicSourceCapabilities();
         capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         ProcessorPlan plan = TestOptimizer.helpPlan(sql,         
                           metadata,
@@ -5878,7 +5786,7 @@
         capFinder.addCapabilities("BQT2", new BasicSourceCapabilities()); //$NON-NLS-1$
 
         Command command = helpParse(sql);
-        ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.exampleBQTCached(), capFinder);
+        ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.exampleBQTCached(), capFinder);
         
         // Construct data manager with data        
         HardcodedDataManager dataManager = new HardcodedDataManager();
@@ -5926,7 +5834,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);   
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());       
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());       
         // Run query
         helpProcess(plan, dataManager, expected); 
     }
@@ -5945,7 +5853,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -5967,7 +5875,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -5987,7 +5895,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -6007,7 +5915,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -6027,7 +5935,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -6047,7 +5955,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -6067,7 +5975,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -6087,13 +5995,13 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
     }
     
-    @Test public void testBitwiseAggregateProc() { 
+    @Test public void testBitwiseAggregateProc() throws Exception { 
         // Create query 
         String sql = "EXEC virt.agg()"; //$NON-NLS-1$
         
@@ -6105,7 +6013,7 @@
         };    
     
         // Plan query
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleBitwise();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBitwise();
         ProcessorPlan plan = helpGetPlan(sql, metadata);
 
         // Construct data manager with data
@@ -6116,30 +6024,17 @@
         helpProcess(plan, dataManager, expected);
     }
     
-    private void sampleDataBitwise(FakeDataManager dataMgr, FakeMetadataFacade metadata) {    
-        try { 
-            // Group pm1.g1
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("phys.t"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = FakeDataStore.createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList(new Object[] { new Integer(0), "a", new Integer(1) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { new Integer(0), "a", new Integer(3) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { new Integer(0), "a", new Integer(16) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { new Integer(1), "b", new Integer(4) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { new Integer(2), "c", new Integer(2) }), //$NON-NLS-1$
-                    Arrays.asList(new Object[] { new Integer(2), "c", new Integer(1) }), //$NON-NLS-1$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());    //$NON-NLS-1$ //$NON-NLS-2$
-        }
+    private void sampleDataBitwise(FakeDataManager dataMgr, QueryMetadataInterface metadata) throws Exception {    
+        dataMgr.registerTuples(
+            metadata,
+            "phys.t", new List[] { 
+				    Arrays.asList(new Object[] { new Integer(0), "a", new Integer(1) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Integer(0), "a", new Integer(3) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Integer(0), "a", new Integer(16) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Integer(1), "b", new Integer(4) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Integer(2), "c", new Integer(2) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Integer(2), "c", new Integer(1) }), //$NON-NLS-1$
+				    } );    
     }  
     
     @Test public void testFunctionGroupByInJoinCriteria() {  
@@ -6158,41 +6053,33 @@
         sampleData1(dataManager); 
          
         // Plan query 
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached()); 
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached()); 
  
         // Run query 
         helpProcess(plan, dataManager, expected); 
     }
 
-    private FakeMetadataFacade createProjectErrorMetadata() {
-        FakeMetadataObject p1 = FakeMetadataFactory.createPhysicalModel("p1"); //$NON-NLS-1$
-        FakeMetadataObject t1 = FakeMetadataFactory.createPhysicalGroup("p1.t", p1); //$NON-NLS-1$
-        List e1 = FakeMetadataFactory.createElements(t1, new String[] {"a", "b" }, new String[] { "string", "string" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+    private TransformationMetadata createProjectErrorMetadata() {
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema p1 = RealMetadataFactory.createPhysicalModel("p1", metadataStore); //$NON-NLS-1$
+        Table t1 = RealMetadataFactory.createPhysicalGroup("t", p1); //$NON-NLS-1$
+        RealMetadataFactory.createElements(t1, new String[] {"a", "b" }, new String[] { "string", "string" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
         
-        FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
+        Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$NON-NLS-1$
         QueryNode n1 = new QueryNode("SELECT convert(a, integer) as c, b FROM p1.t"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vt1 = FakeMetadataFactory.createVirtualGroup("v1.t1", v1, n1); //$NON-NLS-1$
-        List vte1 = FakeMetadataFactory.createElements(vt1, new String[] {"c", "b" }, new String[] { "integer", "string" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        Table vt1 = RealMetadataFactory.createVirtualGroup("t1", v1, n1); //$NON-NLS-1$
+        RealMetadataFactory.createElements(vt1, new String[] {"c", "b" }, new String[] { "integer", "string" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 
         QueryNode n3 = new QueryNode("SELECT c, b FROM v1.t1 UNION ALL SELECT c, b FROM v1.t1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vu1 = FakeMetadataFactory.createVirtualGroup("v1.u1", v1, n3); //$NON-NLS-1$
-        List vtu1 = FakeMetadataFactory.createElements(vu1, new String[] {"c", "b" }, new String[] { "integer", "string" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        Table vu1 = RealMetadataFactory.createVirtualGroup("u1", v1, n3); //$NON-NLS-1$
+        RealMetadataFactory.createElements(vu1, new String[] {"c", "b" }, new String[] { "integer", "string" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
         
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(p1);
-        store.addObject(t1);
-        store.addObjects(e1);
-        store.addObject(v1);
-        store.addObject(vt1);
-        store.addObjects(vte1);
-        store.addObject(vu1);
-        store.addObjects(vtu1);
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "projectError");
     }
     
     @Test public void testProjectionErrorOverUnionWithConvert() {  
         // Create query  
-        FakeMetadataFacade metadata = createProjectErrorMetadata();
+        QueryMetadataInterface metadata = createProjectErrorMetadata();
         String sql = "SELECT COUNT(*) FROM v1.u1"; //$NON-NLS-1$ 
          
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
@@ -6221,7 +6108,7 @@
         String sql = "update vm1.g39 set e2=3"; //$NON-NLS-1$ 
  
         // Plan query 
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());        
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());        
 
         // Construct data manager with data 
         HardcodedDataManager dataManager = new HardcodedDataManager(); 
@@ -6252,7 +6139,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
         
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -6264,18 +6151,16 @@
      * 
      */    
     @Test public void testInsertTempTableCreation() {
-        FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$NON-NLS-1$
         QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN insert into #temp (var1) values (1); select #temp.var1 from #temp; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs = FakeMetadataFactory.createResultSet("rs", v1, new String[] { "var1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject paramRS = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs);  //$NON-NLS-1$
-        FakeMetadataObject vp = FakeMetadataFactory.createVirtualProcedure("v1.vp", v1, Arrays.asList(new Object[] {paramRS}), n1); //$NON-NLS-1$
+        ColumnSet<Procedure> rs = RealMetadataFactory.createResultSet("rs", new String[] { "var1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vp = RealMetadataFactory.createVirtualProcedure("vp", v1, null, n1); //$NON-NLS-1$
+        vp.setResultSet(rs);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(v1);
-        store.addObject(vp);
+        ProcessorPlan plan = helpGetPlan("exec v1.vp()", metadata); //$NON-NLS-1$
         
-        ProcessorPlan plan = helpGetPlan("exec v1.vp()", new FakeMetadataFacade(store)); //$NON-NLS-1$
-        
         List[] expected = new List[] {
             Arrays.asList(new Object[] { new Integer(1) })
         };
@@ -6283,18 +6168,16 @@
     }
     
     @Test public void testInsertTempTableCreation1() {
-        FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$NON-NLS-1$
         QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN insert into #temp (var1) values (1); select 2 as var1 into #temp; select #temp.var1 from #temp; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs = FakeMetadataFactory.createResultSet("rs", v1, new String[] { "var1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject paramRS = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs);  //$NON-NLS-1$
-        FakeMetadataObject vp = FakeMetadataFactory.createVirtualProcedure("v1.vp", v1, Arrays.asList(new Object[] {paramRS}), n1); //$NON-NLS-1$
+        ColumnSet<Procedure> rs = RealMetadataFactory.createResultSet("rs", new String[] { "var1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vp = RealMetadataFactory.createVirtualProcedure("vp", v1, null, n1); //$NON-NLS-1$
+        vp.setResultSet(rs);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(v1);
-        store.addObject(vp);
+        ProcessorPlan plan = helpGetPlan("exec v1.vp()", metadata); //$NON-NLS-1$
         
-        ProcessorPlan plan = helpGetPlan("exec v1.vp()", new FakeMetadataFacade(store)); //$NON-NLS-1$
-        
         List[] expected = new List[] {
             Arrays.asList(new Object[] { new Integer(1) }),
             Arrays.asList(new Object[] { new Integer(2) })
@@ -6313,7 +6196,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$ 
  
         Command command = helpParse(sql); 
-        ProcessorPlan plan = helpGetPlan(command, FakeMetadataFactory.exampleBQTCached(), capFinder); 
+        ProcessorPlan plan = helpGetPlan(command, RealMetadataFactory.exampleBQTCached(), capFinder); 
  
         // Run query  
         // Create expected results  
@@ -6334,7 +6217,7 @@
     }
         
     private void sampleDataBQT2a(FakeDataManager dataMgr) throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     
         String[] groups = new String[] {"bqt1.smalla", "bqt2.smalla", "bqt3.smalla" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     
@@ -6388,7 +6271,7 @@
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
         capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6425,7 +6308,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6455,7 +6338,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6485,7 +6368,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6515,7 +6398,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6545,7 +6428,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6575,7 +6458,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6605,7 +6488,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6635,7 +6518,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6665,7 +6548,7 @@
         capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$
         capFinder.addCapabilities("BQT3", caps); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         Command command = helpParse(sql);   
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder);
@@ -6690,7 +6573,7 @@
         HardcodedDataManager dataManager = new HardcodedDataManager();
         dataManager.addData("SELECT DISTINCT g_0.e1 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (SELECT g_0.e1 FROM pm1.g3 AS g_1)", expected); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         // Plan query
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
@@ -6718,7 +6601,7 @@
 
         // Plan query
         String sql = "SELECT e1 FROM pm1.g2 WHERE LOOKUP('pm1.g1','e1', 'e2', 0) = e1";//$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         Command command = TestProcessor.helpParse(sql);   
         CommandContext context = createCommandContext();
         ProcessorPlan plan = helpGetPlan(command, metadata, capFinder, context);
@@ -6736,7 +6619,7 @@
     
     @Test public void testRaiseNullWithSelectInto() {
         String sql = "select pm1.g1.e1, pm1.g1.e2, pm1.g1.e3, pm1.g1.e4 into pm1.g2 from pm1.g1 where (1=0)"; //$NON-NLS-1$
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder()); 
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder()); 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
                 0,      // Access
@@ -6768,7 +6651,7 @@
      */
     @Test public void testCase6219() {
         String sql = "SELECT e1 FROM pm1.g1, (SELECT 'ACT' AS StateCode,'A' AS StateAbbrv UNION ALL SELECT 'NSW' AS StateCode, 'N' AS StateAbbrv) AS StateNames_Abbrvs WHERE (pm1.g1.e1 = StateCode) AND ((StateNames_Abbrvs.StateAbbrv || pm1.g1.e1) = 'VVIC')"; //$NON-NLS-1$
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder()); 
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder()); 
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
                 0,      // Access
@@ -6799,7 +6682,7 @@
     @Test public void testSortWithLimit() {
         String sql = "select e1 from (select pm1.g1.e1, pm1.g1.e2 from pm1.g1 order by pm1.g1.e1, pm1.g1.e2 limit 1) x"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
         
@@ -6815,7 +6698,7 @@
     @Test public void testSortWithLimit1() {
         String sql = "select c from (select pm1.g1.e1 a, pm1.g1.e2 b, pm1.g1.e3 c from pm1.g1 order by b limit 1) x"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata);
         
@@ -6833,7 +6716,7 @@
     @Test public void testSortWithLimit2() {
         String sql = "select a from (select max(e2) a from pm1.g1 group by e2 order by a limit 1) x where a = 0"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -6852,7 +6735,7 @@
     @Test public void testSortWithLimit3() {
         String sql = "select c from (select pm1.g1.e3 c from pm1.g1 order by pm1.g1.e2 limit 1) x"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -6868,7 +6751,7 @@
     @Test public void testSortWithLimit4() {
         String sql = "select c from (select pm1.g1.e1 a, pm1.g1.e2 b, pm1.g1.e3 c from pm1.g1 order by b limit 1) x"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_ORDERBY_UNRELATED, false);
@@ -6884,11 +6767,32 @@
         helpProcess(plan, manager, expected);
         assertEquals("SELECT g_0.e3 AS c_0, g_0.e2 AS c_1 FROM pm1.g1 AS g_0 ORDER BY c_1", manager.getQueries().iterator().next()); //$NON-NLS-1$
     }
+    
+    @Test public void testSortWithOffset() {
+        String sql = "select e1 from (select pm1.g1.e1, pm1.g1.e2 from pm1.g1 order by pm1.g1.e1, pm1.g1.e2 offset 4 rows) x"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+        FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = new BasicSourceCapabilities();
+        caps.setCapabilitySupport(Capability.ROW_OFFSET, true);
+        caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+        
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, capFinder);
+        
+        List[] expected = new List[] {
+                Arrays.asList(new Object[] { "a"}),
+        };
 
+        HardcodedDataManager manager = new HardcodedDataManager(RealMetadataFactory.example1Cached());
+        manager.addData("SELECT g1.e1, g1.e2 FROM g1 ORDER BY g1.e1, g1.e2 LIMIT 4, 2147483647", new List[] {Arrays.asList("a", 1)});
+        helpProcess(plan, manager, expected);
+    }
+
     @Test public void testCountWithHaving() {
         String sql = "select e1, count(*) from pm1.g1 group by e1 having count(*) > 1"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -6904,7 +6808,7 @@
     @Test public void testLimitZero() {
         String sql = "select e1 from pm1.g1 limit 0"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -6921,7 +6825,7 @@
     @Test public void testLimitZero1() {
         String sql = "select distinct vm1.g1.e1, y.e1 from vm1.g1 left outer join (select 1 x, e1 from vm1.g2 limit 0) y on vm1.g1.e1 = y.e1 where vm1.g1.e1 = 'a'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -6954,7 +6858,7 @@
     @Test public void testLimitZero2() {
         String sql = "select vm1.g1.e1 from vm1.g1 union select e1 from pm1.g2 limit 0"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -6974,7 +6878,7 @@
         
         String sql = "select e1 from pm1.g2 limit 0"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, capFinder);
         
@@ -6989,7 +6893,7 @@
     @Test public void testUnionWithTypeConversion() {
         String sql = "select pm1.g1.e1, pm1.g1.e2 from pm1.g1 where e1 = 'b' union select e2, e1 from pm1.g2 where e1 = 'b' order by e1, e2"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7014,7 +6918,7 @@
     @Test public void testNonDeterministicEvaluation() throws Exception {
         String sql = "select e1, convert(rand()*1000, integer) as x from pm1.g1 where e1 = 'a'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7035,7 +6939,7 @@
     @Test public void testDeterministicEvaluation() throws Exception {
         String sql = "select e1, convert(rand(0)*1000, integer) as x from pm1.g1 where e1 = 'a'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7053,7 +6957,7 @@
     @Test public void testEmptyAggregate() throws Exception {
         String sql = "select count(e1) from pm1.g1 where 1 = 0"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7069,7 +6973,7 @@
     @Test public void testNullAggregate() throws Exception {
         String sql = "select count(*), count(e1), sum(convert(e1, integer)) from pm1.g1 where e1 is null"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7088,7 +6992,7 @@
     @Test public void testNullAggregate1() throws Exception {
         String sql = "select e1 from pm1.g1 where 1 = 0 group by e1"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7103,7 +7007,7 @@
     @Test public void testReferenceReplacementWithExpression() throws Exception {
         String sql = "select e1, e2 from (select e1, convert(e2, string) e2 from pm1.g1) x where exists (select e3 from pm1.g2 where x.e2 = e1)"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7145,7 +7049,7 @@
         sampleDataBQT2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.exampleBQTCached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.exampleBQTCached(), 
                                                     new String[] {"SELECT b.intkey FROM bqt2.SMALLA AS b", "SELECT a.intkey FROM bqt1.smalla AS a"}, new DefaultCapabilitiesFinder(), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
 
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -7191,7 +7095,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     new String[] {"SELECT a.e4, a.e2 FROM pm1.g1 AS a", "SELECT b.e4, b.e2 FROM pm1.g2 AS b"}, new DefaultCapabilitiesFinder(), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -7234,7 +7138,7 @@
         sampleData1(dataManager);
         
         // Plan query
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), 
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), 
                                                     new String[] {"SELECT a.e4, a.e2 FROM pm1.g1 AS a", "SELECT b.e4, b.e2 FROM pm1.g2 AS b"}, new DefaultCapabilitiesFinder(), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$
         
         TestOptimizer.checkNodeTypes(plan, new int[] {
@@ -7269,7 +7173,7 @@
         caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true);
         capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         List[] expected = new List[] {
             Arrays.asList("a", "b"), //$NON-NLS-1$ //$NON-NLS-2$
@@ -7277,7 +7181,10 @@
         };
 
         HardcodedDataManager manager = new HardcodedDataManager();
-        manager.addData("SELECT 'a', pm1.g1.e1 FROM pm1.g1", expected); //$NON-NLS-1$ 
+        manager.addData("SELECT pm1.g1.e1 FROM pm1.g1", new List[] {
+                Arrays.asList("b"), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList("c") //$NON-NLS-1$ //$NON-NLS-2$
+            }); //$NON-NLS-1$ 
         
         processPreparedStatement("select ?, e1 from pm1.g1", expected, manager, capFinder,
 				metadata, Arrays.asList("a")); 
@@ -7298,7 +7205,7 @@
         sampleData2(dataManager);
         
         // Plan query
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         // Run query
         helpProcess(plan, dataManager, expected);
@@ -7320,7 +7227,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData2(dataManager);
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, new String[] {"SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 6"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, new String[] {"SELECT pm1.g1.e1 FROM pm1.g1 LIMIT 6"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         helpProcess(plan, dataManager, expected);          
     }
     
@@ -7338,7 +7245,7 @@
         		Arrays.asList(Integer.valueOf(2))
         });
         
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached());
 
         List[] expected = new List[] {
                 Arrays.asList(new Object[] { "b" }), //$NON-NLS-1$
@@ -7369,7 +7276,7 @@
     	"   SELECT CONVERT(e2, long) AS e2 FROM pm1.g1 AS A WHERE e1 = 'a'" + //$NON-NLS-1$
     	") AS A"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, TestOptimizer.getGenericFinder());
         
@@ -7392,7 +7299,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7416,7 +7323,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7432,7 +7339,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7451,7 +7358,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7471,7 +7378,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7492,7 +7399,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7507,14 +7414,14 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
     
     @Test public void testUncorrelatedScalarSubqueryPushdown() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
@@ -7540,7 +7447,7 @@
     
     @Test public void testNonDeterministicScalarSubquery() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
@@ -7564,7 +7471,7 @@
     
     @Test public void testUncorrelatedScalarSubqueryPushdown1() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
@@ -7598,7 +7505,7 @@
         HardcodedDataManager dataManager = new HardcodedDataManager();
         dataManager.addData("SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", new List[] {Arrays.asList(1, "2"), Arrays.asList(3, "4")});
         dataManager.addData("EXEC pm1.sp2(1)", new List[] {Arrays.asList("b", 2)});
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7613,7 +7520,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7628,7 +7535,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example4(), TestOptimizer.getGenericFinder());
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example4(), TestOptimizer.getGenericFinder());
         
         helpProcess(plan, dataManager, expected);
     }
@@ -7643,10 +7550,68 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        ProcessorPlan plan = helpGetPlan(sql, FakeMetadataFactory.example4(), TestOptimizer.getGenericFinder());
+        BasicSourceCapabilities caps = getTypicalCapabilities();
+        caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, false);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example4(), new DefaultCapabilitiesFinder(caps));
         
         helpProcess(plan, dataManager, expected);
     }
     
+    @Test public void testDupSelect() throws Exception {
+    	String sql = "select e1, e1 from pm1.g1";
+        
+    	HardcodedDataManager dataManager = new HardcodedDataManager();
+    	
+    	dataManager.addData("SELECT g_0.e1 FROM pm1.g1 AS g_0", new List[] {Arrays.asList(1)});
+        
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, new List[] {Arrays.asList(1, 1)});
+    }
+    
+    @Test public void testDupSelect1() throws Exception {
+    	String sql = "select 1, 2 from pm1.g1";
+        
+    	HardcodedDataManager dataManager = new HardcodedDataManager();
+    	
+    	dataManager.addData("SELECT 2 FROM pm1.g1 AS g_0", new List[] {Arrays.asList(2)});
+        
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, new List[] {Arrays.asList(1, 2)});
+    }
+    
+    @Test public void testDupSelectWithOrderBy() throws Exception {
+    	String sql = "select e1 as a, e1 as b from pm1.g1 order by b";
+        
+    	HardcodedDataManager dataManager = new HardcodedDataManager();
+    	
+    	//note that the command is referencing c_0
+    	dataManager.addData("SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", new List[] {Arrays.asList(1)});
+        
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, new List[] {Arrays.asList(1, 1)});
+    }
+    
+    @Test public void testOrderByExpression() throws Exception {
+    	String sql = "SELECT pm1.g1.e2 as y FROM pm1.g1 ORDER BY e3 || e1";
+        
+    	List[] expected = new List[] {
+        		Arrays.asList(1),
+        		Arrays.asList(0),
+        		Arrays.asList(0),
+        		Arrays.asList(2),
+        		Arrays.asList(3),
+        		Arrays.asList(1),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
     private static final boolean DEBUG = false;
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestProcessor.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestProcessor.java:3149-3171
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestProcessor.java:3149-3217,3220-3275
/trunk/engine/src/test/java/org/teiid/query/processor/TestProcessor.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -38,12 +38,18 @@
 import org.teiid.api.exception.query.ExpressionEvaluationException;
 import org.teiid.core.types.BlobImpl;
 import org.teiid.core.types.BlobType;
+import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.types.InputStreamFactory;
 import org.teiid.core.util.ObjectConverterUtil;
 import org.teiid.core.util.TimestampWithTimezone;
 import org.teiid.core.util.UnitTestUtil;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.unittest.TimestampUtil;
 
 @SuppressWarnings({"nls", "unchecked"})
@@ -187,6 +193,32 @@
         process(sql, expected);
     }
     
+    @Test public void testXmlTableInView() throws Exception {
+        String sql = "select * from g1"; //$NON-NLS-1$
+        
+        List<?>[] expected = new List<?>[] {
+        		Arrays.asList(null, "first"),
+        		Arrays.asList("attr", "second"),
+        };    
+        
+		MetadataStore metadataStore = new MetadataStore();
+	    // Create models
+	    Schema vm1 = RealMetadataFactory.createVirtualModel("vm1", metadataStore);  //$NON-NLS-1$
+	
+	    QueryNode vm1g1n1 = new QueryNode("select * from xmltable('/a/b' passing convert('<a><b>first</b><b x=\"attr\">second</b></a>', xml) columns x string path '@x', val string path '/.') as x"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table vm1g1 = RealMetadataFactory.createVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+	    
+	    RealMetadataFactory.createElements(vm1g1, 
+	                                new String[] { "x", "val" }, //$NON-NLS-1$
+	                                new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	    // Create the facade from the store
+	    TransformationMetadata metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
+
+	    ProcessorPlan plan = helpGetPlan(helpParse(sql), metadata, new DefaultCapabilitiesFinder(), createCommandContext());
+        
+        helpProcess(plan, createCommandContext(), dataManager, expected);
+    }
+    
 	@Test public void testXmlTableDefaultAndParent() throws Exception {
         String sql = "select * from xmltable('/a/b' passing convert('<a y=\"rev\"><b>first</b><b x=\"1\">second</b></a>', xml) columns x integer default -1 path '@x' , val string path '../@y') as x"; //$NON-NLS-1$
         
@@ -202,8 +234,8 @@
         String sql = "select * from xmltable('/a/b' passing convert('<a><b>first</b><b x=\"1\">second</b></a>', xml) columns val xml path '.') as x"; //$NON-NLS-1$
         
         List<?>[] expected = new List<?>[] {
-        		Arrays.asList("<b>first</b>"),
-        		Arrays.asList("<b x=\"1\">second</b>"),
+        		Arrays.asList("<b xmlns=\"\">first</b>"),
+        		Arrays.asList("<b xmlns=\"\" x=\"1\">second</b>"),
         };    
     
         process(sql, expected);
@@ -271,7 +303,27 @@
     
         process(sql, expected);
     }
+
+    @Test public void testXmlQueryEmptyNullString() throws Exception {
+    	String sql = "select xmlquery('/a/b' passing xmlparse(document '<x/>') null on empty)"; //$NON-NLS-1$
+        
+        List<?>[] expected = new List<?>[] {
+        		Arrays.asList((String)null)
+        };    
     
+        process(sql, expected);
+    }
+    
+    @Test public void testXmlQueryStreaming() throws Exception {
+    	String sql = "select xmlquery('/a/b' passing xmlparse(document '<a><b x=''1''/><b x=''2''/></a>') null on empty)"; //$NON-NLS-1$
+        
+        List<?>[] expected = new List<?>[] {
+        		Arrays.asList("<b xmlns=\"\" x=\"1\"/><b xmlns=\"\" x=\"2\"/>")
+        };    
+    
+        process(sql, expected);
+    }
+    
     @Test public void testXmlNameEscaping() throws Exception {
     	String sql = "select xmlforest(\"xml\") from (select 1 as \"xml\") x"; //$NON-NLS-1$
         
@@ -338,7 +390,7 @@
         		Arrays.asList(ObjectConverterUtil.convertToString(new FileInputStream(UnitTestUtil.getTestDataFile("udf.xmi")))),
         };    
     
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(TestTextTable.clobFromFile("udf.xmi")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(TestTextTable.clobFromFile("udf.xmi")));
     }
 	
 	@Test public void testXmlParseBlob() throws Exception {
@@ -348,7 +400,7 @@
         		Arrays.asList(ObjectConverterUtil.convertToString(new FileInputStream(UnitTestUtil.getTestDataFile("udf.xmi")))),
         };    
     
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(blobFromFile("udf.xmi")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(blobFromFile("udf.xmi")));
     }
 	
 	@Test public void testXmlParseBlobWithEncoding() throws Exception {
@@ -358,7 +410,7 @@
         		Arrays.asList(ObjectConverterUtil.convertToString(new InputStreamReader(new FileInputStream(UnitTestUtil.getTestDataFile("encoding.xml")), Charset.forName("ISO-8859-1")))),
         };    
     
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(blobFromFile("encoding.xml")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(blobFromFile("encoding.xml")));
     }
 	
     @Test public void testXmlTableTypes() throws Exception {
@@ -371,6 +423,27 @@
         process(sql, expected);
     }
     
+    @Test public void testXmlTableStreamingParentAttributes() throws Exception {
+        String sql = "select * from xmltable('/a/b' passing xmlparse(document '<a x=''1''><b>foo</b></a>') columns y string path '.', x integer path '../@x') as x"; //$NON-NLS-1$
+        List<?>[] expected = new List<?>[] {
+        		Arrays.asList("foo", 1),
+        };    
+        process(sql, expected);
+    }
+    
+    /**
+     * Highlights that the PathMapFilter needs to be selective in calling startContent
+     * @throws Exception
+     */
+    @Test public void testXmlStreamingError() throws Exception {
+        String sql = "select * from xmltable('/a/a' passing xmlparse(document '<a><a>2000-01-01T01:01:00.2-06:00<a></a></a></a>') columns x timestamp path 'xs:dateTime(./text())') as x"; //$NON-NLS-1$
+        Timestamp ts = TimestampUtil.createTimestamp(100, 0, 1, 1, 1, 0, 200000000);
+        List<?>[] expected = new List<?>[] {
+        		Arrays.asList(ts),
+        };    
+        process(sql, expected);
+    }
+    
 	@Test public void testXmlTableSubquery() throws Exception {
 		String sql = "select * from xmltable('/a/b' passing convert('<a><b>first</b><b x=\"attr\">c</b></a>', xml) columns x string path '@x', val string path '/.') as x where val = (select max(e1) from pm1.g1 as x)";
     	
@@ -393,7 +466,7 @@
     }
     
 	private void process(String sql, List<?>[] expected) throws Exception {
-        ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), createCommandContext());
+        ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), createCommandContext());
         
         helpProcess(plan, createCommandContext(), dataManager, expected);
 	}


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java:3149-3217,3220-3275,3281-3325,3340-3349
/trunk/engine/src/test/java/org/teiid/query/processor/TestSQLXMLProcessing.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,7 +30,7 @@
 import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
 import org.teiid.query.processor.ProcessorPlan;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 import junit.framework.TestCase;
@@ -58,7 +58,7 @@
         }); 
         
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached());
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached());
         
         // Run query
         TestProcessor.helpProcess(plan, dataManager, expected);
@@ -86,7 +86,7 @@
             }});
         
         Command command = TestProcessor.helpParse(sql);   
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, FakeMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, RealMetadataFactory.example1Cached(), new DefaultCapabilitiesFinder(), context);
         
         // Run query
         TestProcessor.helpProcess(plan, context, dataManager, expected);


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestSecurityFunctions.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -30,7 +30,7 @@
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TestSetProcessing {
@@ -38,7 +38,7 @@
     @Test public void testExcept() throws Exception {
         String sql = "select e1, e2 from pm1.g2 except select e1, 1 from pm1.g2"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), new String[] {"SELECT pm1.g2.e1 FROM pm1.g2", "SELECT pm1.g2.e1, pm1.g2.e2 FROM pm1.g2"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), new String[] {"SELECT pm1.g2.e1 FROM pm1.g2", "SELECT pm1.g2.e1, pm1.g2.e2 FROM pm1.g2"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  //$NON-NLS-2$
         
         List<?>[] expected = new List[] {
             Arrays.asList(new Object[] {"a", 0}), //$NON-NLS-1$
@@ -54,7 +54,7 @@
     @Test public void testIntersect() throws Exception {
         String sql = "select e1, e2 from pm1.g2 intersect select e1, 1 from pm1.g2"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), new String[] {"SELECT pm1.g2.e1 FROM pm1.g2", "SELECT pm1.g2.e1, pm1.g2.e2 FROM pm1.g2"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  //$NON-NLS-2$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(), new String[] {"SELECT pm1.g2.e1 FROM pm1.g2", "SELECT pm1.g2.e1, pm1.g2.e2 FROM pm1.g2"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$  //$NON-NLS-2$
         
         List<?>[] expected = new List[] {
             Arrays.asList(new Object[] {null, 1}),
@@ -69,7 +69,7 @@
     @Test public void testIntersectExcept() {
         String sql = "select e1, e2 from pm1.g2 except select e1, 1 from pm1.g2 intersect select 'a', e2 from pm1.g2"; //$NON-NLS-1$
         
-        ProcessorPlan plan = TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), new String[] {"SELECT g_0.e1, 1 FROM pm1.g2 AS g_0", "SELECT g_0.e1, g_0.e2 FROM pm1.g2 AS g_0", "SELECT 'a', g_0.e2 FROM pm1.g2 AS g_0"}); //$NON-NLS-1$  //$NON-NLS-2$ //$NON-NLS-3$
+        ProcessorPlan plan = TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), new String[] {"SELECT g_0.e1 FROM pm1.g2 AS g_0", "SELECT g_0.e1, g_0.e2 FROM pm1.g2 AS g_0", "SELECT g_0.e2 FROM pm1.g2 AS g_0"}); //$NON-NLS-1$  //$NON-NLS-2$ //$NON-NLS-3$
         
         List<?>[] expected = new List[] {
             Arrays.asList(new Object[] {null, 1}),


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestSetProcessing.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestTempTables.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestTempTables.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -42,7 +42,7 @@
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.tempdata.TempTableDataManager;
 import org.teiid.query.tempdata.TempTableStore;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 @SuppressWarnings({"nls", "unchecked"})
@@ -68,7 +68,7 @@
 
 	@Before public void setUp() {
 		tempStore = new TempTableStore("1"); //$NON-NLS-1$
-		metadata = new TempMetadataAdapter(FakeMetadataFactory.example1Cached(), tempStore.getMetadataStore());
+		metadata = new TempMetadataAdapter(RealMetadataFactory.example1Cached(), tempStore.getMetadataStore());
 		metadata.setSession(true);
 		FakeDataManager fdm = new FakeDataManager();
 	    TestProcessor.sampleData1(fdm);
@@ -197,6 +197,15 @@
 		execute("select * from x where e1 like 'z%'", new List[0]); //$NON-NLS-1$
 	}
 	
+	@Test public void testLikeRegexWithIndex() throws Exception {
+		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (3, 'ab')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select * from x where e1 like_regex '^b?.*'", new List[] {Arrays.asList("ab", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
+		execute("select * from x where e1 like_regex '^ab+.*'", new List[] {Arrays.asList("ab", 3)}); //$NON-NLS-1$
+		execute("select * from x where e1 like_regex '^ab|b'", new List[] {Arrays.asList("ab", 3), Arrays.asList("b", 2)}); //$NON-NLS-1$
+	}
+	
 	@Test public void testIsNullWithIndex() throws Exception {
 		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
 		execute("insert into x (e2, e1) values (3, null)", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
@@ -312,7 +321,10 @@
 	@Test public void testUnneededMergePredicate() throws Exception {
 		execute("create local temporary table x (e1 string, e2 integer, primary key (e1))", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
 		execute("create local temporary table x1 (e1 string, e2 integer)", new List[] {Arrays.asList(0)}); //$NON-NLS-1$
-		TestOptimizer.helpPlan("select x.e1 from x, x1 where x.e2 = x1.e2 and x.e1 = x1.e1", this.metadata, new String[] {"SELECT x.e2, x.e1 FROM x ORDER BY x.e1", "SELECT x1.e2, x1.e1 FROM x1 ORDER BY x1.e1"}, ComparisonMode.EXACT_COMMAND_STRING);
+		TestOptimizer.helpPlan("select x.e1 from x makenotdep, x1 makenotdep where x.e2 = x1.e2 and x.e1 = x1.e1", this.metadata, new String[] {"SELECT x.e2, x.e1 FROM x ORDER BY x.e1", "SELECT x1.e2, x1.e1 FROM x1 ORDER BY x1.e1"}, ComparisonMode.EXACT_COMMAND_STRING);
+		execute("insert into x (e2, e1) values (2, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("insert into x1 (e2, e1) values (3, 'b')", new List[] {Arrays.asList(1)}); //$NON-NLS-1$
+		execute("select x.e1 from x makenotdep, x1 makenotdep where x.e2 = x1.e2 and x.e1 = x1.e1", new List[0]); //$NON-NLS-1$
 	}
 	
 	private void sampleTable() throws Exception {


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestTempTables.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestTempTables.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestTempTables.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestTextTable.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestTextTable.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestTextTable.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -37,13 +37,13 @@
 import org.teiid.core.types.ClobType;
 import org.teiid.core.types.InputStreamFactory;
 import org.teiid.core.util.UnitTestUtil;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings({"unchecked", "nls"})
 public class TestTextTable {
@@ -72,7 +72,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
     }
 	
 	@Test public void testTextTableFixedWin() throws Exception {
@@ -85,7 +85,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos_win.txt")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos_win.txt")));
     }
 	
 	@Test public void testTextTableFixedPartial() throws Exception {
@@ -98,7 +98,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/cdm_dos.txt")));
     }
 	
 	@Test public void testNamedMultilineHeader() throws Exception {
@@ -114,7 +114,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/test-file.txt.csv")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/test-file.txt.csv")));
     }
 	
 	@Test public void testHeaderWithSkip() throws Exception {
@@ -127,7 +127,7 @@
         FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
         
-        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/TextParts_HeaderRow2.csv")));
+        processPreparedStatement(sql, expected, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(clobFromFile("text/TextParts_HeaderRow2.csv")));
     }
 	
 	@Test public void testEscape() throws Exception {
@@ -159,6 +159,29 @@
         process(sql, expected);
     }
 	
+	@Test public void testNoRowDelimiter() throws Exception {
+    	String sql = "select * from texttable('abcdef' COLUMNS c1 string width 1, c2 string width 1 no row delimiter) x"; //$NON-NLS-1$
+    	
+        List[] expected = new List[] {
+        		Arrays.asList("a","b"),
+        		Arrays.asList("c","d"),
+        		Arrays.asList("e","f"),
+        };    
+    
+        process(sql, expected);
+    }
+	
+	@Test public void testNoTrim() throws Exception {
+    	String sql = "select * from texttable('a b \nc  d' COLUMNS c1 string width 2, c2 string width 2 no trim) x"; //$NON-NLS-1$
+    	
+        List[] expected = new List[] {
+        		Arrays.asList("a","b "),
+        		Arrays.asList("c"," d"),
+        };    
+    
+        process(sql, expected);
+    }
+	
 	@Test public void testNoRows() throws Exception {
     	String sql = "select * from texttable('' COLUMNS c1 string, c2 string SKIP 3) x"; //$NON-NLS-1$
     	
@@ -248,7 +271,7 @@
 	public static void process(String sql, List[] expectedResults) throws Exception {    
     	FakeDataManager dataManager = new FakeDataManager();
         sampleData1(dataManager);
-    	ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+    	ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
         helpProcess(plan, createCommandContext(), dataManager, expectedResults);
     }
 	
@@ -258,7 +281,7 @@
 	
     @Test public void testTextAgg() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
@@ -285,7 +308,7 @@
     
     @Test public void testTextAggOrderByUnrelated() throws Exception {
         FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         BasicSourceCapabilities caps = getTypicalCapabilities();
         caps.setCapabilitySupport(Capability.QUERY_SUBQUERIES_SCALAR, false);
@@ -317,7 +340,7 @@
         sampleData1(dataManager);
         
         char[] data = new char[5000];
-        processPreparedStatement(sql, null, dataManager, new DefaultCapabilitiesFinder(), FakeMetadataFactory.example1Cached(), Arrays.asList(new ClobType(new SerialClob(data))));
+        processPreparedStatement(sql, null, dataManager, new DefaultCapabilitiesFinder(), RealMetadataFactory.example1Cached(), Arrays.asList(new ClobType(new SerialClob(data))));
     }
 	
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestTextTable.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestTextTable.java:3149-3171
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestTextTable.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestTextTable.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,7 +28,6 @@
 import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
 
@@ -40,21 +39,24 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.unittest.TimestampUtil;
 import org.teiid.query.util.CommandContext;
 import org.teiid.query.validator.TestValidator;
 
-
+ at SuppressWarnings("nls")
 public class TestVirtualDepJoin {
     
     /** 
@@ -65,37 +67,34 @@
      * @param object2
      * @since 4.3
      */
-    private static void setStats(List elementObjects,
+    private static void setStats(List<Column> elementObjects,
                                  int[] ndvs,
                                  int[] nnvs,
                                  String[] mins,
                                  String[] maxs) {
-        
-        Iterator iter = elementObjects.iterator();
-        for(int i=0; iter.hasNext(); i++) {
-            FakeMetadataObject obj = (FakeMetadataObject) iter.next();
+        for (int i = 0; i < elementObjects.size(); i++) {
+        	Column obj = elementObjects.get(i);
             if(ndvs != null) {
-                obj.putProperty(FakeMetadataObject.Props.DISTINCT_VALUES, new Integer(ndvs[i]));
+                obj.setDistinctValues(ndvs[i]);
             }
             if(nnvs != null) {
-                obj.putProperty(FakeMetadataObject.Props.NULL_VALUES, new Integer(nnvs[i]));
+                obj.setNullValues(nnvs[i]);
             }
             if(mins != null) {
-                obj.putProperty(FakeMetadataObject.Props.MIN_VALUE, mins[i]);
+                obj.setMinimumValue(mins[i]);
             }
             if(maxs != null) {
-                obj.putProperty(FakeMetadataObject.Props.MAX_VALUE, maxs[i]);
+                obj.setMaximumValue(maxs[i]);
             }
-            
         }
     }
     
-    public static FakeMetadataFacade exampleVirtualDepJoin() {
-        FakeMetadataObject us = FakeMetadataFactory.createPhysicalModel("US"); //$NON-NLS-1$
-        us.putProperty(FakeMetadataObject.Props.MAX_SET_SIZE, new Integer(0));
-        FakeMetadataObject usAccts = FakeMetadataFactory.createPhysicalGroup("US.Accounts", us); //$NON-NLS-1$
-        usAccts.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000000));
-        List usAcctsElem = FakeMetadataFactory.createElements(usAccts, 
+    public static TransformationMetadata exampleVirtualDepJoin() {
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema us = RealMetadataFactory.createPhysicalModel("US", metadataStore); //$NON-NLS-1$
+        Table usAccts = RealMetadataFactory.createPhysicalGroup("Accounts", us); //$NON-NLS-1$
+        usAccts.setCardinality(1000000);
+        List<Column> usAcctsElem = RealMetadataFactory.createElements(usAccts, 
                                     new String[] { "customer", "account", "txn", "txnid", "pennies" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
                                     new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
         setStats(usAcctsElem,
@@ -105,11 +104,10 @@
                  new String[] {"1000", null, null, null, "-5"}  // max per column - use defaults //$NON-NLS-1$ //$NON-NLS-2$
         );
 
-        FakeMetadataObject europe = FakeMetadataFactory.createPhysicalModel("Europe"); //$NON-NLS-1$
-        europe.putProperty(FakeMetadataObject.Props.MAX_SET_SIZE, new Integer(0));
-        FakeMetadataObject euAccts = FakeMetadataFactory.createPhysicalGroup("Europe.CustAccts", europe); //$NON-NLS-1$
-        euAccts.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000000));
-        List euAcctsElem = FakeMetadataFactory.createElements(euAccts, 
+        Schema europe = RealMetadataFactory.createPhysicalModel("Europe", metadataStore); //$NON-NLS-1$
+        Table euAccts = RealMetadataFactory.createPhysicalGroup("CustAccts", europe); //$NON-NLS-1$
+        euAccts.setCardinality(1000000);
+        List<Column> euAcctsElem = RealMetadataFactory.createElements(euAccts, 
                                     new String[] { "id", "accid", "type", "amount" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                                     new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.SHORT, DataTypeManager.DefaultDataTypes.BIG_DECIMAL });
         setStats(euAcctsElem,
@@ -119,11 +117,10 @@
                  null  // max per column - use defaults
         );
 
-        FakeMetadataObject cust = FakeMetadataFactory.createPhysicalModel("CustomerMaster"); //$NON-NLS-1$
-        cust.putProperty(FakeMetadataObject.Props.MAX_SET_SIZE, new Integer(0));
-        FakeMetadataObject customers = FakeMetadataFactory.createPhysicalGroup("CustomerMaster.Customers", cust); //$NON-NLS-1$
-        customers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000));
-        List customersElem = FakeMetadataFactory.createElements(customers, 
+        Schema cust = RealMetadataFactory.createPhysicalModel("CustomerMaster", metadataStore); //$NON-NLS-1$
+        Table customers = RealMetadataFactory.createPhysicalGroup("Customers", cust); //$NON-NLS-1$
+        customers.setCardinality(1000);
+        List<Column> customersElem = RealMetadataFactory.createElements(customers, 
                                     new String[] { "id", "first", "last", "birthday" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                                     new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE });
         setStats(customersElem,
@@ -132,9 +129,9 @@
                  null, // min per column - use defaults
                  null  // max per column - use defaults
         );
-        FakeMetadataObject locations = FakeMetadataFactory.createPhysicalGroup("CustomerMaster.Locations", cust); //$NON-NLS-1$
-        locations.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1200));
-        List locationsElem = FakeMetadataFactory.createElements(locations, 
+        Table locations = RealMetadataFactory.createPhysicalGroup("Locations", cust); //$NON-NLS-1$
+        locations.setCardinality(1200);
+        List<Column> locationsElem = RealMetadataFactory.createElements(locations, 
                                     new String[] { "id", "location" }, //$NON-NLS-1$ //$NON-NLS-2$ 
                                     new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.STRING });
         setStats(locationsElem,
@@ -144,46 +141,23 @@
                  null  // max per column - use defaults
         );
 
-        FakeMetadataObject vAccts = FakeMetadataFactory.createVirtualModel("Accounts"); //$NON-NLS-1$
+        Schema vAccts = RealMetadataFactory.createVirtualModel("Accounts", metadataStore); //$NON-NLS-1$
         QueryNode accountsPlan = new QueryNode("SELECT customer as customer_id, convert(account, long) as account_id, convert(txnid, long) as transaction_id, case txn when 'DEP' then 1 when 'TFR' then 2 when 'WD' then 3 else -1 end as txn_type, (pennies + convert('0.00', bigdecimal)) / 100 as amount, 'US' as source FROM US.Accounts where txn != 'X'" +  //$NON-NLS-1$
 		   "UNION ALL " +  //$NON-NLS-1$
 		   "SELECT id, convert(accid / 10000, long), mod(accid, 10000), convert(type, integer), amount, 'EU' from Europe.CustAccts"); //$NON-NLS-1$ 
-        FakeMetadataObject accounts = FakeMetadataFactory.createVirtualGroup("Accounts.Accounts", vAccts, accountsPlan); //$NON-NLS-1$
-        List accountsElem = FakeMetadataFactory.createElements(accounts, 
+        Table accounts = RealMetadataFactory.createVirtualGroup("Accounts", vAccts, accountsPlan); //$NON-NLS-1$
+        RealMetadataFactory.createElements(accounts, 
                                             new String[] { "customer_id", "account_id", "transaction_id", "txn_type", "amount", "source" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
                                             new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, DataTypeManager.DefaultDataTypes.STRING });
         
-        FakeMetadataObject master = FakeMetadataFactory.createVirtualModel("Master"); //$NON-NLS-1$
+        Schema master = RealMetadataFactory.createVirtualModel("Master", metadataStore); //$NON-NLS-1$
         QueryNode masterPlan = new QueryNode("select id as CustomerID, First, Last, a.account_id as AccountID, transaction_id as TransactionID, txn_type AS TxnCode, Amount from CustomerMaster.Customers c, Accounts.Accounts a where c.id=a.customer_id"); //$NON-NLS-1$ 
-        FakeMetadataObject transactions = FakeMetadataFactory.createVirtualGroup("Master.Transactions", master, masterPlan); //$NON-NLS-1$
-        List transactionsElem = FakeMetadataFactory.createElements(transactions, 
+        Table transactions = RealMetadataFactory.createVirtualGroup("Transactions", master, masterPlan); //$NON-NLS-1$
+        RealMetadataFactory.createElements(transactions, 
                                             new String[] { "CustomerID", "First", "Last", "AccountID", "TransactionID", "TxnCode", "Amount" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
                                             new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL });
         
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(us);
-        store.addObject(usAccts);
-        store.addObjects(usAcctsElem);
-
-        store.addObject(europe);
-        store.addObject(euAccts);
-        store.addObjects(euAcctsElem);
-
-        store.addObject(cust);
-        store.addObject(customers);
-        store.addObjects(customersElem);
-        store.addObject(locations);
-        store.addObjects(locationsElem);
-        
-        store.addObject(vAccts);
-        store.addObject(accounts);
-        store.addObjects(accountsElem);
-
-        store.addObject(master);
-        store.addObject(transactions);
-        store.addObjects(transactionsElem);
-
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "virtualDepJoin");
     }
 
     @Test public void testVirtualDepJoinNoValues() throws Exception {  
@@ -195,7 +169,7 @@
                 };     
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = exampleVirtualDepJoin();        
+        QueryMetadataInterface metadata = exampleVirtualDepJoin();        
         FakeDataManager dataManager = new FakeDataManager(); 
         sampleDataVirtualDepJoin(dataManager, metadata); 
          
@@ -208,7 +182,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);    
         finder.addCapabilities("Europe", caps);//$NON-NLS-1$
         finder.addCapabilities("CustomerMaster", caps);//$NON-NLS-1$
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, exampleVirtualDepJoin(), finder, context); 
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, metadata, finder, context); 
  
         TestOptimizer.checkDependentJoinCount(plan, 1);
         // Run query 
@@ -235,7 +209,7 @@
                 };     
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = exampleVirtualDepJoin();        
+        QueryMetadataInterface metadata = exampleVirtualDepJoin();        
         FakeDataManager dataManager = new FakeDataManager(); 
         sampleDataVirtualDepJoin(dataManager, metadata); 
          
@@ -251,7 +225,7 @@
         finder.addCapabilities("US", caps); //$NON-NLS-1$
         finder.addCapabilities("Europe", caps);//$NON-NLS-1$
         finder.addCapabilities("CustomerMaster", caps);//$NON-NLS-1$
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, exampleVirtualDepJoin(), finder, context); 
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, metadata, finder, context); 
          
         // Check plan contents
         int selectCount = !setPushdown ? 3 : 0;
@@ -302,7 +276,7 @@
                 };     
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = exampleVirtualDepJoin();        
+        QueryMetadataInterface metadata = exampleVirtualDepJoin();        
         FakeDataManager dataManager = new FakeDataManager(); 
         sampleDataVirtualDepJoin(dataManager, metadata); 
          
@@ -317,7 +291,7 @@
         finder.addCapabilities("US", caps1); //$NON-NLS-1$
         finder.addCapabilities("Europe", caps2);//$NON-NLS-1$
         finder.addCapabilities("CustomerMaster", caps1);//$NON-NLS-1$
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, exampleVirtualDepJoin(), finder, context); 
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, metadata, finder, context); 
  
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -351,7 +325,7 @@
                 };     
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = exampleVirtualDepJoin();        
+        QueryMetadataInterface metadata = exampleVirtualDepJoin();        
         FakeDataManager dataManager = new FakeDataManager(); 
         sampleDataVirtualDepJoin(dataManager, metadata); 
          
@@ -364,7 +338,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);    
         finder.addCapabilities("Europe", caps);//$NON-NLS-1$
         finder.addCapabilities("CustomerMaster", caps);//$NON-NLS-1$
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, exampleVirtualDepJoin(), finder, context); 
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, metadata, finder, context); 
  
         TestOptimizer.checkNodeTypes(plan, new int[] {
             1,      // Access
@@ -390,7 +364,7 @@
         List<String> expectedQueries = new ArrayList<String>(6);
         for (int i = 0; i < 3; i++) {
         	expectedQueries.add("SELECT g_0.id AS c_0, g_0.first AS c_1, g_0.last AS c_2 FROM CustomerMaster.Customers AS g_0 WHERE g_0.first = 'Miles' ORDER BY c_0"); //$NON-NLS-1$
-        	expectedQueries.add("SELECT g_0.id AS c_0, g_0.amount AS c_1 FROM Europe.CustAccts AS g_0 WHERE g_0.id = 100 ORDER BY c_0"); //$NON-NLS-1$
+        	expectedQueries.add("SELECT g_0.id, g_0.amount FROM Europe.CustAccts AS g_0 WHERE g_0.id = 100"); //$NON-NLS-1$
         }
         
         assertEquals(expectedQueries, dataManager.getQueries());
@@ -419,7 +393,7 @@
         // Create query  
         String sql = "SELECT * from Master.Transactions where last = 'Davis' order by CustomerID, TransactionID"; //$NON-NLS-1$ 
          
-        List expected = new LinkedList();
+        List<List<Object>> expected = new LinkedList<List<Object>>();
         
         
         // Create expected results 
@@ -460,7 +434,7 @@
         expected.add(Arrays.asList(new Object[] { new Long(300), "CloneB", "Davis", new Long(630), new Long(1008), new Integer(2), new BigDecimal("62.00") })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = exampleVirtualDepJoin();        
+        QueryMetadataInterface metadata = exampleVirtualDepJoin();        
         FakeDataManager dataManager = new FakeDataManager();
         sampleDataVirtualDepJoin(dataManager, metadata); 
         overrideVirtualDepJoinData(dataManager, metadata, unique);
@@ -475,7 +449,7 @@
         finder.addCapabilities("US", caps); //$NON-NLS-1$
         finder.addCapabilities("Europe", caps);//$NON-NLS-1$
         finder.addCapabilities("CustomerMaster", caps);//$NON-NLS-1$
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, exampleVirtualDepJoin(), finder, context); 
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, metadata, finder, context); 
  
         // Run query 
         BufferManager bufferMgr = createCustomBufferMgr(2);
@@ -515,7 +489,7 @@
                 };     
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = exampleVirtualDepJoin();        
+        QueryMetadataInterface metadata = exampleVirtualDepJoin();        
         FakeDataManager dataManager = new FakeDataManager(); 
         sampleDataVirtualDepJoin(dataManager, metadata); 
          
@@ -527,102 +501,71 @@
         finder.addCapabilities("US", caps); //$NON-NLS-1$
         finder.addCapabilities("Europe", caps);//$NON-NLS-1$
         finder.addCapabilities("CustomerMaster", caps);//$NON-NLS-1$
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, exampleVirtualDepJoin(), finder); 
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, metadata, finder); 
  
         // Run query 
         CommandContext context = TestProcessor.createCommandContext();
         TestProcessor.helpProcess(plan, context, dataManager, expected); 
     }
     
-    private void sampleDataVirtualDepJoin(FakeDataManager dataMgr, FakeMetadataFacade metadata) throws Exception {
+    private void sampleDataVirtualDepJoin(FakeDataManager dataMgr, QueryMetadataInterface metadata) throws Exception {
         dataMgr.setBlockOnce();
-        // Group US.Accounts
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("US.Accounts"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = FakeDataStore.createElements(elementIDs);
     
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList(new Object[] { new Long(100), new Integer(15000), "DEP", new Integer(123), new Integer(10000) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(100), new Integer(15000), "TFR", new Integer(127), new Integer(25000) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(100), new Integer(15000), "WD", new Integer(128), new Integer(100000) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(100), new Integer(15001), "DEP", new Integer(134), new Integer(1000) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(100), new Integer(15001), "DEP", new Integer(201), new Integer(1000) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(200), new Integer(16000), "WD", new Integer(207), new Integer(1234) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(200), new Integer(16000), "WD", new Integer(299), new Integer(95034) }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(200), new Integer(16000), "X", new Integer(301), new Integer(5000) }), //$NON-NLS-1$
-                } );    
+            metadata,
+            "US.Accounts", new List[] { 
+				    Arrays.asList(new Object[] { new Long(100), new Integer(15000), "DEP", new Integer(123), new Integer(10000) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(100), new Integer(15000), "TFR", new Integer(127), new Integer(25000) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(100), new Integer(15000), "WD", new Integer(128), new Integer(100000) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(100), new Integer(15001), "DEP", new Integer(134), new Integer(1000) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(100), new Integer(15001), "DEP", new Integer(201), new Integer(1000) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(200), new Integer(16000), "WD", new Integer(207), new Integer(1234) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(200), new Integer(16000), "WD", new Integer(299), new Integer(95034) }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(200), new Integer(16000), "X", new Integer(301), new Integer(5000) }), //$NON-NLS-1$
+				    } );    
 
-        // Group Europe.CustAccts
-        groupID = (FakeMetadataObject) metadata.getGroupID("Europe.CustAccts"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = FakeDataStore.createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList(new Object[] { new Long(100), new Long(5401002), new Short((short)1), new BigDecimal("7.20") }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(100), new Long(5401003), new Short((short)2), new BigDecimal("1000.00") }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(200), new Long(5501004), new Short((short)3), new BigDecimal("542.20") }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(200), new Long(5501005), new Short((short)1), new BigDecimal("99.99") }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(300), new Long(6201006), new Short((short)1), new BigDecimal("10000.00") }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(300), new Long(6201007), new Short((short)2), new BigDecimal("0.75") }), //$NON-NLS-1$
-                Arrays.asList(new Object[] { new Long(300), new Long(6301008), new Short((short)2), new BigDecimal("62.00") }), //$NON-NLS-1$
-                } );    
+            metadata,
+            "Europe.CustAccts", new List[] { 
+				    Arrays.asList(new Object[] { new Long(100), new Long(5401002), new Short((short)1), new BigDecimal("7.20") }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(100), new Long(5401003), new Short((short)2), new BigDecimal("1000.00") }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(200), new Long(5501004), new Short((short)3), new BigDecimal("542.20") }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(200), new Long(5501005), new Short((short)1), new BigDecimal("99.99") }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(300), new Long(6201006), new Short((short)1), new BigDecimal("10000.00") }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(300), new Long(6201007), new Short((short)2), new BigDecimal("0.75") }), //$NON-NLS-1$
+				    Arrays.asList(new Object[] { new Long(300), new Long(6301008), new Short((short)2), new BigDecimal("62.00") }), //$NON-NLS-1$
+				    } );    
 
-        // Group CustomerMaster.Customers
-        groupID = (FakeMetadataObject) metadata.getGroupID("CustomerMaster.Customers"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = FakeDataStore.createElements(elementIDs);
-    
-        dataMgr.registerTuples(groupID, elementSymbols,                               
-                               new List[] { 
-                                   Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", TimestampUtil.createDate(1926, 4, 25) }), //$NON-NLS-1$ //$NON-NLS-2$
-                                   Arrays.asList(new Object[] { new Long(200), "John", "Coltrane", TimestampUtil.createDate(1926, 8, 23) }), //$NON-NLS-1$ //$NON-NLS-2$
-                                   Arrays.asList(new Object[] { new Long(300), "Thelonious", "Monk", TimestampUtil.createDate(1917, 9, 10) }), //$NON-NLS-1$ //$NON-NLS-2$
-                                   } );    
+        dataMgr.registerTuples(metadata, "CustomerMaster.Customers", new List[] { 
+			       Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", TimestampUtil.createDate(1926, 4, 25) }), //$NON-NLS-1$ //$NON-NLS-2$
+			       Arrays.asList(new Object[] { new Long(200), "John", "Coltrane", TimestampUtil.createDate(1926, 8, 23) }), //$NON-NLS-1$ //$NON-NLS-2$
+			       Arrays.asList(new Object[] { new Long(300), "Thelonious", "Monk", TimestampUtil.createDate(1917, 9, 10) }), //$NON-NLS-1$ //$NON-NLS-2$
+			       } );    
 
-        // Group CustomerMaster.Locations
-        groupID = (FakeMetadataObject) metadata.getGroupID("CustomerMaster.Locations"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = FakeDataStore.createElements(elementIDs);
-    
-        dataMgr.registerTuples(groupID, elementSymbols,                               
-                               new List[] { 
-                                   Arrays.asList(new Object[] { new Long(100), "US" }), //$NON-NLS-1$ 
-                                   Arrays.asList(new Object[] { new Long(100), "EU" }), //$NON-NLS-1$ 
-                                   Arrays.asList(new Object[] { new Long(200), "US" }), //$NON-NLS-1$ 
-                                   Arrays.asList(new Object[] { new Long(200), "EU" }), //$NON-NLS-1$ 
-                                   Arrays.asList(new Object[] { new Long(300), "EU" }), //$NON-NLS-1$ 
-                                   } );        
+        dataMgr.registerTuples(metadata, "CustomerMaster.Locations", new List[] { 
+			       Arrays.asList(new Object[] { new Long(100), "US" }), //$NON-NLS-1$ 
+			       Arrays.asList(new Object[] { new Long(100), "EU" }), //$NON-NLS-1$ 
+			       Arrays.asList(new Object[] { new Long(200), "US" }), //$NON-NLS-1$ 
+			       Arrays.asList(new Object[] { new Long(200), "EU" }), //$NON-NLS-1$ 
+			       Arrays.asList(new Object[] { new Long(300), "EU" }), //$NON-NLS-1$ 
+			       } );        
     }                    
 
-    private void overrideVirtualDepJoinData(FakeDataManager dataMgr, FakeMetadataFacade metadata, boolean unique) throws Exception {
+    private void overrideVirtualDepJoinData(FakeDataManager dataMgr, QueryMetadataInterface metadata, boolean unique) throws Exception {
         // Group CustomerMaster.Customers
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("CustomerMaster.Customers"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = FakeDataStore.createElements(elementIDs);
+        List<List<?>> data = new LinkedList<List<?>>();
         
-        TimestampUtil ts = new TimestampUtil();
-        
-        List data = new LinkedList();
-        
-        data.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", ts.createDate(1926, 4, 25) })); //$NON-NLS-1$ //$NON-NLS-2$
+        data.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", TimestampUtil.createDate(1926, 4, 25) })); //$NON-NLS-1$ //$NON-NLS-2$
         if (!unique) {
-            data.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", ts.createDate(1926, 4, 25) })); //$NON-NLS-1$ //$NON-NLS-2$
+            data.add(Arrays.asList(new Object[] { new Long(100), "Miles", "Davis", TimestampUtil.createDate(1926, 4, 25) })); //$NON-NLS-1$ //$NON-NLS-2$
         }
-        data.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", ts.createDate(1926, 4, 26) })); //$NON-NLS-1$ //$NON-NLS-2$
-        data.add(Arrays.asList(new Object[] { new Long(300), "CloneB", "Davis", ts.createDate(1926, 4, 27) })); //$NON-NLS-1$ //$NON-NLS-2$
-        data.add(Arrays.asList(new Object[] { new Long(400), "CloneC", "Davis", ts.createDate(1926, 4, 28) })); //$NON-NLS-1$ //$NON-NLS-2$
+        data.add(Arrays.asList(new Object[] { new Long(200), "CloneA", "Davis", TimestampUtil.createDate(1926, 4, 26) })); //$NON-NLS-1$ //$NON-NLS-2$
+        data.add(Arrays.asList(new Object[] { new Long(300), "CloneB", "Davis", TimestampUtil.createDate(1926, 4, 27) })); //$NON-NLS-1$ //$NON-NLS-2$
+        data.add(Arrays.asList(new Object[] { new Long(400), "CloneC", "Davis", TimestampUtil.createDate(1926, 4, 28) })); //$NON-NLS-1$ //$NON-NLS-2$
         
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols, (List[])data.toArray(new List[data.size()]));
+            metadata,
+            "CustomerMaster.Customers", (List[])data.toArray(new List[data.size()]));
     }
     
     @Test public void testVirtualAccessVirtualDep() throws Exception {
@@ -686,7 +629,7 @@
                 };     
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = exampleVirtualDepJoin();        
+        QueryMetadataInterface metadata = exampleVirtualDepJoin();        
         FakeDataManager dataManager = new FakeDataManager(); 
         sampleDataVirtualDepJoin(dataManager, metadata); 
          
@@ -699,7 +642,7 @@
         caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, false);    
         finder.addCapabilities("Europe", caps);//$NON-NLS-1$
         finder.addCapabilities("CustomerMaster", caps);//$NON-NLS-1$
-        ProcessorPlan plan = TestProcessor.helpGetPlan(command, exampleVirtualDepJoin(), finder, context); 
+        ProcessorPlan plan = TestProcessor.helpGetPlan(command, metadata, finder, context); 
  
         TestOptimizer.checkNodeTypes(plan, new int[] {
             2,      // Access
@@ -735,7 +678,7 @@
                 };     
 
         // Construct data manager with data 
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();        
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();        
         FakeDataManager dataManager = new FakeDataManager(); 
         TestProcessor.sampleData1(dataManager); 
          


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java:3149-3171
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestVirtualDepJoin.java:3188-3382

Copied: branches/as7/engine/src/test/java/org/teiid/query/processor/TestWindowFunctions.java (from rev 3382, trunk/engine/src/test/java/org/teiid/query/processor/TestWindowFunctions.java)
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestWindowFunctions.java	                        (rev 0)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestWindowFunctions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,239 @@
+/*
+ * 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 org.teiid.query.processor;
+
+import static org.teiid.query.optimizer.TestOptimizer.*;
+import static org.teiid.query.processor.TestProcessor.*;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+import org.teiid.query.optimizer.TestOptimizer;
+import org.teiid.query.optimizer.TestOptimizer.ComparisonMode;
+import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
+import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder;
+import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
+import org.teiid.query.unittest.RealMetadataFactory;
+
+ at SuppressWarnings({"nls", "unchecked"})
+public class TestWindowFunctions {
+
+    @Test public void testViewNotRemoved() throws Exception {
+    	BasicSourceCapabilities caps = getTypicalCapabilities();
+    	caps.setCapabilitySupport(Capability.ELEMENTARY_OLAP, true);
+    	caps.setCapabilitySupport(Capability.QUERY_FROM_INLINE_VIEWS, true);
+        ProcessorPlan plan = TestOptimizer.helpPlan("SELECT y FROM (select row_number() over (order by e1) as y from pm1.g1) as x where x.y = 10", //$NON-NLS-1$
+                                      RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
+                                      new String[] {
+                                          "SELECT v_0.c_0 FROM (SELECT ROW_NUMBER() OVER (ORDER BY g_0.e1) AS c_0 FROM pm1.g1 AS g_0) AS v_0 WHERE v_0.c_0 = 10"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+    
+        checkNodeTypes(plan, FULL_PUSHDOWN);                                    
+    }
+    
+    @Test public void testWindowFunctionPushdown() throws Exception {
+    	BasicSourceCapabilities caps = getTypicalCapabilities();
+    	caps.setCapabilitySupport(Capability.ELEMENTARY_OLAP, true);
+    	caps.setCapabilitySupport(Capability.WINDOW_FUNCTION_ORDER_BY_AGGREGATES, true);
+    	caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e1) over (order by e1) as y from pm1.g1", //$NON-NLS-1$
+                                      RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
+                                      new String[] {
+                                          "SELECT MAX(g_0.e1) OVER (ORDER BY g_0.e1) FROM pm1.g1 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+    
+        checkNodeTypes(plan, FULL_PUSHDOWN);                                    
+    }
+
+    @Test public void testWindowFunctionPushdown1() throws Exception {
+    	BasicSourceCapabilities caps = getTypicalCapabilities();
+    	caps.setCapabilitySupport(Capability.ELEMENTARY_OLAP, true);
+    	caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true);
+        ProcessorPlan plan = TestOptimizer.helpPlan("select max(e1) over (order by e1) as y from pm1.g1", //$NON-NLS-1$
+                                      RealMetadataFactory.example1Cached(), null, new DefaultCapabilitiesFinder(caps),
+                                      new String[] {
+                                          "SELECT g_0.e1 FROM pm1.g1 AS g_0"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+    
+        checkNodeTypes(plan, new int[] {
+                1,      // Access
+                0,      // DependentAccess
+                0,      // DependentSelect
+                0,      // DependentProject
+                0,      // DupRemove
+                0,      // Grouping
+                0,      // NestedLoopJoinStrategy
+                0,      // MergeJoinStrategy
+                0,      // Null
+                0,      // PlanExecution
+                1,      // Project
+                0,      // Select
+                0,      // Sort
+                0       // UnionAll
+            });                                     
+    }
+    
+	@Test public void testRanking() throws Exception {
+    	String sql = "select e1, row_number() over (order by e1), rank() over (order by e1), dense_rank() over (order by e1 nulls last) from pm1.g1";
+        
+    	List<?>[] expected = new List[] {
+        		Arrays.asList("a", 2, 2, 1),
+        		Arrays.asList(null, 1, 1, 4),
+        		Arrays.asList("a", 3, 2, 1),
+        		Arrays.asList("c", 6, 6, 3),
+        		Arrays.asList("b", 5, 5, 2),
+        		Arrays.asList("a", 4, 2, 1),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
+    @Test public void testPartitionedMax() throws Exception {
+    	String sql = "select e2, max(e1) over (partition by e2) as y from pm1.g1";
+        
+    	List<?>[] expected = new List[] {
+        		Arrays.asList(0, "a"),
+        		Arrays.asList(1, "c"),
+        		Arrays.asList(3, "a"),
+        		Arrays.asList(1, "c"),
+        		Arrays.asList(2, "b"),
+        		Arrays.asList(0, "a"),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
+    @Test public void testUnrelatedWindowFunctionOrderBy() throws Exception {
+    	String sql = "select e2, e1 from pm1.g1 order by count(e1) over (partition by e3), e2";
+        
+    	List<?>[] expected = new List[] {
+    			Arrays.asList(1, "c"),
+        		Arrays.asList(3, "a"),
+        		Arrays.asList(0, "a"),
+        		Arrays.asList(0, "a"),
+        		Arrays.asList(1, null),
+        		Arrays.asList(2, "b"),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
+    @Test public void testWindowFunctionOrderBy() throws Exception {
+    	String sql = "select e2, e1, count(e1) over (partition by e3) as c from pm1.g1 order by c, e2";
+        
+    	List<?>[] expected = new List[] {
+        		Arrays.asList(1, "c", 2),
+        		Arrays.asList(3, "a", 2),
+        		Arrays.asList(0, "a", 3),
+        		Arrays.asList(0, "a", 3),
+        		Arrays.asList(1, null, 3),
+        		Arrays.asList(2, "b", 3),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+
+    /**
+     * Note that we've optimized the ordering to be performed prior to the windowing.
+     * If we change the windowing logic to not preserve the incoming row ordering, then this optimization will need to change
+     * @throws Exception
+     */
+    @Test public void testCountDuplicates() throws Exception {
+    	String sql = "select e1, count(e1) over (order by e1) as c from pm1.g1 order by e1";
+        
+    	List<?>[] expected = new List[] {
+        		Arrays.asList("a", 2),
+        		Arrays.asList("a", 2),
+        		Arrays.asList("b", 3),
+        };
+    	
+    	HardcodedDataManager dataManager = new HardcodedDataManager();
+    	dataManager.addData("SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", new List[] {Arrays.asList("a"), Arrays.asList("a"), Arrays.asList("b")});
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
+    @Test public void testEmptyOver() throws Exception {
+    	String sql = "select e1, max(e1) over () as c from pm1.g1";
+        
+    	List<?>[] expected = new List[] {
+        		Arrays.asList("a", "c"),
+        		Arrays.asList(null, "c"),
+        		Arrays.asList("a", "c"),
+        		Arrays.asList("c", "c"),
+        		Arrays.asList("b", "c"),
+        		Arrays.asList("a", "c"),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
+    @Test public void testRowNumberMedian() throws Exception {
+    	String sql = "select e1, r, c from (select e1, row_number() over (order by e1) as r, count(*) over () c from pm1.g1) x where r = ceiling(c/2)";
+        
+    	List<?>[] expected = new List[] {
+        		Arrays.asList("a", 3, 6),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
+    @Test public void testPartitionedRowNumber() throws Exception {
+    	String sql = "select e1, e3, row_number() over (partition by e3 order by e1) as r from pm1.g1 order by r limit 2";
+        
+    	List<?>[] expected = new List[] {
+        		Arrays.asList(null, Boolean.FALSE, 1),
+        		Arrays.asList("a", Boolean.TRUE, 1),
+        };
+    	
+    	FakeDataManager dataManager = new FakeDataManager();
+    	sampleData1(dataManager);
+        ProcessorPlan plan = helpGetPlan(sql, RealMetadataFactory.example1Cached(), TestOptimizer.getGenericFinder());
+        
+        helpProcess(plan, dataManager, expected);
+    }
+    
+}

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -12,7 +12,7 @@
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings({"nls", "unchecked"})
 public class TestWithClauseProcessing {
@@ -30,7 +30,7 @@
 	    FakeDataManager dataManager = new FakeDataManager();
 	    sampleData1(dataManager);
 	    
-	    ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+	    ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
 	    
 	    helpProcess(plan, dataManager, expected);
 	}
@@ -50,7 +50,7 @@
 	    FakeDataManager dataManager = new FakeDataManager();
 	    sampleData1(dataManager);
 	    
-	    ProcessorPlan plan = helpGetPlan(helpParse(sql), FakeMetadataFactory.example1Cached());
+	    ProcessorPlan plan = helpGetPlan(helpParse(sql), RealMetadataFactory.example1Cached());
 	    
 	    helpProcess(plan, dataManager, expected);
 	}
@@ -67,7 +67,22 @@
 	    FakeDataManager dataManager = new FakeDataManager();
 	    sampleData1(dataManager);
 	    
-	    TestOptimizer.helpPlan(sql, FakeMetadataFactory.example1Cached(), null, capFinder, new String[] {"WITH a (x, y, z) AS (SELECT g_0.e1, g_0.e2, g_0.e3 FROM pm1.g1 AS g_0) SELECT g_0.x FROM a AS g_0, a AS g_1"}, ComparisonMode.EXACT_COMMAND_STRING);
+	    TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, new String[] {"WITH a (x, y, z) AS (SELECT g_0.e1, g_0.e2, g_0.e3 FROM pm1.g1 AS g_0) SELECT g_0.x FROM a AS g_0, a AS g_1"}, ComparisonMode.EXACT_COMMAND_STRING);
 	}
+	
+	@Test public void testWithPushdownWithConstants() throws TeiidException {
+		 FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder();
+        BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities();
+        caps.setCapabilitySupport(Capability.COMMON_TABLE_EXPRESSIONS, true);
+        caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true);
+        capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$
+       
+	    String sql = "with a (x, y) as (select 1, 2 from pm1.g1) SELECT a.x from a, a z"; //$NON-NLS-1$
+	    
+	    FakeDataManager dataManager = new FakeDataManager();
+	    sampleData1(dataManager);
+	    
+	    TestOptimizer.helpPlan(sql, RealMetadataFactory.example1Cached(), null, capFinder, new String[] {"WITH a (x, y) AS (SELECT 1, 2 FROM pm1.g1 AS g_0) SELECT g_0.x FROM a AS g_0, a AS g_1"}, ComparisonMode.EXACT_COMMAND_STRING);
+	}
 
 }


Property changes on: branches/as7/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java:3149-3217
/trunk/engine/src/test/java/org/teiid/query/processor/TestWithClauseProcessing.java:3188-3382

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/eval/TestExpressionEvaluator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -60,7 +60,7 @@
 import org.teiid.query.sql.symbol.TestCaseExpression;
 import org.teiid.query.sql.symbol.TestSearchedCaseExpression;
 import org.teiid.query.sql.util.ValueIterator;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 @SuppressWarnings("nls")
@@ -194,7 +194,7 @@
         e2.setType(String.class);
         
         Function func = new Function("concat", new Expression[] { e1, e2 }); //$NON-NLS-1$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("concat", new Class[] { String.class, String.class } ); //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("concat", new Class[] { String.class, String.class } ); //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
 
         SingleElementSymbol[] elements = new SingleElementSymbol[] {
@@ -216,7 +216,7 @@
         e2.setType(String.class);
         
         Function func = new Function("concat", new Expression[] { e2, e1 }); //$NON-NLS-1$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("concat", new Class[] { String.class, String.class } ); //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("concat", new Class[] { String.class, String.class } ); //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
 
         SingleElementSymbol[] elements = new SingleElementSymbol[] {
@@ -237,7 +237,7 @@
         e1.setType(Integer.class);        
         
         Function func = new Function("lookup", new Expression[] { new Constant("pm1.g1"), new Constant("e2"), new Constant("e1"), e1 }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, String.class } ); //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, String.class } ); //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
 
         SingleElementSymbol[] elements = new SingleElementSymbol[] {
@@ -309,7 +309,7 @@
 
     @Test public void testUser() throws Exception {
         Function func = new Function("user", new Expression[] {}); //$NON-NLS-1$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("user", new Class[] {} );         //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("user", new Class[] {} );         //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
 
         FakeDataManager dataMgr = new FakeDataManager();
@@ -326,7 +326,7 @@
      */
     @Test public void testEnv() throws Exception {
         Function func = new Function("env", new Expression[] {}); //$NON-NLS-1$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("env", new Class[] {String.class} );         //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("env", new Class[] {String.class} );         //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
         
         FakeDataManager dataMgr = new FakeDataManager();
@@ -352,7 +352,7 @@
         } else {
             parameterSignature = new Class[] { String.class };
         }        
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("commandpayload", parameterSignature );         //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("commandpayload", parameterSignature );         //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
         
         FakeDataManager dataMgr = new FakeDataManager();       
@@ -432,4 +432,79 @@
     	assertEquals(Boolean.TRUE, Evaluator.evaluate(inc));
     }
     
+    @Test public void testSubstring() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("substring('abcd' from 2 for 2)");
+    	assertEquals("bc", Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testExtract() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("extract(year from cast('2011-01-01' as date))");
+    	assertEquals(2011, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testExtract1() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("extract(day from cast('2011-01-01' as date))");
+    	assertEquals(1, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testSimilarTo() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'aaaxy' similar to 'a+%'");
+    	assertEquals(Boolean.TRUE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testSimilarTo1() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xaay' similar to 'xa{2,3}y'");
+    	assertEquals(Boolean.TRUE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testSimilarTo2() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xay' similar to 'xa{2,3}y'");
+    	assertEquals(Boolean.FALSE, Evaluator.evaluate(ex));
+    }
+    
+    @Test(expected=ExpressionEvaluationException.class) public void testSimilarTo3() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xay' similar to '{'");
+    	assertEquals(Boolean.FALSE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testSimilarTo4() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xay' similar to 'xa{2,}y'");
+    	assertEquals(Boolean.FALSE, Evaluator.evaluate(ex));
+    }
+
+    @Test public void testSimilarTo5() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'x1y' similar to 'x([a-z]+|[0-9])_'");
+    	assertEquals(Boolean.TRUE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testSimilarTo6() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xx' similar to 'x([a-z]+|[0-9])_'");
+    	assertEquals(Boolean.FALSE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testLikeRegex() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'aaaxy' like_regex 'a+.*'");
+    	assertEquals(Boolean.TRUE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testLikeRegex1() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xaay' similar to 'xa{2,3}y'");
+    	assertEquals(Boolean.TRUE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testLikeRegex2() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xay' like_regex 'xa{2,3}y'");
+    	assertEquals(Boolean.FALSE, Evaluator.evaluate(ex));
+    }
+
+    @Test(expected=ExpressionEvaluationException.class) public void testLikeRegex3() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'xay' like_regex '{'");
+    	assertEquals(Boolean.FALSE, Evaluator.evaluate(ex));
+    }
+    
+    @Test public void testLikePlus() throws Exception {
+    	Expression ex = TestFunctionResolving.getExpression("'+' like '+'");
+    	assertEquals(Boolean.TRUE, Evaluator.evaluate(ex));
+    }
+    
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/proc/TestProcedureProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -29,13 +29,22 @@
 import java.util.List;
 
 import org.junit.Test;
+import org.mockito.Mockito;
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryProcessingException;
 import org.teiid.api.exception.query.QueryValidatorException;
 import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidException;
+import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.service.TransactionContext;
+import org.teiid.dqp.service.TransactionService;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.metadata.QueryMetadataInterface;
@@ -59,11 +68,6 @@
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 import org.teiid.query.validator.Validator;
@@ -125,131 +129,76 @@
     	helpTestProcess(procPlan, new List[] {Arrays.asList(expectedRows)}, dataMgr, metadata);
     }
     
-    // Helper to create a list of elements - used in creating sample data
-    private static List createElements(List elementIDs) { 
-        List elements = new ArrayList();
-        for(int i=0; i<elementIDs.size(); i++) {
-            FakeMetadataObject elementID = (FakeMetadataObject) elementIDs.get(i);            
-            ElementSymbol element = new ElementSymbol(elementID.getName());
-            elements.add(element);
-        }        
-        
-        return elements;
-    }    
-    
-    private FakeDataManager exampleDataManager(FakeMetadataFacade metadata) throws QueryMetadataException, TeiidComponentException {
+    private FakeDataManager exampleDataManager(QueryMetadataInterface metadata) throws TeiidException {
         FakeDataManager dataMgr = new FakeDataManager();
     
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Second", new Integer(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm1.g1", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Second", Integer.valueOf(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
 
-        groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g2"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Second", new Integer(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm1.g2", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Second", Integer.valueOf(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
         return dataMgr;
     }    
     
-    private FakeDataManager exampleDataManager2(FakeMetadataFacade metadata) throws QueryMetadataException, TeiidComponentException {
+    private FakeDataManager exampleDataManager2(QueryMetadataInterface metadata) throws TeiidException {
         FakeDataManager dataMgr = new FakeDataManager();
     
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Second", new Integer(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm1.g1", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Second", Integer.valueOf(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
 
-        groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g2"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Second", new Integer(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm1.g2", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Second", Integer.valueOf(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
-        groupID = (FakeMetadataObject) metadata.getGroupID("pm2.g1"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Second", new Integer(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm2.g1", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Second", Integer.valueOf(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
-        groupID = (FakeMetadataObject) metadata.getGroupID("pm2.g2"); //$NON-NLS-1$
-        elementIDs = metadata.getElementIDsInGroupID(groupID);
-        elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Second", new Integer(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm2.g2", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Second", Integer.valueOf(15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
         return dataMgr;
     }    
     
-    private FakeDataManager exampleDataManagerPm5(FakeMetadataFacade metadata) throws QueryMetadataException, TeiidComponentException {
+    private FakeDataManager exampleDataManagerPm5(QueryMetadataInterface metadata) throws TeiidException {
         FakeDataManager dataMgr = new FakeDataManager();
     
-        // Group stock.items
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm5.g3"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Short((short)5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Second", new Short((short)15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Short((short)51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm5.g3", new List[] { 
+				    Arrays.asList( new Object[] { "First", new Short((short)5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Second", new Short((short)15), new Boolean(true), new Double(2.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", new Short((short)51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
         return dataMgr;
     }    
@@ -264,7 +213,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -287,7 +236,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -310,7 +259,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
         dataMgr.setBlockOnce();
@@ -332,7 +281,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e2=40"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -362,7 +311,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -391,7 +340,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
         dataMgr.setBlockOnce();
@@ -419,7 +368,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e2=45"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -437,7 +386,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -474,7 +423,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -494,7 +443,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -522,7 +471,7 @@
 		
 		String userUpdateStr = "UPDATE vm1.g1 SET e2=30";    //$NON-NLS-1$
 		 
-		FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+		QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
 		FakeDataManager dataMgr = new FakeDataManager();
 		FakeDataStore.sampleData2(dataMgr);
 
@@ -550,7 +499,7 @@
 		
 		String userUpdateStr = "UPDATE vm1.g1 SET e2=30";    //$NON-NLS-1$
 		 
-		FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+		QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
 		FakeDataManager dataMgr = new FakeDataManager();
 		FakeDataStore.sampleData2(dataMgr);
 		
@@ -561,7 +510,7 @@
     @Test public void testVirtualProcedure() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -578,7 +527,7 @@
     @Test public void testVirtualProcedureWithBlockedException() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp2()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
         dataMgr.setBlockOnce();
@@ -596,7 +545,7 @@
     @Test public void testVirtualProcedure2() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp3()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -611,7 +560,7 @@
     @Test public void testVirtualProcedure3() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp4()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -626,7 +575,7 @@
     @Test public void testVirtualProcedure4() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp5()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -641,7 +590,7 @@
     @Test public void testVirtualProcedure5() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp6()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -656,7 +605,7 @@
     @Test public void testVirtualProcedure6() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp7(5)"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -671,7 +620,7 @@
     @Test public void testVirtualProcedure7() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp8(51)"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -686,7 +635,7 @@
     @Test public void testVirtualProcedure8() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp9(51)"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -701,7 +650,7 @@
     @Test public void testVirtualProcedure9() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp10(51)"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -716,7 +665,7 @@
     @Test public void testVirtualProcedure10() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp13()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -724,13 +673,13 @@
                 
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "Third", new Integer(5)})};         //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Third", Integer.valueOf(5)})};         //$NON-NLS-1$
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testVirtualProcedure11() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp14()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         // Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -746,24 +695,18 @@
     
     @Test public void testVirtualProcedure12() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp15()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         // Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
                 
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g2"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm1.g2", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
         // Create expected results
         List[] expected = new List[] {
@@ -775,25 +718,19 @@
     //Defect17447_testVirtualProcedure13
     @Test public void testVirtualProcedure13() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp16()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         // Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
                 
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g2"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm1.g2", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
         // Create expected results
         List[] expected = new List[] {
@@ -804,7 +741,7 @@
     		
     @Test public void testVirtualProcedure14() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp17()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         // Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -818,7 +755,7 @@
 
     @Test public void testVirtualProcedure15() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp19()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         // Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -838,7 +775,7 @@
     
     @Test public void testVirtualProcedure16() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp20()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         // Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -858,7 +795,7 @@
     
     @Test public void testVirtualProcedure17() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp21(7)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         //Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -866,16 +803,16 @@
   
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "First", new Integer(5)}),  //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Second", new Integer(15)}),  //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Third", new Integer(51)}),  //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Fourth", new Integer(7)})};           //$NON-NLS-1$
+            Arrays.asList(new Object[] { "First", Integer.valueOf(5)}),  //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Second", Integer.valueOf(15)}),  //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Third", Integer.valueOf(51)}),  //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Fourth", Integer.valueOf(7)})};           //$NON-NLS-1$
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testVirtualProcedure18() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp22(7)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         //Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -883,14 +820,14 @@
   
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "Second", new Integer(15)}),  //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Third", new Integer(51)}) }; //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Second", Integer.valueOf(15)}),  //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Third", Integer.valueOf(51)}) }; //$NON-NLS-1$
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testVirtualProcedure19() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp23(7)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         //Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -898,26 +835,26 @@
   
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "Second", new Integer(15)})}; //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Second", Integer.valueOf(15)})}; //$NON-NLS-1$
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testVirtualProcedure19WithBlockedException() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp23(7)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         //Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata); 
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "Second", new Integer(15)})}; //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Second", Integer.valueOf(15)})}; //$NON-NLS-1$
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
 
     @Test public void testVirtualProcedureNoDataInTempTable() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp25()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         //Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -946,7 +883,7 @@
 
         String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -957,7 +894,7 @@
     
     @Test public void testVirtualProcedure30() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp30()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
     
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
@@ -974,7 +911,7 @@
 
     @Test public void testVirtualProcedure31() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp31(51)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
         // Set up data
@@ -989,7 +926,7 @@
     @Test public void testVirtualProcedureDefect14282() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp24()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1003,7 +940,7 @@
     
     @Test public void testDefect16193() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp35(51)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
         // Set up data
@@ -1017,33 +954,23 @@
     
     @Test public void testVirtualProcedure16602() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp37()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
       
 
         // Set up data
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g1"); //$NON-NLS-1$
-        List elementSymbols = new ArrayList(); 
-        ElementSymbol element = new ElementSymbol("Count"); //$NON-NLS-1$
-        elementSymbols.add(element);            
+        HardcodedDataManager dataMgr = new HardcodedDataManager();
+        dataMgr.addData("INSERT INTO pm1.g1 (e1, e2, e3, e4) VALUES (null, 5, UNKNOWN, null)", new List[] {Arrays.asList(1)});
                     
-        dataMgr.registerTuples(
-        		groupID,
-        		elementSymbols,
-            new List[] {
-                 Arrays.asList( new Object[] { new Integer(1) } ) 
-                } );
-        
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { new Integer(1)})};           
+            Arrays.asList(1)};           
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testDefect16649_1() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp38()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
         // Set up data
@@ -1057,7 +984,7 @@
     
     @Test public void testDefect16649_2() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp39()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
         // Set up data
@@ -1071,7 +998,7 @@
     
     @Test public void testDefect16694() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp40()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
         // Set up data
@@ -1085,7 +1012,7 @@
     
     @Test public void testDefect16707() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp44(2)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
         // Set up data
@@ -1101,7 +1028,7 @@
     
     @Test public void testDefect16707_1() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp43(2)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
         // Set up data
@@ -1117,25 +1044,19 @@
     
     @Test public void testDefect17451() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp45()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         //Set up data
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
-                    
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("pm1.g2"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List elementSymbols = createElements(elementIDs);
     
         dataMgr.registerTuples(
-            groupID,
-            elementSymbols,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { "First", new Integer(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", new Integer(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
-                } );
+            metadata,
+            "pm1.g2", new List[] { 
+				    Arrays.asList( new Object[] { "First", Integer.valueOf(5), new Boolean(true), new Double(1.003)} ), //$NON-NLS-1$
+				    Arrays.asList( new Object[] { "Third", Integer.valueOf(51), new Boolean(true), new Double(3.003)} ) //$NON-NLS-1$
+				    } );
         
         // Create expected results
         List[] expected = new List[] {
@@ -1147,7 +1068,7 @@
     //Defect 17447
     @Test public void testVirtualProcedure46() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp46()";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);       
 
@@ -1181,7 +1102,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure1, procedure2);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1192,7 +1113,7 @@
     
     @Test public void testDefect19982() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp55(5)";     //$NON-NLS-1$
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 
         // Set up data
@@ -1200,16 +1121,16 @@
   
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "First", new Integer(5)}),  //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Second", new Integer(5)}), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Third", new Integer(5)})};           //$NON-NLS-1$
+            Arrays.asList(new Object[] { "First", Integer.valueOf(5)}),  //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Second", Integer.valueOf(5)}), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Third", Integer.valueOf(5)})};           //$NON-NLS-1$
         helpTestProcess(plan, expected, dataMgr, metadata);
     } 
     
     @Test public void testCase3521() throws Exception {
         String userUpdateStr = "EXEC pm1.vsp1()"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1242,7 +1163,7 @@
 
         String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1254,21 +1175,14 @@
     @Test public void testDynamicCommandWithIntoExpression() throws Exception {
     	
     	//Test INTO clause with expression
-    	FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'SELECT e1 FROM pm1.g1 WHERE e1 = ''First''' as x string into #temp; declare string VARIABLES.RESULT = select x from #temp;select VARIABLES.RESULT; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
+    	String query = "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+            + "execute string 'SELECT e1 FROM pm1.g1 WHERE e1 = ''First''' as x string into #temp; declare string VARIABLES.RESULT = select x from #temp;select VARIABLES.RESULT; END";
 
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, query);
+
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-        
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1279,16 +1193,31 @@
             };           
         helpTestProcess(plan, expected, dataMgr, metadata);
       }
+
+	private void addProc(TransformationMetadata metadata, String query)
+			throws QueryMetadataException {
+		addProc(metadata, "sq2", query, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[0], new String[0]);
+	}
+	
+	private void addProc(TransformationMetadata metadata, String name, String query, String[] rsCols, String[] rsTypes, String[] params, String[] paramTypes)
+	throws QueryMetadataException {
+		Schema pm1 = metadata.getMetadataStore().getSchema("PM1"); //$NON-NLS-1$
+		pm1.getProcedures().remove(name.toUpperCase());
+		ColumnSet<Procedure> rs2 = RealMetadataFactory.createResultSet("rs1", rsCols, rsTypes);
+		QueryNode sq2n1 = new QueryNode(query); //$NON-NLS-1$ 
+		ArrayList<ProcedureParameter> procParams = new ArrayList<ProcedureParameter>(params.length);
+		for (int i = 0; i < params.length; i++) {
+			procParams.add(RealMetadataFactory.createParameter(params[i], SPParameter.IN, paramTypes[i]));
+		}
+		Procedure sq1 = RealMetadataFactory.createVirtualProcedure(name, pm1, procParams, sq2n1);  //$NON-NLS-1$
+		sq1.setResultSet(rs2);
+	}
     
     @Test public void testDynamicCommandWithIntoAndLoop() throws Exception {
     	
     	//Test INTO clause with loop
-    	FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
         procedure.append("BEGIN\n"); //$NON-NLS-1$
         procedure.append("declare integer VARIABLES.e2_total=0;\n"); //$NON-NLS-1$
@@ -1301,13 +1230,9 @@
         procedure.append("SELECT VARIABLES.e2_total;\n"); //$NON-NLS-1$
         procedure.append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, procedure.toString());
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1315,26 +1240,18 @@
     	
         //Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { new Integer(66)}),  
+            Arrays.asList(new Object[] { Integer.valueOf(66)}),  
             };           
         helpTestProcess(plan, expected, dataMgr, metadata);
       }
     
     @Test public void testDynamicCommandWithParameter() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in' as e1 string, e2 integer; END"); //$NON-NLS-1$ //
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "execute string 'SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in' as e1 string, e2 integer; END", new String[] { "e1", "e2" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
 
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
-        
         String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1343,26 +1260,18 @@
                 
         // Create expected results
         List[] expected = new List[] {
-                Arrays.asList(new Object[] { "First", new Integer(5) }),  //$NON-NLS-1$
+                Arrays.asList(new Object[] { "First", Integer.valueOf(5) }),  //$NON-NLS-1$
         };        
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testDynamicCommandWithUsing() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "execute string 'SELECT e1, e2 FROM pm1.g1 WHERE e1=using.id' using id=pm1.sq2.in; END", new String[] { "e1", "e2" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'SELECT e1, e2 FROM pm1.g1 WHERE e1=using.id' using id=pm1.sq2.in; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
-        
         String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1371,26 +1280,18 @@
                 
         // Create expected results
         List[] expected = new List[] {
-                Arrays.asList(new Object[] { "First", new Integer(5) }),  //$NON-NLS-1$
+                Arrays.asList(new Object[] { "First", Integer.valueOf(5) }),  //$NON-NLS-1$
         };        
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testDynamicCommandWithVariable() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "declare string VARIABLES.x; VARIABLES.x = pm1.sq2.in; execute string 'SELECT e1, e2 FROM pm1.g1 WHERE e1=VARIABLES.x'; END", new String[] { "e1", "e2" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "declare string VARIABLES.x; VARIABLES.x = pm1.sq2.in; execute string 'SELECT e1, e2 FROM pm1.g1 WHERE e1=VARIABLES.x'; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
-        
         String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1399,26 +1300,18 @@
                 
         // Create expected results
         List[] expected = new List[] {
-                Arrays.asList(new Object[] { "First", new Integer(5) }),  //$NON-NLS-1$
+                Arrays.asList(new Object[] { "First", Integer.valueOf(5) }),  //$NON-NLS-1$
         };        
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testDynamicCommandValidationFails() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "declare object VARIABLES.x; execute string 'SELECT xmlelement(name elem, x)'; select 1; END", new String[] { "e1", "e2" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "declare object VARIABLES.x; execute string 'SELECT xmlelement(name elem, x)'; select 1; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
-        
         String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1434,21 +1327,13 @@
     }
 
     @Test public void testDynamicCommandWithSingleSelect() throws Exception {
-    	//Test select of a single value in a DynamicCommand
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'SELECT 26'; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
+        addProc(metadata, "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+                + "execute string 'SELECT 26'; END");
 
-        metadata.getStore().addObject(rs1);
-        metadata.getStore().addObject(sq1);
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-        
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1463,20 +1348,12 @@
     
     //converts e1 from integer to string, with a different name
     @Test public void testDynamicCommandTypeConversion() throws Exception {
-    	 FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-         
-         FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-         
-         FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-         FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-         FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-         QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                         + "declare string VARIABLES.x; VARIABLES.x = 'a'; execute string 'SELECT e2 ' || ' FROM pm1.g1 ' || ' where e1=pm1.sq2.in'; END"); //$NON-NLS-1$ //
-         FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-         metadata.getStore().addObject(rs2);
-         metadata.getStore().addObject(sq2);
-         
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "declare string VARIABLES.x; VARIABLES.x = 'a'; execute string 'SELECT e2 ' || ' FROM pm1.g1 ' || ' where e1=pm1.sq2.in'; END", new String[] { "e1" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
+        
          String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
          
          FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1491,24 +1368,12 @@
     }
     
     @Test public void testDynamicCommandRecursion() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
+        
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "execute string 'EXEC pm1.sq2(''First'')' as e1 string, e2 integer; END", new String[] { "e1", "e2" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-
-        FakeMetadataObject rs2 = FakeMetadataFactory
-                                                    .createResultSet("pm1.rs2", pm1, new String[] {"e1", "e2"}, new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory
-                                                      .createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2); //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory
-                                                      .createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null); //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                                   + "execute string 'EXEC pm1.sq2(''First'')' as e1 string, e2 integer; END"); //$NON-NLS-1$ //
-        FakeMetadataObject sq2 = FakeMetadataFactory
-                                                    .createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] {rs2p1, rs2p2}), sq2n1); //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
-
         String userUpdateStr = "EXEC pm1.sq2('First')"; //$NON-NLS-1$
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1522,25 +1387,16 @@
     
     @Test public void testDynamicCommandIncorrectProjectSymbolCount() throws Exception {
     	//Tests dynamic query with incorrect number of elements   
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "SELECT pm1.g1.e1 FROM pm1.g1; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-        
-        QueryNode sq2n2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                + "execute string 'EXEC pm1.sq1(''First'')' as e1 string, e2 integer; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n2);  //$NON-NLS-1$
+        addProc(metadata, "sq1", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "SELECT pm1.g1.e1 FROM pm1.g1; END", new String[] { "e1" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
 
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
-        metadata.getStore().addObject(sq2);
-        
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "execute string 'EXEC pm1.sq1(''First'')' as e1 string, e2 integer; END", new String[] { "e1" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
+
         String userUpdateStr = "EXEC pm1.sq2('test')"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1551,23 +1407,14 @@
      }
     
     @Test public void testDynamicCommandPositional() throws Exception {
-    	//Tests dynamic query with incorrect number of elements   
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "execute string 'select e1 as x, e2 from pm1.g1'; END", new String[] { "e1", "e2" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
+
+        String userUpdateStr = "EXEC pm1.sq2('test')"; //$NON-NLS-1$
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'select e1 as x, e2 from pm1.g1'; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-        
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
-        
-        String userUpdateStr = "EXEC pm1.sq1('test')"; //$NON-NLS-1$
-        
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1578,23 +1425,13 @@
      }
     
     @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();
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+										                                + "execute string 'select e1 from pm1.g1'; END", new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER}, new String[0], new String[0]); //$NON-NLS-1$ 
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'select e1 from pm1.g1'; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
-        
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
-        
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1604,19 +1441,12 @@
      
     @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();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        addProc(metadata, "sq1", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+				        + "execute string 'select e1 as x, e2 from pm1.g1'; END", new String[] { "e1", "e2" }
+        , new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }, new String[0], new String[0]);
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'select e1 from pm1.g1'; execute string 'select e1, e2 from pm1.g1' as e1 string, e2 integer; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
-        
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
-        
         String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1625,15 +1455,15 @@
     	
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "First", new Integer(5)}),  //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Second", new Integer(15)}), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Third", new Integer(51)})};           //$NON-NLS-1$      
+            Arrays.asList(new Object[] { "First", "5"}),  //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Second", "15"}), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Third", "51"})};           //$NON-NLS-1$      
        
         helpTestProcess(plan, expected, dataMgr, metadata);
      }
     
     @Test public void testAssignmentWithCase() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
         String sql = new StringBuffer("declare integer caseValue = ") //$NON-NLS-1$
         .append("CASE") //$NON-NLS-1$
@@ -1644,18 +1474,9 @@
         .append(" ELSE 9999") //$NON-NLS-1$
         .append(" END").toString(); //$NON-NLS-1$
 
+        addProc(metadata, "sq1", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+                                        + sql + "; SELECT caseValue; END", new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER}, new String[] {"param"}, new String[] {DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$ 
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("param", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$        
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + sql + "; SELECT caseValue; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs1);
-        metadata.getStore().addObject(sq1);
-        
         String userUpdateStr = "EXEC pm1.sq1('d')"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -1664,7 +1485,7 @@
                 
         // Create expected results
         List[] expected = new List[] {
-                Arrays.asList(new Object[] { new Integer(3) }),  
+                Arrays.asList(new Object[] { Integer.valueOf(3) }),  
         };        
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
@@ -1672,50 +1493,35 @@
     @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();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm5 = metadata.getStore().findObject("pm5",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("pm5.rs1", pm5, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.SHORT}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'select e1,e2 from pm5.g3' as e1 string, e2 integer INTO #temp; select * from #temp; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm5.sq1", pm5, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1 );  //$NON-NLS-1$
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+                + "execute string 'select e1,e2 from pm5.g3' as e1 string, e2 integer INTO #temp; select * from #temp; END", new String[] { "e1", "e2"}, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.SHORT}, new String[0], new String[0]); //$NON-NLS-1$
         
-        metadata.getStore().addObject(rs1);
-        metadata.getStore().addObject(sq1);
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
-        String userUpdateStr = "EXEC pm5.sq1()"; //$NON-NLS-1$
-        
         FakeDataManager dataMgr = exampleDataManagerPm5(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
     	
         // Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { "First", new Integer(5)}),  //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Second", new Integer(15)}), //$NON-NLS-1$
-            Arrays.asList(new Object[] { "Third", new Integer(51)})};           //$NON-NLS-1$      
+            Arrays.asList(new Object[] { "First", Integer.valueOf(5)}),  //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Second", Integer.valueOf(15)}), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "Third", Integer.valueOf(51)})};           //$NON-NLS-1$      
        
         helpTestProcess(plan, expected, dataMgr, metadata);
      }
     
     @Test public void testDynamicCommandWithVariableOnly() throws Exception {
     	//Tests dynamic query with only a variable that represents thte entire dynamic query.
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm5 = metadata.getStore().findObject("pm5",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("pm5.rs1", pm5, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.SHORT}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("param", 1, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.SHORT, rs1);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("ret", 2, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "DECLARE string VARIABLES.CRIT = 'select e1, e2 from pm5.g3 where e2=using.id'; execute string VARIABLES.CRIT USING ID = pm5.sq1.param; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm5.sq1", pm5, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1 );  //$NON-NLS-1$
+        addProc(metadata, "sq1", "CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+                + "DECLARE string VARIABLES.CRIT = 'select e1, e2 from pm5.g3 where e2=using.id'; execute string VARIABLES.CRIT USING ID = pm1.sq1.param; END", new String[] { "e1", "e2"}, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.SHORT}, new String[] {"param"}, new String[] {DataTypeManager.DefaultDataTypes.SHORT}); //$NON-NLS-1$
         
-        metadata.getStore().addObject(rs1);
-        metadata.getStore().addObject(sq1);
+        String userUpdateStr = "EXEC pm1.sq1(convert(5,short))"; //$NON-NLS-1$
         
-        String userUpdateStr = "EXEC pm5.sq1(convert(5,short))"; //$NON-NLS-1$
-        
         FakeDataManager dataMgr = exampleDataManagerPm5(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -1729,7 +1535,7 @@
     @Test public void testVirtualProcedureWithCreate() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp60()"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1746,7 +1552,7 @@
     @Test public void testVirtualProcedureWithCreateAndDrop() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp61()"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1763,7 +1569,7 @@
     @Test public void testVirtualProcedureWithCreateAndSelectInto() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp62()"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1779,12 +1585,8 @@
     
     @Test public void testDifferentlyScopedTempTables() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
         procedure.append("BEGIN\n"); //$NON-NLS-1$
         procedure.append("declare integer VARIABLES.e2_total=0;\n"); //$NON-NLS-1$
@@ -1801,13 +1603,9 @@
         procedure.append("SELECT VARIABLES.e2_total;\n"); //$NON-NLS-1$
         procedure.append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, procedure.toString());
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1815,19 +1613,15 @@
         
         //Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { new Integer(3)}),  
+            Arrays.asList(new Object[] { Integer.valueOf(3)}),  
             };           
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testLoopsWithBreak() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
         procedure.append("BEGIN\n"); //$NON-NLS-1$
         procedure.append("declare integer VARIABLES.e2_total=0;\n"); //$NON-NLS-1$
@@ -1843,33 +1637,67 @@
         procedure.append("SELECT VARIABLES.e2_total;\n"); //$NON-NLS-1$
         procedure.append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
+        addProc(metadata, procedure.toString());
+        
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
+        
+        FakeDataManager dataMgr = exampleDataManager(metadata);
 
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+        //Create expected results
+        List[] expected = new List[] {
+            Arrays.asList(new Object[] { Integer.valueOf(76)}),  
+            };           
+        helpTestProcess(plan, expected, dataMgr, metadata);
+    }
+    
+    @Test public void testLoopsWithLabels() throws Exception {
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
+        StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
+        procedure.append("y: BEGIN\n"); //$NON-NLS-1$
+        procedure.append("declare integer VARIABLES.e2_total=param1;\n"); //$NON-NLS-1$
+        procedure.append("x: loop on (select e2 as x from pm1.g1) as mycursor\n"); //$NON-NLS-1$
+        procedure.append("BEGIN\n"); //$NON-NLS-1$
+        procedure.append("e2_total=e2_total+mycursor.x;\n"); //$NON-NLS-1$
+        procedure.append("loop on (select e2 as x from pm1.g1) as mycursor1\n"); //$NON-NLS-1$
+        procedure.append("BEGIN\n"); //$NON-NLS-1$
+        procedure.append("if (e2_total < 5)\n"); //$NON-NLS-1$
+        procedure.append("break x;\n"); //$NON-NLS-1$
+        procedure.append("else if (e2_total > 50)\n"); //$NON-NLS-1$
+        procedure.append("leave y;\n"); //$NON-NLS-1$
+        procedure.append("e2_total=e2_total+mycursor1.x;"); //$NON-NLS-1$
+        procedure.append("END\n"); //$NON-NLS-1$
+        procedure.append("END\n"); //$NON-NLS-1$
+        procedure.append("SELECT VARIABLES.e2_total;\n"); //$NON-NLS-1$
+        procedure.append("END"); //$NON-NLS-1$
+        
+        addProc(metadata, "sq2", procedure.toString(), new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }, new String[] {"param1"}, new String[] {DataTypeManager.DefaultDataTypes.INTEGER});
+        
+        String userUpdateStr = "EXEC pm1.sq2(1)"; //$NON-NLS-1$
+        
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
         
         //Create expected results
         List[] expected = new List[] {
-            Arrays.asList(new Object[] { new Integer(76)}),  
             };           
         helpTestProcess(plan, expected, dataMgr, metadata);
+        
+        expected = new List[] {
+            Arrays.asList(0),  
+            };           
+        userUpdateStr = "EXEC pm1.sq2(-5)"; //$NON-NLS-1$
+        plan = getProcedurePlan(userUpdateStr, metadata);
+        helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
     @Test public void testCreateWithoutDrop() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
         procedure.append("BEGIN\n"); //$NON-NLS-1$
         procedure.append("create local temporary table t1 (e1 integer);\n"); //$NON-NLS-1$
@@ -1877,13 +1705,9 @@
         procedure.append("SELECT e1 from t1;\n"); //$NON-NLS-1$
         procedure.append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, procedure.toString());
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1897,12 +1721,8 @@
      */
     @Test public void testDoubleDrop() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
         procedure.append("BEGIN\n"); //$NON-NLS-1$
         procedure.append("create local temporary table t1 (e1 string);\n"); //$NON-NLS-1$
@@ -1912,13 +1732,9 @@
         procedure.append("SELECT 1;\n"); //$NON-NLS-1$
         procedure.append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, procedure.toString());
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -1931,33 +1747,28 @@
      * defect 23975 
      */
     @Test public void testFunctionInput() throws Exception {
-        FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadataStore); //$NON-NLS-1$
 
-        FakeMetadataObject p1 = FakeMetadataFactory.createParameter("v1.vp1.in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("v1.rs1", v1, new String[] {"e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject rs1p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
+        ProcedureParameter p1 = RealMetadataFactory.createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ColumnSet<Procedure> rs1 = RealMetadataFactory.createResultSet("v1.rs1", new String[] {"e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
 
         QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string VARIABLES.x = '1'; exec v1.vp2(concat(x, v1.vp1.in)); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vt1 = FakeMetadataFactory.createVirtualProcedure("v1.vp1", v1, Arrays.asList(new FakeMetadataObject[] { rs1p1, p1 }), n1); //$NON-NLS-1$
+        Procedure vt1 = RealMetadataFactory.createVirtualProcedure("vp1", v1, Arrays.asList(p1), n1); //$NON-NLS-1$
+        vt1.setResultSet(rs1);
         
-        FakeMetadataObject p2 = FakeMetadataFactory.createParameter("v1.vp2.in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        ProcedureParameter p2 = RealMetadataFactory.createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
         QueryNode n2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN select v1.vp2.in; end"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vt2 = FakeMetadataFactory.createVirtualProcedure("v1.vp2", v1, Arrays.asList(new FakeMetadataObject[] { rs1p1, p2 }), n2); //$NON-NLS-1$
+        Procedure vt2 = RealMetadataFactory.createVirtualProcedure("vp2", v1, Arrays.asList(p2), n2); //$NON-NLS-1$
+        vt2.setResultSet(RealMetadataFactory.createResultSet("v1.rs1", new String[] {"e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING })); //$NON-NLS-1$ //$NON-NLS-2$
                 
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(v1);
-        store.addObject(rs1);
-        store.addObject(vt1);
-        store.addObject(vt2);
-        store.addObject(vt2);
-        
         String sql = "exec v1.vp1('1')"; //$NON-NLS-1$
         
         List[] expected = new List[] {  
             Arrays.asList(new Object[] { "11" }), //$NON-NLS-1$ 
         };        
         
-        FakeMetadataFacade metadata = new FakeMetadataFacade(store);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "foo");
         
         // Construct data manager with data 
         // Plan query 
@@ -1989,7 +1800,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure1, procedure2);
         
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
                                      
@@ -2004,23 +1815,15 @@
         // Create query 
         String sql = "EXEC pm1.vsp49()"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataStore store = metadata.getStore();
+        addProc(metadata, "sq2", "CREATE VIRTUAL PROCEDURE BEGIN if (1 = 2) begin declare integer x = 1; end SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in; END", 
+        		new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }
+        , new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});  //$NON-NLS-1$
         
-        FakeMetadataObject pm1 = store.findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN if (1 = 2) begin declare integer x = 1; end SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-        
-        store.addObject(sq2);
-        
         // Create expected results
         List[] expected = new List[] { 
-            Arrays.asList(new Object[] { "b", new Integer(2) }), //$NON-NLS-1$
+            Arrays.asList(new Object[] { "b", Integer.valueOf(2) }), //$NON-NLS-1$
         };    
     
         // Construct data manager with data
@@ -2035,12 +1838,8 @@
     }
     
     @Test public void testInsertAfterCreate() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n") //$NON-NLS-1$
         .append("BEGIN\n") //$NON-NLS-1$
         .append("\n  create local temporary table #temp (e1 string, e2 string);") //$NON-NLS-1$
@@ -2049,13 +1848,9 @@
         .append("SELECT e2 as e1 from #temp;\n") //$NON-NLS-1$
         .append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, procedure.toString());
         
-        String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
+        String userUpdateStr = "EXEC pm1.sq2()"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -2079,7 +1874,7 @@
 
         String userUpdateStr = "UPDATE g4 SET e1='x' where e2=5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -2108,7 +1903,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x' where e2=5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure, procedure2);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure, procedure2);
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -2118,23 +1913,14 @@
     }
     
     @Test public void testEvaluatableSelectWithOrderBy() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("param", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n") //$NON-NLS-1$
         .append("BEGIN\n") //$NON-NLS-1$
         .append("SELECT param from pm1.g1 order by param limit 1;\n") //$NON-NLS-1$
         .append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, "sq1", procedure.toString(), new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[] {"param"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
         
         String userUpdateStr = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
         
@@ -2148,23 +1934,14 @@
     }
     
     @Test public void testEvaluatableSelectWithOrderBy1() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
+        TransformationMetadata metadata = RealMetadataFactory.example1();
         
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("param", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n") //$NON-NLS-1$
         .append("BEGIN\n") //$NON-NLS-1$
         .append("SELECT param from pm1.g1 union select e1 from pm1.g1 order by param limit 2;\n") //$NON-NLS-1$
         .append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+        addProc(metadata, "sq1", procedure.toString(), new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[] {"param"}, new String[] {DataTypeManager.DefaultDataTypes.STRING});
         
         String userUpdateStr = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
         
@@ -2200,7 +1977,7 @@
         .append("SELECT * FROM #TEMP;\n") //$NON-NLS-1$
         .append("END"); //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = createProcedureMetadata(procedure.toString());
+        QueryMetadataInterface metadata = createProcedureMetadata(procedure.toString());
         
         String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
         
@@ -2210,24 +1987,13 @@
         
         
         helpTestProcess(plan, new List[] {
-            Arrays.asList(new Object[] {new Integer(240)}),
-            Arrays.asList(new Object[] {new Integer(637)})}, dataMgr, metadata);
+            Arrays.asList(new Object[] {Integer.valueOf(240)}),
+            Arrays.asList(new Object[] {Integer.valueOf(637)})}, dataMgr, metadata);
     }
 
-    private FakeMetadataFacade createProcedureMetadata(String procedure) {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        
-        
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1}), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
+    private QueryMetadataInterface createProcedureMetadata(String procedure) throws QueryMetadataException {
+    	TransformationMetadata metadata = RealMetadataFactory.example1();
+    	addProc(metadata, "sq1", procedure, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[0], new String[0]);
         return metadata;
     }
     
@@ -2240,7 +2006,7 @@
         procedure += "Select x from temp;\n"; //$NON-NLS-1$
         procedure += "END\n"; //$NON-NLS-1$
                 
-        FakeMetadataFacade metadata = createProcedureMetadata(procedure);
+        QueryMetadataInterface metadata = createProcedureMetadata(procedure);
         
         String userUpdateStr = "EXEC pm1.sq1()"; //$NON-NLS-1$
         
@@ -2257,24 +2023,21 @@
      * wraps {@link TestXMLPlanningEnhancements.testNested2WithContextCriteria5d1} in a procedure
      */
     @Test public void testXMLWithExternalCriteria() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
                 
-        FakeMetadataObject pm1 = metadata.getStore().findObject("xqttest",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        Schema pm1 = metadata.getMetadataStore().getSchemas().get("XMLTEST"); //$NON-NLS-1
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("input", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
+        ColumnSet<Procedure> rs2 = RealMetadataFactory.createResultSet("pm1.rs2", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs2p2 = RealMetadataFactory.createParameter("input", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
         QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "declare integer VARIABLES.x = xqttest.proc.input; SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)=x OR OrderID='2'; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("xqttest.proc", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
+                                        + "declare integer VARIABLES.x = proc.input; SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)=x OR OrderID='2'; END"); //$NON-NLS-1$ 
+        Procedure sq2 = RealMetadataFactory.createVirtualProcedure("proc", pm1, Arrays.asList(rs2p2), sq2n1);  //$NON-NLS-1$
+        sq2.setResultSet(rs2);
         
-        String userUpdateStr = "EXEC xqttest.proc(5)"; //$NON-NLS-1$
+        String userUpdateStr = "EXEC proc(5)"; //$NON-NLS-1$
         
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
                         
@@ -2286,25 +2049,22 @@
     }
     
     @Test public void testXMLWithExternalCriteria_InXMLVar() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+    	TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
-        expectedDoc = expectedDoc.replaceAll("\\r", ""); //$NON-NLS-1$ //$NON-NLS-2$        
-        FakeMetadataObject pm1 = metadata.getStore().findObject("xqttest",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        expectedDoc = expectedDoc.replaceAll("\\r", ""); //$NON-NLS-1$ //$NON-NLS-2$   
+        Schema pm1 = metadata.getMetadataStore().getSchemas().get("XMLTEST"); //$NON-NLS-1
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("input", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
+        ColumnSet<Procedure> rs2 = RealMetadataFactory.createResultSet("pm1.rs2", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs2p2 = RealMetadataFactory.createParameter("input", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
         QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "declare integer VARIABLES.x = xqttest.proc.input; declare xml y = SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)=x OR OrderID='2'; select convert(y, string); END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("xqttest.proc", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
+                                        + "declare integer VARIABLES.x = proc.input; declare xml y = SELECT * FROM xmltest.doc9 WHERE context(SupplierID, OrderID)=x OR OrderID='2'; select convert(y, string); END"); //$NON-NLS-1$ 
+        Procedure sq2 = RealMetadataFactory.createVirtualProcedure("proc", pm1, Arrays.asList(rs2p2), sq2n1);  //$NON-NLS-1$
+        sq2.setResultSet(rs2);
 
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
+        String userUpdateStr = "EXEC proc(5)"; //$NON-NLS-1$
         
-        String userUpdateStr = "EXEC xqttest.proc(5)"; //$NON-NLS-1$
-        
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
                         
         // Create expected results
@@ -2320,7 +2080,7 @@
      * This one will successfully auto-stage
      */
     @Test public void testXMLWithExternalCriteria1() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+    	TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +  //$NON-NLS-1$
@@ -2358,18 +2118,14 @@
             "   </Catalog>\n" +  //$NON-NLS-1$
             "</Catalogs>"; //$NON-NLS-1$
 
-        FakeMetadataObject pm1 = metadata.getStore().findObject("xmltest",FakeMetadataObject.MODEL); //$NON-NLS-1$
+        Schema pm1 = metadata.getMetadataStore().getSchemas().get("XMLTEST"); //$NON-NLS-1
         
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("input", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
+        ColumnSet<Procedure> rs2 = RealMetadataFactory.createResultSet("pm1.rs2", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs2p2 = RealMetadataFactory.createParameter("input", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
         QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
                                         + "declare integer VARIABLES.x = xmltest.proc.input; SELECT * FROM xmltest.doc9 WHERE context(SupplierID, SupplierID)=x; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("xmltest.proc", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq2);
-        
+        Procedure sq2 = RealMetadataFactory.createVirtualProcedure("proc", pm1, Arrays.asList(rs2p2), sq2n1);  //$NON-NLS-1$
+        sq2.setResultSet(rs2);
         String userUpdateStr = "EXEC xmltest.proc(52)"; //$NON-NLS-1$
         
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
@@ -2384,7 +2140,7 @@
     @Test public void testCase174806() throws Exception{
         String userUpdateStr = "EXEC pm1.vsp63()"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
@@ -2398,7 +2154,7 @@
     
     @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();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
 
         ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);   
 
@@ -2451,12 +2207,12 @@
         procedure += "   SELECT VARIABLES.Var1 AS e1;\n"; //$NON-NLS-1$
         procedure += "END\n"; //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = createProcedureMetadata(procedure);
+        QueryMetadataInterface metadata = createProcedureMetadata(procedure);
         String userQuery = "SELECT e1 FROM (EXEC pm1.sq1()) as proc"; //$NON-NLS-1$
         FakeDataManager dataMgr = exampleDataManager(metadata);
         ProcessorPlan plan = getProcedurePlan(userQuery, metadata);
 
-        List[] expected = new List[] {Arrays.asList(new Object[] {new Integer(3)})};
+        List[] expected = new List[] {Arrays.asList(new Object[] {Integer.valueOf(3)})};
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
     
@@ -2473,7 +2229,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         FakeDataManager dataMgr = exampleDataManager(metadata);
 		ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 		helpTestProcess(plan, 5, dataMgr, metadata);									 
@@ -2491,7 +2247,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
                                      
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         FakeDataManager dataMgr = exampleDataManager(metadata);
 		ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 		helpTestProcess(plan, 0, dataMgr, metadata);									 
@@ -2506,7 +2262,7 @@
     
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
     
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
         FakeDataManager dataMgr = exampleDataManager(metadata);
 		ProcessorPlan plan = getProcedurePlan(userUpdateStr, metadata);
 		helpTestProcess(plan, 8, dataMgr, metadata);									 
@@ -2542,15 +2298,15 @@
         		"   " + sql + ";" + //$NON-NLS-1$ //$NON-NLS-2$
         		"END"; //$NON-NLS-1$
         	
-        FakeMetadataFacade metadata = createProcedureMetadata(proc);
+        QueryMetadataInterface metadata = createProcedureMetadata(proc);
         String userQuery = "SELECT * FROM (EXEC pm1.sq1()) as proc"; //$NON-NLS-1$
         FakeDataManager dataMgr = exampleDataManager2(metadata);
         ProcessorPlan plan = getProcedurePlan(userQuery, metadata);
 
         List[] expected = new List[] {
-                Arrays.asList( new Object[] { "First", "First", new Integer(5), new Integer(5)} ), //$NON-NLS-1$ //$NON-NLS-2$
-                Arrays.asList( new Object[] { "Second", null, new Integer(15), null} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", null, new Integer(51), null} ) //$NON-NLS-1$
+                Arrays.asList( new Object[] { "First", "First", Integer.valueOf(5), Integer.valueOf(5)} ), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList( new Object[] { "Second", null, Integer.valueOf(15), null} ), //$NON-NLS-1$
+                Arrays.asList( new Object[] { "Third", null, Integer.valueOf(51), null} ) //$NON-NLS-1$
         };
         helpTestProcess(plan, expected, dataMgr, metadata);
         
@@ -2588,15 +2344,15 @@
         		"   " + sql + ";" + //$NON-NLS-1$ //$NON-NLS-2$
         		"END"; //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = createProcedureMetadata(proc);
+        QueryMetadataInterface metadata = createProcedureMetadata(proc);
         String userQuery = "SELECT * FROM (EXEC pm1.sq1()) as proc"; //$NON-NLS-1$
         FakeDataManager dataMgr = exampleDataManager2(metadata);
         ProcessorPlan plan = getProcedurePlan(userQuery, metadata, TestOptimizer.getGenericFinder());
 
         List[] expected = new List[] {
-                Arrays.asList( new Object[] { "First", "First", new Integer(5), new Integer(5)} ), //$NON-NLS-1$ //$NON-NLS-2$
-                Arrays.asList( new Object[] { "Second", null, new Integer(15), null} ), //$NON-NLS-1$
-                Arrays.asList( new Object[] { "Third", null, new Integer(51), null} ) //$NON-NLS-1$
+                Arrays.asList( new Object[] { "First", "First", Integer.valueOf(5), Integer.valueOf(5)} ), //$NON-NLS-1$ //$NON-NLS-2$
+                Arrays.asList( new Object[] { "Second", null, Integer.valueOf(15), null} ), //$NON-NLS-1$
+                Arrays.asList( new Object[] { "Third", null, Integer.valueOf(51), null} ) //$NON-NLS-1$
         };
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
@@ -2610,7 +2366,7 @@
                 " select e1 from #t1;\n" + //$NON-NLS-1$
         		"END"; //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = createProcedureMetadata(proc);
+        QueryMetadataInterface metadata = createProcedureMetadata(proc);
         String userQuery = "SELECT * FROM (EXEC pm1.sq1()) as proc"; //$NON-NLS-1$
         FakeDataManager dataMgr = exampleDataManager2(metadata);
         ProcessorPlan plan = getProcedurePlan(userQuery, metadata, TestOptimizer.getGenericFinder());
@@ -2629,7 +2385,7 @@
                 " select e2 from (exec pm1.sq2((select max(e1) from t1))) x;\n" + //$NON-NLS-1$
         		"END"; //$NON-NLS-1$
 
-        FakeMetadataFacade metadata = createProcedureMetadata(proc);
+        QueryMetadataInterface metadata = createProcedureMetadata(proc);
         String userQuery = "SELECT * FROM (EXEC pm1.sq1()) as proc"; //$NON-NLS-1$
         FakeDataManager dataMgr = exampleDataManager2(metadata);
         ProcessorPlan plan = getProcedurePlan(userQuery, metadata, TestOptimizer.getGenericFinder());
@@ -2642,7 +2398,7 @@
     
     @Test public void testUnambiguousVirtualProc() throws Exception {
         String userQuery = "EXEC MMSP6('1')"; //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         ProcessorPlan plan = getProcedurePlan(userQuery, metadata, TestOptimizer.getGenericFinder());
 
         List[] expected = new List[] {
@@ -2664,13 +2420,7 @@
     
     @Test public void testNonQueryPushdownValidation() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject in = FakeMetadataFactory.createParameter("pm1.sq1.in1", 2, SPParameter.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
+        TransformationMetadata metadata = RealMetadataFactory.example1();
 
         StringBuffer procedure = new StringBuffer("CREATE VIRTUAL PROCEDURE \n"); //$NON-NLS-1$
         procedure.append("BEGIN\n"); //$NON-NLS-1$
@@ -2681,12 +2431,8 @@
         procedure.append("exec pm1.sq2(in1 || 'foo');\n"); //$NON-NLS-1$
         procedure.append("END"); //$NON-NLS-1$
         
-        QueryNode sq2n1 = new QueryNode(procedure.toString()); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { in, rs2p1 }), sq2n1);  //$NON-NLS-1$
+        addProc(metadata, "sq1", procedure.toString(), new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }, new String[] {"in1"}, new String[] {DataTypeManager.DefaultDataTypes.INTEGER});        
 
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
-        
         String userUpdateStr = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
         
         FakeDataManager dataMgr = exampleDataManager(metadata);
@@ -2733,6 +2479,54 @@
 
         helpTestProcess(plan, expected, dataMgr, metadata);
     }
+    
+    @Test public void testBeginAtomic() throws Exception {
+        String proc = "CREATE VIRTUAL PROCEDURE " + //$NON-NLS-1$
+        		"BEGIN ATOMIC" + //$NON-NLS-1$
+                " select e1, e2, e3, e4 into #t1 from pm1.g1;\n" + //$NON-NLS-1$
+                " update #t1 set e1 = 1 where e4 < 2;\n" + //$NON-NLS-1$
+                " delete from #t1 where e4 > 2;\n" + //$NON-NLS-1$
+                " select e2/\"in\" from #t1;\n" + //$NON-NLS-1$
+        		"END"; //$NON-NLS-1$
+        TransformationMetadata tm = RealMetadataFactory.example1();
+        addProc(tm, "sq1", proc, new String[] { "e1" }, 
+        		new String[] { DataTypeManager.DefaultDataTypes.INTEGER }, new String[] {"in"}, new String[] {DataTypeManager.DefaultDataTypes.INTEGER});
+        FakeDataManager dataMgr = exampleDataManager(tm);
+        CommandContext context = new CommandContext("pID", null, null, null, 1); //$NON-NLS-1$
+    	QueryMetadataInterface metadata = new TempMetadataAdapter(tm, new TempMetadataStore());
+        context.setMetadata(metadata);
 
+        TransactionContext tc = new TransactionContext();
+        TransactionService ts = Mockito.mock(TransactionService.class);
+        context.setTransactionService(ts);
+        context.setTransactionContext(tc);
+        String userQuery = "EXEC pm1.sq1(1)"; //$NON-NLS-1$
+        ProcessorPlan plan = getProcedurePlan(userQuery, tm, TestOptimizer.getGenericFinder());
+        List[] expected = new List[] {
+                Arrays.asList(5), 
+        };
+    	TestProcessor.helpProcess(plan, context, dataMgr, expected);
+    	Mockito.verify(ts, Mockito.times(3)).begin(tc);
+    	Mockito.verify(ts, Mockito.times(3)).commit(tc);
+    	
+    	tc = new TransactionContext();
+        ts = Mockito.mock(TransactionService.class);
+        context.setTransactionService(ts);
+        context.setTransactionContext(tc);
+        userQuery = "EXEC pm1.sq1(0)"; //$NON-NLS-1$
+        plan = getProcedurePlan(userQuery, tm, TestOptimizer.getGenericFinder());
+        expected = null;
+        try {
+        	TestProcessor.helpProcess(plan, context, dataMgr, expected);
+        	fail();
+        } catch (TeiidProcessingException e) {
+        	
+        }
+    	Mockito.verify(ts).begin(tc);
+    	Mockito.verify(ts).resume(tc);
+    	Mockito.verify(ts, Mockito.times(0)).commit(tc);
+    	Mockito.verify(ts).rollback(tc);
+    }
+
     private static final boolean DEBUG = false;
 }

Deleted: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/NodeTestUtil.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/NodeTestUtil.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/NodeTestUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,73 +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 org.teiid.query.processor.relational;
-
-import org.teiid.common.buffer.BufferManager;
-import org.teiid.common.buffer.StorageManager;
-import org.teiid.common.buffer.impl.BufferManagerImpl;
-import org.teiid.common.buffer.impl.MemoryStorageManager;
-import org.teiid.core.TeiidComponentException;
-
-/** 
- * @since 4.2
- */
-public class NodeTestUtil {
-    
-    static BufferManager getTestBufferManager(long bytesAvailable, int procBatchSize, int connectorBatchSize) {
-    	BufferManagerImpl bufferManager = new BufferManagerImpl();
-    	bufferManager.setProcessorBatchSize(procBatchSize);
-    	bufferManager.setConnectorBatchSize(connectorBatchSize);
-    	bufferManager.setMaxProcessingBatchColumns((int)(bytesAvailable/procBatchSize/BufferManagerImpl.KB_PER_VALUE/1024));
-    	bufferManager.setMaxReserveBatchColumns((int)(bytesAvailable/procBatchSize/BufferManagerImpl.KB_PER_VALUE/1024));
-        // Get the properties for BufferManager
-        return createBufferManager(bufferManager);
-    }
-    
-    static BufferManager getTestBufferManager(long bytesAvailable, int procBatchSize) {
-    	BufferManagerImpl bufferManager = new BufferManagerImpl();
-    	bufferManager.setProcessorBatchSize(procBatchSize);
-    	bufferManager.setMaxProcessingBatchColumns((int)(bytesAvailable/procBatchSize/BufferManagerImpl.KB_PER_VALUE/1024));
-    	bufferManager.setMaxReserveBatchColumns((int)(bytesAvailable/procBatchSize/BufferManagerImpl.KB_PER_VALUE/1024));
-        // Get the properties for BufferManager
-        return createBufferManager(bufferManager);
-    }
-    
-    static BufferManager createBufferManager(BufferManagerImpl bufferManager) {
-        try {
-			bufferManager.initialize();
-		} catch (TeiidComponentException e) {
-			throw new RuntimeException(e);
-		}
-
-        // Add storage managers
-        
-        bufferManager.setStorageManager(createFakeDatabaseStorageManager());
-        return bufferManager;
-    }
-    
-    
-    private static StorageManager createFakeDatabaseStorageManager() {
-        return new MemoryStorageManager();        
-    } 
-    
-}

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestAccessNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -42,7 +42,7 @@
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 
@@ -74,7 +74,7 @@
     }
     
     @Test public void testOpen_Defect16059() throws Exception {
-    	Query query = (Query)TestResolver.helpResolve("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5 AND ? IS NULL", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    	Query query = (Query)TestResolver.helpResolve("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5 AND ? IS NULL", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         IsNullCriteria nullCrit = (IsNullCriteria)((CompoundCriteria)query.getCriteria()).getCriteria(1);
         nullCrit.setExpression(new Constant(null));
         
@@ -82,7 +82,7 @@
     }
     
     @Test public void testOpen_Defect16059_2() throws Exception {
-    	Query query = (Query)TestResolver.helpResolve("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5 AND ? IS NOT NULL", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    	Query query = (Query)TestResolver.helpResolve("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5 AND ? IS NOT NULL", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         IsNullCriteria nullCrit = (IsNullCriteria)((CompoundCriteria)query.getCriteria()).getCriteria(1);
         nullCrit.setExpression(new Constant(null));
         
@@ -92,7 +92,7 @@
     @Test public void testExecCount()throws Exception{
         // Setup
         AccessNode node = new AccessNode(1);
-    	Query query = (Query)TestResolver.helpResolve("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    	Query query = (Query)TestResolver.helpResolve("SELECT e1, e2 FROM pm1.g1 WHERE e2 = 5", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         node.setCommand(query);
         CommandContext context = new CommandContext();
         context.setProcessorID("processorID"); //$NON-NLS-1$

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestBatchedUpdateNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -44,7 +44,7 @@
 import org.teiid.query.sql.lang.BatchedUpdateCommand;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 
@@ -69,7 +69,7 @@
     }
     
     private BatchedUpdateNode helpOpen(String[] commands, ProcessorDataManager pdm) throws Exception {
-        BatchedUpdateNode node = helpGetNode(commands, FakeMetadataFactory.example1Cached(), pdm);
+        BatchedUpdateNode node = helpGetNode(commands, RealMetadataFactory.example1Cached(), pdm);
         node.open();
         return node;
     }

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestGroupingNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,7 +22,7 @@
 
 package org.teiid.query.processor.relational;
 
-import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.*;
 
 import java.math.BigDecimal;
 import java.util.ArrayList;
@@ -45,15 +45,16 @@
 import org.teiid.query.processor.FakeDataManager;
 import org.teiid.query.processor.FakeTupleSource;
 import org.teiid.query.processor.ProcessorDataManager;
+import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
-
+ at SuppressWarnings("unchecked")
 public class TestGroupingNode {
 
 	public static FakeTupleSource createTupleSource1() { 
@@ -153,7 +154,7 @@
 		
 		List groupingElements = new ArrayList();
 		groupingElements.add(col1);
-		node.setGroupingElements(groupingElements);	  
+		node.setOrderBy(new OrderBy(groupingElements).getOrderByItems());
         CommandContext context = new CommandContext("pid", "test", null, null, 1);               //$NON-NLS-1$ //$NON-NLS-2$
         
         List[] expected = new List[] {
@@ -231,8 +232,6 @@
         outputElements.add(new AggregateSymbol("bigAvg", "AVG", false, bigDecimal)); //$NON-NLS-1$ //$NON-NLS-2$
         node.setElements(outputElements);
         
-        // Set grouping elements to null 
-        node.setGroupingElements(null);         
         CommandContext context = new CommandContext("pid", "test", null, null, 1);               //$NON-NLS-1$ //$NON-NLS-2$
         
         List[] data = new List[] {
@@ -272,7 +271,7 @@
         // Set grouping elements to null 
         List groupingElements = new ArrayList();
         groupingElements.add(col1); 
-        node.setGroupingElements(groupingElements);         
+        node.setOrderBy(new OrderBy(groupingElements).getOrderByItems());         
         CommandContext context = new CommandContext("pid", "test", null, null, 1);               //$NON-NLS-1$ //$NON-NLS-2$
         
         List[] data = new List[] {
@@ -308,7 +307,7 @@
         col2.setType(Integer.class);
         
         Function func = new Function("lookup", new Expression[] { new Constant("pm1.g1"), new Constant("e2"), new Constant("e1"), col2 }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, Integer.class } ); //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, Integer.class } ); //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
         func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
         
@@ -320,7 +319,7 @@
         
         List groupingElements = new ArrayList();
         groupingElements.add(col1); 
-        node.setGroupingElements(groupingElements);   
+        node.setOrderBy(new OrderBy(groupingElements).getOrderByItems());   
         CommandContext context = new CommandContext("pid", "test", null, null, 1);    //$NON-NLS-1$ //$NON-NLS-2$
         
         FakeDataManager dataMgr = new FakeDataManager();
@@ -366,7 +365,7 @@
         if (groupBy) {
             List groupingElements = new ArrayList();
             groupingElements.add(new ElementSymbol("col1")); //$NON-NLS-1$
-            node.setGroupingElements(groupingElements);
+            node.setOrderBy(new OrderBy(groupingElements).getOrderByItems());
         }
         CommandContext context = new CommandContext("pid", "test", null, null, 1);               //$NON-NLS-1$ //$NON-NLS-2$
         
@@ -434,7 +433,7 @@
         
         List groupingElements = new ArrayList();
         groupingElements.add(col1); 
-        node.setGroupingElements(groupingElements);
+        node.setOrderBy(new OrderBy(groupingElements).getOrderByItems());
 		return node;
 	}
     

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestJoinNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,6 +34,7 @@
 import org.junit.Test;
 import org.teiid.common.buffer.BlockedException;
 import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
 import org.teiid.common.buffer.TupleBatch;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
@@ -47,7 +48,7 @@
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 @SuppressWarnings("unchecked")
@@ -203,7 +204,7 @@
 
             case FUNCTION_CRITERIA :
                 Function func = new Function("lookup", new Expression[] { new Constant("pm1.g1"), new Constant("e2"), new Constant("e1"), es1 }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-                FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, Integer.class }); //$NON-NLS-1$
+                FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, Integer.class }); //$NON-NLS-1$
                 func.setFunctionDescriptor(desc);
                 func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
                 CompareCriteria joinCriteria = new CompareCriteria(es2, CompareCriteria.EQ, func);
@@ -231,7 +232,7 @@
     }
     
     public void helpTestJoinDirect(List[] expectedResults, int batchSize, int processingBytes) throws TeiidComponentException, TeiidProcessingException {
-        BufferManager mgr = NodeTestUtil.getTestBufferManager(processingBytes, batchSize);
+        BufferManager mgr = BufferManagerFactory.getTestBufferManager(processingBytes, batchSize);
         CommandContext context = new CommandContext("pid", "test", null, null, 1);               //$NON-NLS-1$ //$NON-NLS-2$
         
         join.addChild(leftNode);

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestLimitNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestLimitNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestLimitNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -239,8 +239,8 @@
         assertTrue(batch.getTerminationFlag());
     }
     
-    static List[] getRows(int rows) {
-        List[] data = new List[rows];
+    static List<?>[] getRows(int rows) {
+        List<?>[] data = new List[rows];
         for (int i = 0; i < rows; i++) {
             data[i] = Arrays.asList(new Object[] {new Integer(i+1)});
         }

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectIntoNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectIntoNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectIntoNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,6 +32,7 @@
 import org.teiid.api.exception.query.ExpressionEvaluationException;
 import org.teiid.common.buffer.BlockedException;
 import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
 import org.teiid.common.buffer.TupleBatch;
 import org.teiid.common.buffer.TupleSource;
 import org.teiid.core.TeiidComponentException;
@@ -80,7 +81,7 @@
         
         CommandContext context = new CommandContext();
         context.setProcessorID("processorID"); //$NON-NLS-1$
-        BufferManager bm = NodeTestUtil.getTestBufferManager(tupleBatchSize, tupleBatchSize);
+        BufferManager bm = BufferManagerFactory.getTestBufferManager(tupleBatchSize, tupleBatchSize);
         ProcessorDataManager dataManager = new FakePDM(tupleBatchSize);
         
         child.initialize(context, bm, dataManager);

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestProjectNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -46,7 +46,7 @@
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 
@@ -212,7 +212,7 @@
         elements.add(es1);
         
         Function func = new Function("concat", new Expression[] { es1, new Constant("abc")}); //$NON-NLS-1$ //$NON-NLS-2$
-        FunctionDescriptor fd = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("concat", new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING }); //$NON-NLS-1$
+        FunctionDescriptor fd = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("concat", new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING }); //$NON-NLS-1$
         func.setFunctionDescriptor(fd);
         func.setType(DataTypeManager.DefaultDataClasses.STRING);
         ExpressionSymbol expr = new ExpressionSymbol("expr", func); //$NON-NLS-1$
@@ -236,7 +236,7 @@
         elements.add(es1);
         
         Function func = new Function("convert", new Expression[] { es1, new Constant("integer")}); //$NON-NLS-1$ //$NON-NLS-2$
-        FunctionDescriptor fd = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("convert", new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING }); //$NON-NLS-1$
+        FunctionDescriptor fd = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("convert", new Class[] { DataTypeManager.DefaultDataClasses.STRING, DataTypeManager.DefaultDataClasses.STRING }); //$NON-NLS-1$
         func.setFunctionDescriptor(fd);
         func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
         ExpressionSymbol expr = new ExpressionSymbol("expr", func); //$NON-NLS-1$
@@ -259,7 +259,7 @@
         elements.add(es1);
 
         Function func = new Function("lookup", new Expression[] { new Constant("pm1.g1"), new Constant("e2"), new Constant("e1"), es1 }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, String.class } ); //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, String.class } ); //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
         func.setType(DataTypeManager.DefaultDataClasses.STRING);
         

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSelectNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -51,7 +51,7 @@
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.Function;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 public class TestSelectNode {
@@ -237,7 +237,7 @@
         elements.add(es1);
 
         Function func = new Function("lookup", new Expression[] { new Constant("pm1.g1"), new Constant("e2"), new Constant("e1"), es1 }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        FunctionDescriptor desc = FakeMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, Integer.class } ); //$NON-NLS-1$
+        FunctionDescriptor desc = RealMetadataFactory.SFM.getSystemFunctionLibrary().findFunction("lookup", new Class[] { String.class, String.class, String.class, Integer.class } ); //$NON-NLS-1$
         func.setFunctionDescriptor(desc);
         func.setType(DataTypeManager.DefaultDataClasses.INTEGER);
         CompareCriteria crit = new CompareCriteria(func, CompareCriteria.EQ, new Constant(new Integer(1))); 

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSortNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSortNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestSortNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -52,7 +52,7 @@
     public static final int BATCH_SIZE = 100;
     
     private void helpTestSort(List elements, List[] data, List sortElements, List sortTypes, List[] expected, Mode mode) throws TeiidComponentException, TeiidProcessingException {
-        BufferManager mgr = NodeTestUtil.getTestBufferManager(100, BATCH_SIZE, BATCH_SIZE);
+        BufferManager mgr = BufferManagerFactory.getTestBufferManager(100, BATCH_SIZE, BATCH_SIZE);
         CommandContext context = new CommandContext ("pid", "test", null, null, 1);               //$NON-NLS-1$ //$NON-NLS-2$
         
         BlockingFakeRelationalNode dataNode = new BlockingFakeRelationalNode(2, data);

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestUnionAllNode.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestUnionAllNode.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/relational/TestUnionAllNode.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -31,6 +31,7 @@
 import org.junit.Test;
 import org.teiid.common.buffer.BlockedException;
 import org.teiid.common.buffer.BufferManager;
+import org.teiid.common.buffer.BufferManagerFactory;
 import org.teiid.common.buffer.TupleBatch;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
@@ -45,7 +46,7 @@
 public class TestUnionAllNode {
 
     public void helpTestUnion(RelationalNode[] children, RelationalNode union, List[] expected) throws TeiidComponentException, TeiidProcessingException {
-        BufferManager mgr = NodeTestUtil.getTestBufferManager(1, 2);
+        BufferManager mgr = BufferManagerFactory.getTestBufferManager(1, 2);
         CommandContext context = new CommandContext("pid", "test", null, null, 1);               //$NON-NLS-1$ //$NON-NLS-2$
         FakeDataManager fdm = new FakeDataManager();
         for(int i=0; i<children.length; i++) {

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/xml/FakePlanExecutor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/xml/FakePlanExecutor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/xml/FakePlanExecutor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -56,7 +56,7 @@
         return this.currentRow;
     }
 
-    public void execute(Map values) throws TeiidComponentException, BlockedException {
+    public void execute(Map values, boolean openOnly) throws TeiidComponentException, BlockedException {
         tupleSource.openSource();
     }
 

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestInstructions.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,6 +26,8 @@
 import java.util.Arrays;
 import java.util.List;
 
+import junit.framework.TestCase;
+
 import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.common.buffer.BufferManager;
@@ -33,27 +35,16 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.mapping.xml.MappingNodeConstants;
 import org.teiid.query.mapping.xml.ResultSetInfo;
+import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.processor.FakeDataManager;
 import org.teiid.query.processor.TestProcessor;
-import org.teiid.query.processor.xml.AddNodeInstruction;
-import org.teiid.query.processor.xml.Condition;
-import org.teiid.query.processor.xml.CriteriaCondition;
-import org.teiid.query.processor.xml.EndDocumentInstruction;
-import org.teiid.query.processor.xml.ExecSqlInstruction;
-import org.teiid.query.processor.xml.IfInstruction;
-import org.teiid.query.processor.xml.InitializeDocumentInstruction;
-import org.teiid.query.processor.xml.MoveCursorInstruction;
-import org.teiid.query.processor.xml.MoveDocInstruction;
-import org.teiid.query.processor.xml.NodeDescriptor;
-import org.teiid.query.processor.xml.ProcessorInstruction;
-import org.teiid.query.processor.xml.Program;
-import org.teiid.query.processor.xml.WhileInstruction;
-import org.teiid.query.processor.xml.XMLPlan;
-import org.teiid.query.processor.xml.XMLProcessorEnvironment;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.resolver.util.ResolverVisitor;
 import org.teiid.query.rewriter.QueryRewriter;
@@ -61,17 +52,13 @@
 import org.teiid.query.sql.lang.Criteria;
 import org.teiid.query.sql.lang.QueryCommand;
 import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
-import junit.framework.TestCase;
 
-
 /**
  */
+ at SuppressWarnings("nls")
 public class TestInstructions extends TestCase {
 
     public TestInstructions(String name) {
@@ -92,43 +79,34 @@
      *     itemName (string)
      *     itemQuantity (integer)
      */
-    public FakeMetadataFacade exampleMetadata() { 
+    public QueryMetadataInterface exampleMetadata() { 
+    	MetadataStore metadataStore = new MetadataStore();
         // Create models
-        FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
-        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
+        Schema stock = RealMetadataFactory.createPhysicalModel("stock", metadataStore); //$NON-NLS-1$
+        Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore);     //$NON-NLS-1$
 
         // Create physical groups
-        FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
+        Table items = RealMetadataFactory.createPhysicalGroup("items", stock); //$NON-NLS-1$
                 
         // Create physical elements
-        List itemElements = FakeMetadataFactory.createElements(items, 
+        RealMetadataFactory.createElements(items, 
             new String[] { "itemNum", "itemName", "itemQuantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
 
         // Create virtual groups
         QueryNode rsQuery = new QueryNode("SELECT itemNum, itemName, itemQuantity FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs = FakeMetadataFactory.createVirtualGroup("xmltest.rs", xmltest, rsQuery); //$NON-NLS-1$
+        Table rs = RealMetadataFactory.createVirtualGroup("rs", xmltest, rsQuery); //$NON-NLS-1$
 
         // Create virtual elements
-        List rsElements = FakeMetadataFactory.createElements(rs, 
+        RealMetadataFactory.createElements(rs, 
             new String[] { "itemNum", "itemName", "itemQuantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });        
             
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(stock);
-        store.addObject(items);
-        store.addObjects(itemElements);
-
-        store.addObject(xmltest);
-        store.addObject(rs);
-        store.addObjects(rsElements);
-                        
         // Create the facade from the store
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
     }
     
-    private Command helpGetCommand(String sql, FakeMetadataFacade metadata) throws TeiidComponentException, TeiidProcessingException {
+    private Command helpGetCommand(String sql, QueryMetadataInterface metadata) throws TeiidComponentException, TeiidProcessingException {
         // parse
         QueryParser parser = new QueryParser();
         Command command = parser.parseCommand(sql);
@@ -139,7 +117,7 @@
         return command;        
     }
 
-    private Criteria helpGetCriteria(String sql, FakeMetadataFacade metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
+    private Criteria helpGetCriteria(String sql, QueryMetadataInterface metadata) throws QueryParserException, QueryResolverException, TeiidComponentException {
         QueryParser parser = new QueryParser();
         Criteria crit = parser.parseCriteria(sql);
    
@@ -154,7 +132,7 @@
     	TestProcessor.doProcess(plan, new FakeDataManager(), new List[] {Arrays.asList(expected)}, new CommandContext());
     }
     
-    public Program exampleProgram(FakeMetadataFacade metadata, XMLProcessorEnvironment env) throws Exception{
+    public Program exampleProgram() throws Exception{
 
         ProcessorInstruction i0 = new InitializeDocumentInstruction("UTF-8", true);         //$NON-NLS-1$
         NodeDescriptor descriptor = NodeDescriptor.createNodeDescriptor("Catalogs", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
@@ -223,7 +201,7 @@
         return program;        
     }
 
-    public Program exampleProgram2(Criteria crit, FakeMetadataFacade metadata, XMLProcessorEnvironment env) throws Exception{
+    public Program exampleProgram2(Criteria crit) throws Exception{
         ProcessorInstruction i0 = new InitializeDocumentInstruction("UTF-8", true);         //$NON-NLS-1$
         NodeDescriptor descriptor = NodeDescriptor.createNodeDescriptor("Catalogs", null, AddNodeInstruction.ELEMENT, null, null, null,false, null, MappingNodeConstants.NORMALIZE_TEXT_PRESERVE);//$NON-NLS-1$
         ProcessorInstruction i1 = new AddNodeInstruction(descriptor);
@@ -304,18 +282,18 @@
     
             
     public void testProcess1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata();
+        QueryMetadataInterface metadata = exampleMetadata();
         String resultSetName = "xmltest.rs"; //$NON-NLS-1$
         
         FakeXMLProcessorEnvironment env = new FakeXMLProcessorEnvironment();
-        Program program = exampleProgram(metadata, env);
+        Program program = exampleProgram();
         
         BufferManager bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
         XMLPlan temp = new XMLPlan(env);
         CommandContext context = new CommandContext("pid", null, null, null, 1); //$NON-NLS-1$
         temp.initialize(context,null,bufferMgr);
 
-        List schema = new ArrayList();
+        List<ElementSymbol> schema = new ArrayList<ElementSymbol>();
         schema.add(new ElementSymbol(resultSetName + ElementSymbol.SEPARATOR + "itemNum")); //$NON-NLS-1$
         schema.add(new ElementSymbol(resultSetName + ElementSymbol.SEPARATOR + "itemName")); //$NON-NLS-1$
         schema.add(new ElementSymbol(resultSetName + ElementSymbol.SEPARATOR + "itemQuantity")); //$NON-NLS-1$
@@ -348,7 +326,7 @@
     }
     
     public void testProcess2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata();
+        QueryMetadataInterface metadata = exampleMetadata();
 
         String resultSetName = "xmltest.rs"; //$NON-NLS-1$
         
@@ -357,7 +335,7 @@
         
         Criteria crit = helpGetCriteria("xmltest.rs.itemName = 'Screwdriver'", metadata);  //$NON-NLS-1$ 
         FakeXMLProcessorEnvironment env = new FakeXMLProcessorEnvironment();
-        Program program = exampleProgram2(crit, metadata, env);
+        Program program = exampleProgram2(crit);
                 
         BufferManager bufferMgr = BufferManagerFactory.getStandaloneBufferManager();
         XMLPlan temp = new XMLPlan(env);

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestProcessorEnvironment.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestProcessorEnvironment.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestProcessorEnvironment.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -119,31 +119,31 @@
         env.pushProgram(p1, true); //simulate recursion
         
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i1, env.getCurrentInstruction());
+        assertEquals(i1, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i1.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i2, env.getCurrentInstruction());
+        assertEquals(i2, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i2.process(env, context);
         assertEquals(p2, env.getCurrentProgram());
-        assertEquals(i3, env.getCurrentInstruction());
+        assertEquals(i3, env.getCurrentInstruction(null));
         assertEquals(p2, env.getCurrentProgram());
         i3.process(env, context);
         assertEquals(p2, env.getCurrentProgram());
-        assertEquals(i4, env.getCurrentInstruction());
+        assertEquals(i4, env.getCurrentInstruction(null));
         assertEquals(p2, env.getCurrentProgram());
         i4.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i1, env.getCurrentInstruction());
+        assertEquals(i1, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i1.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i2, env.getCurrentInstruction());
+        assertEquals(i2, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i2.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(null, env.getCurrentInstruction());
+        assertEquals(null, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
     }
     
@@ -173,31 +173,31 @@
         env.pushProgram(p2);
         
         assertEquals(p2, env.getCurrentProgram());
-        assertEquals(i3, env.getCurrentInstruction());
+        assertEquals(i3, env.getCurrentInstruction(null));
         assertEquals(p2, env.getCurrentProgram());
         i3.process(env, context);
         assertEquals(p2, env.getCurrentProgram());
-        assertEquals(i4, env.getCurrentInstruction());
+        assertEquals(i4, env.getCurrentInstruction(null));
         assertEquals(p2, env.getCurrentProgram());
         i4.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i1, env.getCurrentInstruction());
+        assertEquals(i1, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i1.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i2, env.getCurrentInstruction());
+        assertEquals(i2, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i2.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i1, env.getCurrentInstruction());
+        assertEquals(i1, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i1.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(i2, env.getCurrentInstruction());
+        assertEquals(i2, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
         i2.process(env, context);
         assertEquals(p1, env.getCurrentProgram());
-        assertEquals(null, env.getCurrentInstruction());
+        assertEquals(null, env.getCurrentInstruction(null));
         assertEquals(p1, env.getCurrentProgram());
     }    
     

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestSourceNodeGenaratorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -82,7 +82,7 @@
         MappingSourceNode source = (MappingSourceNode)root;
         assertEquals("licenseSource", source.getResultName()); //$NON-NLS-1$
         
-        List list = source.getStagingTables();
+        List<String> list = source.getStagingTables();
         assertEquals(2, list.size());
 
         assertEquals("testTempGroup1", list.get(0)); //$NON-NLS-1$
@@ -128,7 +128,7 @@
         assertTrue(node instanceof MappingElement);
         MappingElement element = (MappingElement)node;
 
-        List list = element.getStagingTables();
+        List<String> list = element.getStagingTables();
         assertEquals(1, list.size());
         assertEquals("testTempGroup1", list.get(0)); //$NON-NLS-1$
         
@@ -137,7 +137,7 @@
         assertEquals(1, element.getMinOccurence());
         assertEquals(1, element.getMaxOccurence());
         
-        MappingNode node1 = (MappingNode)element.getNodeChildren().get(0);
+        MappingNode node1 = element.getNodeChildren().get(0);
         assertTrue(node1 instanceof MappingSourceNode);
         
         MappingSourceNode source = (MappingSourceNode)node1;        
@@ -149,7 +149,7 @@
         
         // make sure source's child is mapping element and mapping element's source
         // is above source        
-        node1 = (MappingNode)source.getNodeChildren().get(0);
+        node1 = source.getNodeChildren().get(0);
         assertTrue(node instanceof MappingElement);
         element = (MappingElement)node1;
         assertEquals("childNode", element.getName()); //$NON-NLS-1$
@@ -194,14 +194,14 @@
         MappingSourceNode source = (MappingSourceNode)node;
         assertEquals("parentNodeSource", source.getSource()); //$NON-NLS-1$
         
-        node = (MappingNode)source.getNodeChildren().get(0);
+        node = source.getNodeChildren().get(0);
         assertTrue(node instanceof MappingElement);        
         MappingElement element = (MappingElement)node;
         assertEquals("parentNode", element.getName()); //$NON-NLS-1$
         assertTrue(element.isRootRecursiveNode());
         assertFalse(element.isRecursive());
         
-        node = (MappingNode)element.getNodeChildren().get(0);
+        node = element.getNodeChildren().get(0);
         assertTrue(node instanceof MappingElement);        
         element = (MappingElement)node;
         assertEquals("childNode", element.getName()); //$NON-NLS-1$
@@ -213,7 +213,7 @@
         assertEquals("ddd", attribute.getDefaultValue()); //$NON-NLS-1$
         assertEquals("fff", attribute.getValue()); //$NON-NLS-1$
         
-        node = (MappingNode)element.getNodeChildren().get(0);
+        node = element.getNodeChildren().get(0);
         assertTrue(node instanceof MappingRecursiveElement);        
         MappingRecursiveElement recursive = (MappingRecursiveElement)node;
         assertEquals("recursivenodename", recursive.getName()); //$NON-NLS-1$
@@ -254,7 +254,7 @@
         assertEquals("parentSource", source.getSource()); //$NON-NLS-1$
         
         // parent element
-        node = (MappingNode)source.getNodeChildren().get(0);
+        node = source.getNodeChildren().get(0);
         assertTrue(node instanceof MappingElement);        
         MappingElement element = (MappingElement)node;
         assertEquals("parentNode", element.getName()); //$NON-NLS-1$
@@ -262,12 +262,12 @@
         assertFalse(element.isRecursive());
         
         // recursive source
-        node = (MappingNode)element.getNodeChildren().get(0);
+        node = element.getNodeChildren().get(0);
         source = (MappingSourceNode)node;
         assertEquals("childSource", source.getSource()); //$NON-NLS-1$
         assertEquals("parentSource", source.getAliasResultName()); //$NON-NLS-1$
         
-        node = (MappingNode)source.getNodeChildren().get(0);
+        node = source.getNodeChildren().get(0);
         assertTrue(node instanceof MappingRecursiveElement);        
         MappingRecursiveElement relement = (MappingRecursiveElement)node;
         

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLPlanningEnhancements.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,62 +28,58 @@
 import java.util.List;
 import java.util.Map;
 
+import org.junit.Ignore;
 import org.junit.Test;
 import org.teiid.client.metadata.ParameterInfo;
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.mapping.xml.MappingAttribute;
 import org.teiid.query.mapping.xml.MappingDocument;
 import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.mapping.xml.MappingNode;
+import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.TestOptimizer;
 import org.teiid.query.optimizer.relational.rules.RuleChooseDependent;
 import org.teiid.query.processor.FakeDataManager;
 import org.teiid.query.processor.ProcessorPlan;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 
-
+ at SuppressWarnings("nls")
 public class TestXMLPlanningEnhancements {
 
-    private FakeMetadataFacade getMetadata(String query) {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata();
+    private TransformationMetadata getMetadata(String query) {
+    	TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
         
-        FakeMetadataStore store = metadata.getStore();
+        Schema xmltest = metadata.getMetadataStore().getSchemas().get("XMLTEST");
         
-        FakeMetadataObject xmltest = store.findObject("xmltest", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
         QueryNode rsQueryY = new QueryNode(query); //$NON-NLS-1$
         rsQueryY.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
         rsQueryY.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-        FakeMetadataObject rsQY = FakeMetadataFactory.createVirtualGroup("xmltest.suppliersY", xmltest, rsQueryY); //$NON-NLS-1$
+        Table rsQY = RealMetadataFactory.createVirtualGroup("suppliersY", xmltest, rsQueryY); //$NON-NLS-1$
         
-        List rsElementsY = FakeMetadataFactory.createElements(rsQY, 
+        RealMetadataFactory.createElements(rsQY, 
                                                               new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                                                               new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
                                                          
-        FakeMetadataObject doc18a = FakeMetadataFactory.createVirtualGroup("xmltest.doc18a", xmltest, TestXMLProcessor.createXMLPlanNested("xmltest.suppliersY")); //$NON-NLS-1$ //$NON-NLS-2$
-        List docE18a = FakeMetadataFactory.createElements(doc18a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+        Table doc18a = RealMetadataFactory.createXmlDocument("doc18a", xmltest, TestXMLProcessor.createXMLPlanNested("xmltest.suppliersY")); //$NON-NLS-1$ //$NON-NLS-2$
+        RealMetadataFactory.createElements(doc18a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        store.addObject(rsQY);
-        store.addObjects(rsElementsY);
-        store.addObject(doc18a);
-        store.addObjects(docE18a);
         return metadata;
     }
     
-    private FakeMetadataFacade getTempTableMetadata(boolean simpleTempSelect) {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata();
+    private TransformationMetadata getTempTableMetadata(boolean simpleTempSelect) {
+        TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
         
-        FakeMetadataStore store = metadata.getStore();
+        Schema xmltest = metadata.getMetadataStore().getSchemas().get("XMLTEST");
         
-        FakeMetadataObject xmltest = store.findObject("xmltest", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject docJoin = FakeMetadataFactory.createVirtualGroup("xmltest.docJoin", xmltest, createXMLPlanNestedJoin()); //$NON-NLS-1$
-        List docEJoin = FakeMetadataFactory.createElements(docJoin, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-!
 NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
+        Table docJoin = RealMetadataFactory.createXmlDocument("docJoin", xmltest, createXMLPlanNestedJoin()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(docJoin, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NL!
 S-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
         QueryNode tempQueryJoin = null;
@@ -93,44 +89,37 @@
             tempQueryJoin = new QueryNode("SELECT stock.orders.* FROM stock.orders join stock.suppliers on stock.orders.supplierFK=stock.suppliers.supplierNum"); //$NON-NLS-1$ //$NON-NLS-2$
         }
 
-        FakeMetadataObject tempJoin = FakeMetadataFactory.createVirtualGroup("tempGroup.orders", xmltest, tempQueryJoin); //$NON-NLS-1$
+        Table tempJoin = RealMetadataFactory.createXmlStagingTable("docJoin.orders", xmltest, tempQueryJoin); //$NON-NLS-1$
 
         // Created virtual group w/ nested result set & binding - selects from 2nd temp root group
         QueryNode rsQueryJoin = null;
         if (!simpleTempSelect) {
-            rsQueryJoin = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders join stock.suppliers on tempGroup.orders.supplierFK=stock.suppliers.supplierNum WHERE itemFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+            rsQueryJoin = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM docJoin.orders join stock.suppliers on docJoin.orders.supplierFK=stock.suppliers.supplierNum WHERE itemFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
             rsQueryJoin.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
             rsQueryJoin.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
         } else {
-            rsQueryJoin = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders WHERE supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+            rsQueryJoin = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM docJoin.orders WHERE supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
             rsQueryJoin.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
         }
-        FakeMetadataObject rsJoin = FakeMetadataFactory.createVirtualGroup("xmltest.ordersC", xmltest, rsQueryJoin); //$NON-NLS-1$
+        Table rsJoin = RealMetadataFactory.createVirtualGroup("ordersC", xmltest, rsQueryJoin); //$NON-NLS-1$
         
-        List tempJoinElements = FakeMetadataFactory.createElements(tempJoin, 
+        RealMetadataFactory.createElements(tempJoin, 
                                                                    new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
                                                                    new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElementsJoin = FakeMetadataFactory.createElements(rsJoin, 
+        RealMetadataFactory.createElements(rsJoin, 
                                                                  new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                                                                  new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-        store.addObject(docJoin);
-        store.addObjects(docEJoin);
-        store.addObjects(tempJoinElements);
-        store.addObjects(rsElementsJoin);        
-        store.addObject(tempJoin);
-        store.addObject(rsJoin);
-        
         return metadata;
     }
     
-    private static MappingNode createXMLPlanNestedJoin() {
+    private static MappingDocument createXMLPlanNestedJoin() {
         
         MappingDocument doc = new MappingDocument(true);
         
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
 
-        root.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders"})); //$NON-NLS-1$ 
+        root.setStagingTables(Arrays.asList("xmltest.docJoin.orders")); //$NON-NLS-1$ 
         
         MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
         MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
@@ -166,9 +155,18 @@
         return doc;  
     } 
     
+    @Test public void testThreeWayOrWithNestedSiblings() throws Exception {
+    	QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataNestedWithSibling();
+    	FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNestedWithSibling(metadata);
+    	String resultFile = "TestXMLPlanningEnhancements-testThreeWayOrWithNestedSiblings.xml"; //$NON-NLS-1$
+        String expectedDoc = TestXMLProcessor.readFile(resultFile);
+        
+        TestXMLProcessor.helpTestProcess("select * from xmltest.doc9c where itemid='003' or supplierid = '600' or orderid = '1'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+    } 
+    
     @Test public void testBaseballPlayersDocDefect19541() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerCase3225(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -216,7 +214,7 @@
     }   
     
     @Test public void testNested2WithContextCriteria5c() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5c.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
@@ -225,7 +223,7 @@
     }
     
     @Test public void testNested2WithContextCriteria5d() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
@@ -234,7 +232,7 @@
     }
 
     @Test public void testNested2WithContextCriteria5d1() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5d.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
@@ -243,7 +241,7 @@
     }
 
     @Test public void testNested2WithContextCriteria5e() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String resultFile = "TestXMLProcessor-testNested2WithContextCriteria5e.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
@@ -252,7 +250,7 @@
     }
     
     @Test public void testXQTChoice_6796() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata2();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata2();
         FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
         String resultFile = "TestXMLProcessor-testXQTChoice_6796.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
@@ -261,7 +259,7 @@
     }
     
     @Test public void testOrderByWithChoiceCriteriaElement() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata2();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata2();
         FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
         String expectedDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n   <wrapper/>\n   <wrapper/>\n   <wrapper/>\n   <wrapper/>\n   <wrapper/>\n   <wrapper/>\n   <wrapper/>\n   <wrapper/>\n   <wrapper/>\n</root>"; //$NON-NLS-1$
         
@@ -269,7 +267,7 @@
     }
     
     @Test public void testXQTChoice_withContextCriteria() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata2();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata2();
         FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
         String resultFile = "TestXMLProcessor-testXQTChoice_withContextCriteria.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
@@ -278,7 +276,7 @@
     }
     
     @Test public void testXQTChoice_withContextCriteria1() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata2();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadata2();
         FakeDataManager dataMgr = TestXMLProcessor.exampleXQTDataManager(metadata);
         String resultFile = "TestXMLProcessor-testXQTChoice_withContextCriteria1.xml"; //$NON-NLS-1$
         String expectedDoc = TestXMLProcessor.readFile(resultFile);
@@ -287,7 +285,7 @@
     }
     
     @Test public void testMappingClassWithInlineViewAndCriteria() throws Exception {
-        FakeMetadataFacade metadata = getMetadata("SELECT upper(x.supplierNum) as supplierNum, x.supplierName, x.supplierZipCode from (select stock.suppliers.supplierNum, supplierName, supplierZipCode, itemNum FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum) x where x.itemNum = ?"); //$NON-NLS-1$
+        QueryMetadataInterface metadata = getMetadata("SELECT upper(x.supplierNum) as supplierNum, x.supplierName, x.supplierZipCode from (select stock.suppliers.supplierNum, supplierName, supplierZipCode, itemNum FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum) x where x.itemNum = ?"); //$NON-NLS-1$
 
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$ 
@@ -296,7 +294,7 @@
     }
     
     @Test public void testMappingClassWithUnionAndCriteria() throws Exception {
-        FakeMetadataFacade metadata = getMetadata("SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ? union all SELECT concat(stock.suppliers.supplierNum, '1'), supplierName, convert(12345, string) FROM stock.suppliers WHERE stock.suppliers.supplierNum = ?"); //$NON-NLS-1$
+        QueryMetadataInterface metadata = getMetadata("SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ? union all SELECT concat(stock.suppliers.supplierNum, '1'), supplierName, convert(12345, string) FROM stock.suppliers WHERE stock.suppliers.supplierNum = ?"); //$NON-NLS-1$
 
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$ 
@@ -305,27 +303,26 @@
     }
     
     @Test public void testMappingClassWithInputSetElementNameConflict() throws Exception {
-        FakeMetadataFacade metadata = getMetadata("SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.supplierNum = ?"); //$NON-NLS-1$
+        QueryMetadataInterface metadata = getMetadata("SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.supplierNum = ?"); //$NON-NLS-1$
 
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Catalogs>\n<Catalog>\n<Items/>\n</Catalog>\n</Catalogs>"; //$NON-NLS-1$ 
         TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc18a where supplierID<56", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
     }
     
+    @Ignore("Will plan with a dependent join")
     @Test public void testAutoStagingFailsForMappingClassWithProcRelational() throws Exception {
-        FakeMetadataFacade metadata = getMetadata("SELECT supplierNum, supplierName, supplierZipCode FROM v1.supplierProc where itemnum = ?"); //$NON-NLS-1$
+        TransformationMetadata metadata = getMetadata("SELECT supplierNum, supplierName, supplierZipCode FROM v1.supplierProc where itemnum = ?"); //$NON-NLS-1$
 
-        FakeMetadataObject v1 = FakeMetadataFactory.createVirtualModel("v1"); //$NON-NLS-1$
+        Schema v1 = RealMetadataFactory.createVirtualModel("v1", metadata.getMetadataStore()); //$NON-NLS-1$
         
-        FakeMetadataObject rs1 = FakeMetadataFactory.createResultSet("v1.rs1", v1, new String[] {"supplierNum", "supplierName", "supplierZipCode"}, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING,DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        ColumnSet<Procedure> rs1 = RealMetadataFactory.createResultSet("v1.rs1", new String[] {"supplierNum", "supplierName", "supplierZipCode"}, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING,DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
         
-        FakeMetadataObject rs1p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
-        FakeMetadataObject rs1p2 = FakeMetadataFactory.createParameter("itemNum", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        ProcedureParameter rs1p2 = RealMetadataFactory.createParameter("itemNum", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
         QueryNode n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = v1.supplierProc.itemNum; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vt1 = FakeMetadataFactory.createVirtualProcedure("v1.supplierProc", v1, Arrays.asList(new FakeMetadataObject[] { rs1p1, rs1p2 }), n1); //$NON-NLS-1$
-
-        metadata.getStore().addObject(vt1);
-
+        Procedure vt1 = RealMetadataFactory.createVirtualProcedure("supplierProc", v1, Arrays.asList(rs1p2), n1); //$NON-NLS-1$
+        vt1.setResultSet(rs1);
+        
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$ 
  
@@ -336,7 +333,7 @@
     }
     
     @Test public void testMappingClassWitSelectDistinctAndCriteria() throws Exception {
-        FakeMetadataFacade metadata = getMetadata("SELECT distinct '1' as supplierNum, '2' as supplierName, '3' as supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum like substring(?,1,1) || '%'"); //$NON-NLS-1$
+        QueryMetadataInterface metadata = getMetadata("SELECT distinct '1' as supplierNum, '2' as supplierName, '3' as supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum like substring(?,1,1) || '%'"); //$NON-NLS-1$
 
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
 
@@ -352,7 +349,7 @@
      * be used as inputs
      */
     @Test public void testMappingClassWithStoredProcedureAndCriteria() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testMappingClassWithStoredProcedureAndCriteria.xml"); //$NON-NLS-1$ 
         
@@ -360,7 +357,7 @@
     }
     
     public void defer_testXMLQueryWithFalseRootCriteria() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
         String expectedDoc = ""; //$NON-NLS-1$ 
         
@@ -371,13 +368,13 @@
      * @see #testNested2WithCriteria2
      */
     @Test public void testAutoStagingByCosting() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata();
+        TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-        FakeMetadataObject suppliers = metadata.getStore().findObject("stock.suppliers", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        FakeMetadataObject itemSuppliers = metadata.getStore().findObject("stock.item_supplier", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        Table suppliers = metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+        Table itemSuppliers = metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
 
-        suppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
-        itemSuppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
+        suppliers.setCardinality(10);
+        itemSuppliers.setCardinality(10);
 
         String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
         
@@ -391,14 +388,15 @@
     /**
      * @see #testNested2WithCriteria2
      */
+    @Ignore("Will use a dependent join instead")
     @Test public void testAutoStagingFailsByCosting() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata();
+        TransformationMetadata metadata = TestXMLProcessor.exampleMetadata();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-        FakeMetadataObject suppliers = metadata.getStore().findObject("stock.suppliers", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        FakeMetadataObject itemSuppliers = metadata.getStore().findObject("stock.item_supplier", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        Table suppliers = metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+        Table itemSuppliers = metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
 
-        suppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10000));
-        itemSuppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10000));
+        suppliers.setCardinality(10000);
+        itemSuppliers.setCardinality(10000);
 
         String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
         
@@ -409,8 +407,9 @@
         assertNull(stats.get(ExecStagingTableInstruction.class));
     }
 
+    @Ignore("Will use dependent join instead")
     @Test public void testAutoStagingFailsByNoCache() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
 
         String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
@@ -422,8 +421,9 @@
         assertNull(stats.get(ExecStagingTableInstruction.class));
     }    
     
+    @Ignore("Will use dependent join")
     @Test public void testAutoStagingFailsByNoCacheByGroup() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadataCached();
+        QueryMetadataInterface metadata = TestXMLProcessor.exampleMetadataCached();
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
 
         String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
@@ -443,7 +443,7 @@
     
     // see the next test with costing information too.
     @Test public void testUseOfStagingCardinalityOnDependentJoinsNoCost() throws Exception {
-        FakeMetadataFacade metadata = getTempTableMetadata(false);
+        QueryMetadataInterface metadata = getTempTableMetadata(false);
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
 
         String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
@@ -477,15 +477,15 @@
     }    
     
     @Test public void testUseOfStagingCardinalityOnDependentJoinsWithCost() throws Exception {
-        FakeMetadataFacade metadata = getTempTableMetadata(false);
+        TransformationMetadata metadata = getTempTableMetadata(false);
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-        FakeMetadataObject orders = metadata.getStore().findObject("stock.orders", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        FakeMetadataObject suppliers = metadata.getStore().findObject("stock.suppliers", FakeMetadataObject.GROUP); //$NON-NLS-1$
 
-        // supply the costing information for OrdersC
-        orders.putProperty(FakeMetadataObject.Props.CARDINALITY, BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE - 1);
-        suppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1);        
+        Table orders = metadata.getGroupID("stock.orders"); //$NON-NLS-1$
+        Table suppliers = metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
 
+        orders.setCardinality(BufferManager.DEFAULT_PROCESSOR_BATCH_SIZE - 1);
+        suppliers.setCardinality(RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1);
+        
         String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-FullSuppliers.xml"); //$NON-NLS-1$
         
         XMLPlan xmlPlan = (XMLPlan)TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.docJoin", metadata, dataMgr, null, TestOptimizer.getGenericFinder(false), expectedDoc); //$NON-NLS-1$        
@@ -516,13 +516,14 @@
     } 
     
     @Test public void testNoRedundentStagingTables() throws Exception {
-        FakeMetadataFacade metadata = getTempTableMetadata(true);
+        TransformationMetadata metadata = getTempTableMetadata(true);
         FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-        FakeMetadataObject suppliers = metadata.getStore().findObject("stock.suppliers", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        FakeMetadataObject orders = metadata.getStore().findObject("stock.orders", FakeMetadataObject.GROUP); //$NON-NLS-1$
+        
+        Table suppliers = metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
+        Table orders = metadata.getGroupID("stock.orders"); //$NON-NLS-1$
 
-        suppliers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
-        orders.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
+        suppliers.setCardinality(10);
+        orders.setCardinality(10);
 
         String expectedDoc = TestXMLProcessor.readFile("TestXMLProcessor-OnlySupplier51.xml"); //$NON-NLS-1$
         
@@ -532,20 +533,4 @@
         assertEquals(4, ((List)stats.get(ExecStagingTableInstruction.class)).size());
     }
     
-    @Test public void testEmptyMappingClass() throws Exception {
-        FakeMetadataFacade metadata = TestXMLProcessor.exampleMetadata();
-        FakeDataManager dataMgr = TestXMLProcessor.exampleDataManagerNested(metadata);
-        FakeMetadataObject suppliers = metadata.getStore().findObject("xmltest.suppliers", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        QueryNode node = (QueryNode)suppliers.getProperty(FakeMetadataObject.Props.PLAN);
-        node.setQuery(null);
-        
-        FakeMetadataObject docGroup = metadata.getStore().findObject("xmltest.doc9", FakeMetadataObject.GROUP); //$NON-NLS-1$
-        MappingDocument doc = (MappingDocument)docGroup.getProperty(FakeMetadataObject.Props.PLAN);
-        MappingNode suppliersNode = MappingNode.findNode(doc, "Catalogs.Catalog.Items.Item.Suppliers.Supplier".toUpperCase());
-        suppliersNode.setExclude(true);
-        
-        String expectedDoc = TestXMLProcessor.readFile("TestXMLPlanningEnhancements-testEmptyMappingClass.xml"); //$NON-NLS-1$
-        
-        TestXMLProcessor.helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
-    }
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/processor/xml/TestXMLProcessor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,20 +26,27 @@
 
 import java.io.ByteArrayOutputStream;
 import java.io.FileInputStream;
-import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 
 import org.junit.Test;
 import org.teiid.api.exception.query.QueryPlannerException;
+import org.teiid.api.exception.query.QueryResolverException;
 import org.teiid.client.metadata.ParameterInfo;
 import org.teiid.common.buffer.BufferManager;
 import org.teiid.common.buffer.BufferManagerFactory;
 import org.teiid.core.TeiidComponentException;
+import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidProcessingException;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.util.UnitTestUtil;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.mapping.xml.MappingAttribute;
@@ -48,7 +55,6 @@
 import org.teiid.query.mapping.xml.MappingCriteriaNode;
 import org.teiid.query.mapping.xml.MappingDocument;
 import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.mapping.xml.MappingNode;
 import org.teiid.query.mapping.xml.MappingNodeConstants;
 import org.teiid.query.mapping.xml.MappingRecursiveElement;
 import org.teiid.query.mapping.xml.MappingSequenceNode;
@@ -56,6 +62,7 @@
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.QueryOptimizer;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.CapabilitiesFinder;
@@ -71,11 +78,7 @@
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.rewriter.QueryRewriter;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 
 
@@ -87,7 +90,59 @@
  */
 @SuppressWarnings("nls")
 public class TestXMLProcessor {
-    private static final boolean DEBUG = false;
+    private static final String CARDS_MANAGER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
+	            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
+	            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
+	            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
+	            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
+	            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+	            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+	            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+	            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+	            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+	            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+	            "         </Owner>\r\n" + //$NON-NLS-1$
+	            "      </Manager>\r\n" + //$NON-NLS-1$
+	            "   </Player>\r\n" + //$NON-NLS-1$
+	            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
+	            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
+	            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
+	            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+	            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+	            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+	            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+	            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+	            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+	            "         </Owner>\r\n" + //$NON-NLS-1$
+	            "      </Manager>\r\n" + //$NON-NLS-1$
+	            "   </Player>\r\n" + //$NON-NLS-1$
+	            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
+	            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
+	            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
+	            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
+	            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
+	            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
+	            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
+	            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
+	            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
+	            "         </Owner>\r\n" + //$NON-NLS-1$
+	            "      </Manager>\r\n" + //$NON-NLS-1$
+	            "   </Player>\r\n" + //$NON-NLS-1$
+	            "   <Player PlayerID=\"1005\">\r\n" + //$NON-NLS-1$
+	            "      <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
+	            "      <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
+	            "   </Player>\r\n" + //$NON-NLS-1$
+	            "   <Player PlayerID=\"1006\">\r\n" + //$NON-NLS-1$
+	            "      <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
+	            "      <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
+	            "   </Player>\r\n" + //$NON-NLS-1$
+	            "   <Player PlayerID=\"1008\">\r\n" + //$NON-NLS-1$
+	            "      <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
+	            "      <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
+	            "   </Player>\r\n" + //$NON-NLS-1$
+	            "</BaseballPlayers>\r\n\r\n";
+
+	private static final boolean DEBUG = false;
     
     /**
      * Construct some fake metadata.  Basic conceptual tree is:
@@ -103,47 +158,46 @@
      *     itemName (string)
      *     itemQuantity (integer)
      */
-    public static FakeMetadataFacade exampleMetadataCached() {
+    public static TransformationMetadata exampleMetadataCached() {
         return EXAMPLE_CACHED;
     } 
     
-    private static final FakeMetadataFacade EXAMPLE_CACHED = exampleMetadata();
+    private static final TransformationMetadata EXAMPLE_CACHED = exampleMetadata();
     
-    public static FakeMetadataFacade exampleMetadata() {
-        FakeMetadataStore store = new FakeMetadataStore();
-        FakeMetadataFacade facade = new FakeMetadataFacade(store);
+    public static TransformationMetadata exampleMetadata() {
+        MetadataStore metadataStore = new MetadataStore();
         
         // Create models
-        FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
-        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
+        Schema stock = RealMetadataFactory.createPhysicalModel("stock", metadataStore); //$NON-NLS-1$
+        Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore);     //$NON-NLS-1$
 
         // Create physical groups
-        FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
-        FakeMetadataObject item_supplier = FakeMetadataFactory.createPhysicalGroup("stock.item_supplier", stock); //$NON-NLS-1$
+        Table items = RealMetadataFactory.createPhysicalGroup("items", stock); //$NON-NLS-1$
+        Table item_supplier = RealMetadataFactory.createPhysicalGroup("item_supplier", stock); //$NON-NLS-1$
 
-        FakeMetadataObject suppliers = FakeMetadataFactory.createPhysicalGroup("stock.suppliers", stock); //$NON-NLS-1$
-        FakeMetadataObject orders = FakeMetadataFactory.createPhysicalGroup("stock.orders", stock); //$NON-NLS-1$
-        FakeMetadataObject employees = FakeMetadataFactory.createPhysicalGroup("stock.employees", stock); //$NON-NLS-1$
+        Table suppliers = RealMetadataFactory.createPhysicalGroup("suppliers", stock); //$NON-NLS-1$
+        Table orders = RealMetadataFactory.createPhysicalGroup("orders", stock); //$NON-NLS-1$
+        Table employees = RealMetadataFactory.createPhysicalGroup("employees", stock); //$NON-NLS-1$
              
         // Create physical elements
-        List itemElements = FakeMetadataFactory.createElements(items, 
+        RealMetadataFactory.createElements(items, 
             new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
         //many-to-many join table
-        List itemSupplierElements = FakeMetadataFactory.createElements(item_supplier, 
+        RealMetadataFactory.createElements(item_supplier, 
             new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 
-        List supplierElements = FakeMetadataFactory.createElements(suppliers, 
+        RealMetadataFactory.createElements(suppliers, 
             new String[] { "supplierNum", "supplierName", "supplierZipCode"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        List stockOrders = FakeMetadataFactory.createElements(orders, 
+        RealMetadataFactory.createElements(orders, 
             new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List supplierEmployees = FakeMetadataFactory.createElements(employees, 
+        RealMetadataFactory.createElements(employees, 
             new String[] { "employeeNum", "supplierNumFK", "supervisorNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
@@ -154,43 +208,43 @@
         // Create virtual groups
         // per defect 6829 - intentionally including the reserved word "group" as part of this virtual group name
         QueryNode rsQuery = new QueryNode("SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs = FakeMetadataFactory.createVirtualGroup("xmltest.group.items", xmltest, rsQuery); //$NON-NLS-1$
+        Table rs = RealMetadataFactory.createVirtualGroup("group.items", xmltest, rsQuery); //$NON-NLS-1$
 
         // Created 2nd virtual group w/ nested result set & binding
         QueryNode rsQuery2 = new QueryNode("SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = input.x"); //$NON-NLS-1$ //$NON-NLS-2$
         //QueryNode rsQuery2 = new QueryNode("xmltest.suppliers", "SELECT stock.suppliers.supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?");
         rsQuery2.addBinding("xmltest.group.items.itemNum as x"); //$NON-NLS-1$
-        FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xmltest.suppliers", xmltest, rsQuery2); //$NON-NLS-1$
+        Table rs2 = RealMetadataFactory.createVirtualGroup("suppliers", xmltest, rsQuery2); //$NON-NLS-1$
 
         // Created virtual group w/ nested result set & binding
         QueryNode rsQuery3 = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM stock.orders WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery3.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
         rsQuery3.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
         rsQuery3.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
-        FakeMetadataObject rs3 = FakeMetadataFactory.createVirtualGroup("xmltest.orders", xmltest, rsQuery3); //$NON-NLS-1$
+        Table rs3 = RealMetadataFactory.createVirtualGroup("orders", xmltest, rsQuery3); //$NON-NLS-1$
 
 
 // ======================================================================================================================
 
         //create employees - not connected to any of the above
         QueryNode rsEmployees = new QueryNode("SELECT employeeNum, firstName, lastName FROM stock.employees WHERE supervisorNum IS NULL"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs4 = FakeMetadataFactory.createVirtualGroup("xmltest.employees", xmltest, rsEmployees); //$NON-NLS-1$
+        Table rs4 = RealMetadataFactory.createVirtualGroup("employees", xmltest, rsEmployees); //$NON-NLS-1$
 
         //recursive piece
         QueryNode rsEmployeesRecursive = new QueryNode("SELECT employeeNum, firstName, lastName FROM stock.employees WHERE supervisorNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsEmployeesRecursive.addBinding("xmltest.employees.employeeNum"); //$NON-NLS-1$
-        FakeMetadataObject rs4a = FakeMetadataFactory.createVirtualGroup("xmltest.employeesRecursive", xmltest, rsEmployeesRecursive); //$NON-NLS-1$
+        Table rs4a = RealMetadataFactory.createVirtualGroup("employeesRecursive", xmltest, rsEmployeesRecursive); //$NON-NLS-1$
 
 // ======================================================================================================================
 
         //create employees - not connected to any of the above
         QueryNode rsEmployees2 = new QueryNode("SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE supplierNumFK = '2' AND NOT (supervisorNum IS NULL)"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs5 = FakeMetadataFactory.createVirtualGroup("xmltest.employees2", xmltest, rsEmployees2); //$NON-NLS-1$
+        Table rs5 = RealMetadataFactory.createVirtualGroup("employees2", xmltest, rsEmployees2); //$NON-NLS-1$
 
         //recursive piece
         QueryNode rsEmployees2Recursive = new QueryNode("SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE employeeNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsEmployees2Recursive.addBinding("xmltest.employees2.supervisorNum"); //$NON-NLS-1$
-        FakeMetadataObject rs5a = FakeMetadataFactory.createVirtualGroup("xmltest.employees2Recursive", xmltest, rsEmployees2Recursive); //$NON-NLS-1$
+        Table rs5a = RealMetadataFactory.createVirtualGroup("employees2Recursive", xmltest, rsEmployees2Recursive); //$NON-NLS-1$
 
 //      ======================================================================================================================
 // Alternate mapping class which selects from stored query
@@ -198,25 +252,25 @@
         // Created 2nd virtual group w/ nested result set & binding
         QueryNode rsQueryX = new QueryNode("SELECT * FROM (exec xmltest.sqX(?)) as X"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQueryX.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-        FakeMetadataObject rsQX = FakeMetadataFactory.createVirtualGroup("xmltest.suppliersX", xmltest, rsQueryX); //$NON-NLS-1$
+        Table rsQX = RealMetadataFactory.createVirtualGroup("suppliersX", xmltest, rsQueryX); //$NON-NLS-1$
 
 // ======================================================================================================================
 // ALTERNATE METADATA A (temp groups)
 
         // root temp group
         QueryNode tempQuery = new QueryNode("SELECT * FROM stock.orders"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject temp = FakeMetadataFactory.createVirtualGroup("tempGroup.orders", xmltest, tempQuery); //$NON-NLS-1$
+        Table temp = RealMetadataFactory.createXmlStagingTable("doc9a.tempGroup.orders", xmltest, tempQuery); //$NON-NLS-1$
 
         // 2nd bogus root temp group selects from first - tests that temp groups can select from others
         QueryNode tempQuery2 = new QueryNode("SELECT * FROM tempGroup.orders"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject temp2 = FakeMetadataFactory.createVirtualGroup("tempGroup.orders2", xmltest, tempQuery2); //$NON-NLS-1$
+        Table temp2 = RealMetadataFactory.createXmlStagingTable("doc9a.tempGroup.orders2", xmltest, tempQuery2); //$NON-NLS-1$
         
         // Created virtual group w/ nested result set & binding - selects from 2nd temp root group
         QueryNode rsQuery3a = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders2 WHERE itemFK = ? AND supplierFK = ? AND supplierNameFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery3a.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
         rsQuery3a.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
         rsQuery3a.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
-        FakeMetadataObject rs3a = FakeMetadataFactory.createVirtualGroup("xmltest.ordersA", xmltest, rsQuery3a); //$NON-NLS-1$
+        Table rs3a = RealMetadataFactory.createVirtualGroup("ordersA", xmltest, rsQuery3a); //$NON-NLS-1$
 
 // ======================================================================================================================
 // ALTERNATE METADATA B (temp groups)
@@ -228,11 +282,11 @@
         tempQuery3b.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
         tempQuery3b.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
         tempQuery3b.addBinding("xmltest.suppliers.supplierName"); //$NON-NLS-1$
-        FakeMetadataObject temp3b = FakeMetadataFactory.createVirtualGroup("tempGroup.orders3B", xmltest, tempQuery3b); //$NON-NLS-1$
+        Table temp3b = RealMetadataFactory.createVirtualGroup("tempGroup.orders3B", xmltest, tempQuery3b); //$NON-NLS-1$
         
         // Created virtual group w/ nested result set & binding
         QueryNode rsQuery3b = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders3B"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs3b = FakeMetadataFactory.createVirtualGroup("xmltest.ordersB", xmltest, rsQuery3b); //$NON-NLS-1$
+        Table rs3b = RealMetadataFactory.createVirtualGroup("ordersB", xmltest, rsQuery3b); //$NON-NLS-1$
 
 
 // ======================================================================================================================
@@ -243,11 +297,11 @@
 //        tempQuery3b.addBinding("xmltest.group.items.itemNum");
 //        tempQuery3b.addBinding("xmltest.suppliers.supplierNum");
 //        tempQuery3b.addBinding("xmltest.suppliers.supplierName");
-//        FakeMetadataObject temp3b = FakeMetadataFactory.createVirtualGroup("tempGroup.orders3B", xmltest, tempQuery3b);
+//        Table temp3b = RealMetadataFactory.createVirtualGroup("orders3B", xmltest, tempQuery3b);
 //        
 //        // Created virtual group w/ nested result set & binding
 //        QueryNode rsQuery3b = new QueryNode("xmltest.ordersB", "SELECT orderNum, orderDate, orderQty, orderStatus FROM tempGroup.orders3B");
-//        FakeMetadataObject rs3b = FakeMetadataFactory.createVirtualGroup("xmltest.ordersB", xmltest, rs   Query3b);
+//        Table rs3b = RealMetadataFactory.createVirtualGroup("ordersB", xmltest, rs   Query3b);
 
 // ======================================================================================================================
 
@@ -256,9 +310,9 @@
        // Create virtual groups
        // per defect 12260 - correlated subquery in mapping class transformation
        QueryNode rsQuery12260 = new QueryNode("SELECT itemNum, itemName, itemQuantity, itemStatus, convert((select count(*) from stock.item_supplier where stock.items.itemNum = stock.item_supplier.itemNum), string) as NUMSuppliers FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs12260 = FakeMetadataFactory.createVirtualGroup("xmltest.group.itemsWithNumSuppliers", xmltest, rsQuery12260); //$NON-NLS-1$
+       Table rs12260 = RealMetadataFactory.createVirtualGroup("group.itemsWithNumSuppliers", xmltest, rsQuery12260); //$NON-NLS-1$
 
-       List rsElements12260 = FakeMetadataFactory.createElements(rs12260, 
+       RealMetadataFactory.createElements(rs12260, 
            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus", "numSuppliers" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });        
     
@@ -267,24 +321,24 @@
        // Create virtual groups
        // per defect 8373
        QueryNode rsQuery8373 = new QueryNode("SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items UNION ALL SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs8373 = FakeMetadataFactory.createVirtualGroup("xmltest.items8373", xmltest, rsQuery8373); //$NON-NLS-1$
+       Table rs8373 = RealMetadataFactory.createVirtualGroup("items8373", xmltest, rsQuery8373); //$NON-NLS-1$
 
-       List rsElements8373 = FakeMetadataFactory.createElements(rs8373, 
+       RealMetadataFactory.createElements(rs8373, 
             new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
 
        //select * from xmltest.items8373
        QueryNode rsQuery8373a = new QueryNode("SELECT * FROM xmltest.items8373"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs8373a = FakeMetadataFactory.createVirtualGroup("xmltest.items8373a", xmltest, rsQuery8373a); //$NON-NLS-1$
+       Table rs8373a = RealMetadataFactory.createVirtualGroup("items8373a", xmltest, rsQuery8373a); //$NON-NLS-1$
 
-       List rsElements8373a = FakeMetadataFactory.createElements(rs8373a, 
+       RealMetadataFactory.createElements(rs8373a, 
             new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
 
        QueryNode rsQuery8373b = new QueryNode("SELECT * FROM xmltest.group.items UNION ALL SELECT * FROM xmltest.group.items"); //$NON-NLS-1$ //$NON-NLS-2$
-       FakeMetadataObject rs8373b = FakeMetadataFactory.createVirtualGroup("xmltest.items8373b", xmltest, rsQuery8373b); //$NON-NLS-1$
+       Table rs8373b = RealMetadataFactory.createVirtualGroup("items8373b", xmltest, rsQuery8373b); //$NON-NLS-1$
 
-       List rsElements8373b = FakeMetadataFactory.createElements(rs8373b, 
+       RealMetadataFactory.createElements(rs8373b, 
             new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
        
@@ -294,133 +348,132 @@
         // Test an update query as a mapping class transformation, as if it were a 
         // mapping class returning a single int - defect 8812
         QueryNode rsUpdateQuery = new QueryNode("INSERT INTO stock.items (itemNum, itemName, itemQuantity, itemStatus) VALUES ('3','beer',12,'something')"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rsUpdate = FakeMetadataFactory.createVirtualGroup("xmltest.updateTest", xmltest, rsUpdateQuery); //$NON-NLS-1$
+        Table rsUpdate = RealMetadataFactory.createVirtualGroup("updateTest", xmltest, rsUpdateQuery); //$NON-NLS-1$
 
         // Create virtual elements
-        List rsElements = FakeMetadataFactory.createElements(rs, 
+        RealMetadataFactory.createElements(rs, 
             new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
 
 
-        List rsElements2 = FakeMetadataFactory.createElements(rs2, 
+        RealMetadataFactory.createElements(rs2, 
             new String[] { "supplierNum", "supplierName", "supplierZipCode"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElements3 = FakeMetadataFactory.createElements(rs3, 
+        RealMetadataFactory.createElements(rs3, 
             new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElements4 = FakeMetadataFactory.createElements(rs4, 
+        RealMetadataFactory.createElements(rs4, 
             new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElements4a = FakeMetadataFactory.createElements(rs4a, 
+        RealMetadataFactory.createElements(rs4a, 
             new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElements5 = FakeMetadataFactory.createElements(rs5, 
+        RealMetadataFactory.createElements(rs5, 
             new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElements5a = FakeMetadataFactory.createElements(rs5a, 
+        RealMetadataFactory.createElements(rs5a, 
             new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        List tempElements = FakeMetadataFactory.createElements(temp, 
+        RealMetadataFactory.createElements(temp, 
             new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List tempElements2 = FakeMetadataFactory.createElements(temp2, 
+        RealMetadataFactory.createElements(temp2, 
             new String[] { "orderNum", "itemFK", "supplierFK", "supplierNameFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElements3a = FakeMetadataFactory.createElements(rs3a, 
+        RealMetadataFactory.createElements(rs3a, 
             new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List tempElements3b = FakeMetadataFactory.createElements(temp3b, 
+        RealMetadataFactory.createElements(temp3b, 
             new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsElements3b = FakeMetadataFactory.createElements(rs3b, 
+        RealMetadataFactory.createElements(rs3b, 
             new String[] { "orderNum", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        List rsUpdateElement = FakeMetadataFactory.createElements(rsUpdate, 
+        RealMetadataFactory.createElements(rsUpdate, 
             new String[] { "rowCount" }, //$NON-NLS-1$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER});
 
-        List rsElementsX = FakeMetadataFactory.createElements(rsQX, 
+        RealMetadataFactory.createElements(rsQX, 
             new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
        
         // Create virtual docs
-        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("xmltest.doc1", xmltest, createXMLMappingNode(true)); //$NON-NLS-1$
-        List docE1 = FakeMetadataFactory.createElements(doc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+        Table doc1 = RealMetadataFactory.createXmlDocument("doc1", xmltest, createXMLMappingNode(true)); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
             
-        FakeMetadataObject doc1a = FakeMetadataFactory.createVirtualGroup("xmltest.doc1Unformatted", xmltest, createXMLMappingNode(false)); //$NON-NLS-1$
-        FakeMetadataObject doc1b = FakeMetadataFactory.createVirtualGroup("xmltest.doc1b", xmltest, createXMLPlan2(false, true, 0 )); //$NON-NLS-1$
-        List docE1b = FakeMetadataFactory.createElements(doc1b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+        RealMetadataFactory.createXmlDocument("doc1Unformatted", xmltest, createXMLMappingNode(false)); //$NON-NLS-1$
+        Table doc1b = RealMetadataFactory.createXmlDocument("doc1b", xmltest, createXMLPlan2(false, true, 0 )); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc1b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
                                                         new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        FakeMetadataObject doc1c = FakeMetadataFactory.createVirtualGroup("xmltest.doc1c", xmltest, createXMLPlan2(false, true, 1 )); //$NON-NLS-1$
-        List docE1c = FakeMetadataFactory.createElements(doc1c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+        Table doc1c = RealMetadataFactory.createXmlDocument("doc1c", xmltest, createXMLPlan2(false, true, 1 )); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc1c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
                                                         new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
         
-        FakeMetadataObject docBounded = FakeMetadataFactory.createVirtualGroup("xmltest.docBounded", xmltest, createXMLMappingBoundingNode()); //$NON-NLS-1$
-        List docBoundedElements = FakeMetadataFactory.createElements(docBounded, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+        Table docBounded = RealMetadataFactory.createXmlDocument("docBounded", xmltest, createXMLMappingBoundingNode()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(docBounded, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
         
-
-        FakeMetadataObject doc2  = FakeMetadataFactory.createVirtualGroup("xmltest.doc2",  xmltest, createXMLPlan2(1, -1, false)); //$NON-NLS-1$
-        List docE2 = FakeMetadataFactory.createElements(doc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Table doc2  = RealMetadataFactory.createXmlDocument("doc2",  xmltest, createXMLPlan2(1, -1, false)); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject doc2a = FakeMetadataFactory.createVirtualGroup("xmltest.doc2a", xmltest, createXMLPlan2(1, 1, false)); //$NON-NLS-1$
-        FakeMetadataObject doc2b = FakeMetadataFactory.createVirtualGroup("xmltest.doc2b", xmltest, createXMLPlan2(1, -1, true)); //$NON-NLS-1$
-        FakeMetadataObject doc2c = FakeMetadataFactory.createVirtualGroup("xmltest.doc2c", xmltest, createXMLPlan2(2, -1, false)); //$NON-NLS-1$
-        FakeMetadataObject doc2d = FakeMetadataFactory.createVirtualGroup("xmltest.doc2d", xmltest, createXMLPlan2(2, 1, false)); //$NON-NLS-1$
-        FakeMetadataObject doc2e = FakeMetadataFactory.createVirtualGroup("xmltest.doc2e", xmltest, createXMLPlan2(2, 3, false)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc2a", xmltest, createXMLPlan2(1, 1, false)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc2b", xmltest, createXMLPlan2(1, -1, true)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc2c", xmltest, createXMLPlan2(2, -1, false)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc2d", xmltest, createXMLPlan2(2, 1, false)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc2e", xmltest, createXMLPlan2(2, 3, false)); //$NON-NLS-1$
 
-        FakeMetadataObject doc3 = FakeMetadataFactory.createVirtualGroup("xmltest.doc3", xmltest, createXMLPlanWithDefaults()); //$NON-NLS-1$
-        List docE3 = FakeMetadataFactory.createElements(doc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+        Table doc3 = RealMetadataFactory.createXmlDocument("doc3", xmltest, createXMLPlanWithDefaults()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        FakeMetadataObject doc4 = FakeMetadataFactory.createVirtualGroup("xmltest.doc4", xmltest, createXMLPlanAdvanced()); //$NON-NLS-1$
-        List docE4 = FakeMetadataFactory.createElements(doc4, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Fake", "Catalogs.Fake.FakeChild2", "Catalogs.Fake.FakeChild2.FakeChild2a", "Catalogs.Fake.FakeChild3", "Catalogs.Fake.FakeChild3. at FakeAtt" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+        Table doc4 = RealMetadataFactory.createXmlDocument("doc4", xmltest, createXMLPlanAdvanced()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc4, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Fake", "Catalogs.Fake.FakeChild2", "Catalogs.Fake.FakeChild2.FakeChild2a", "Catalogs.Fake.FakeChild3", "Catalogs.Fake.FakeChild3. at FakeAtt" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER,DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        FakeMetadataObject doc5 = FakeMetadataFactory.createVirtualGroup("xmltest.doc5", xmltest, createXMLPlanUltraAdvanced()); //$NON-NLS-1$
-        List docE5 = FakeMetadataFactory.createElements(doc5, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
+        Table doc5 = RealMetadataFactory.createXmlDocument("doc5", xmltest, createXMLPlanUltraAdvanced()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc5, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject doc6 = FakeMetadataFactory.createVirtualGroup("xmltest.doc6", xmltest, createXMLPlanUltraAdvancedExceptionOnDefault()); //$NON-NLS-1$
-        List docE6 = FakeMetadataFactory.createElements(doc6, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.Shouldn't see"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+        Table doc6 = RealMetadataFactory.createXmlDocument("doc6", xmltest, createXMLPlanUltraAdvancedExceptionOnDefault()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc6, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.Shouldn't see"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject doc7 = FakeMetadataFactory.createVirtualGroup("xmltest.doc7", xmltest, createTestAttributePlan()); //$NON-NLS-1$
-        List docE7 = FakeMetadataFactory.createElements(doc7, new String[] { "FixedValueTest", "FixedValueTest.wrapper", "FixedValueTest.wrapper. at fixed", "FixedValueTest.wrapper. at key", "FixedValueTest.wrapper. at fixedAttr"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+        Table doc7 = RealMetadataFactory.createXmlDocument("doc7", xmltest, createTestAttributePlan()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc7, new String[] { "FixedValueTest", "FixedValueTest.wrapper", "FixedValueTest.wrapper. at fixed", "FixedValueTest.wrapper. at key", "FixedValueTest.wrapper. at fixedAttr"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
                         
-        FakeMetadataObject doc8 = FakeMetadataFactory.createVirtualGroup("xmltest.doc8", xmltest, createXMLPlanNested()); //$NON-NLS-1$
-        List docE8 = FakeMetadataFactory.createElements(doc8, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+        Table doc8 = RealMetadataFactory.createXmlDocument("doc8", xmltest, createXMLPlanNested()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc8, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
     
-        FakeMetadataObject doc9 = FakeMetadataFactory.createVirtualGroup("xmltest.doc9", xmltest, createXMLPlanNested2()); //$NON-NLS-1$
-        List docE9 = FakeMetadataFactory.createElements(doc9, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-2$!
  //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
+        Table doc9 = RealMetadataFactory.createXmlDocument("doc9", xmltest, createXMLPlanNested2()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc9, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3!
 $ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
             
-        FakeMetadataObject doc9a = FakeMetadataFactory.createVirtualGroup("xmltest.doc9a", xmltest, createXMLPlanNested2a()); //$NON-NLS-1$
-        List docE9a = FakeMetadataFactory.createElements(doc9a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-!
 2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
+        Table doc9a = RealMetadataFactory.createXmlDocument("doc9a", xmltest, createXMLPlanNested2a()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc9a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.orders", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.orders.order.OrderStatus"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-!
 3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc9b = FakeMetadataFactory.createVirtualGroup("xmltest.doc9b", xmltest, createXMLPlanNested2b()); //$NON-NLS-1$
-        FakeMetadataObject doc10 = FakeMetadataFactory.createVirtualGroup("xmltest.doc10", xmltest, createXMLPlanNestedWithChoice()); //$NON-NLS-1$
-        List docE10 = FakeMetadataFactory.createElements(doc10, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.Pro!
 cessingOrders.order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
+        RealMetadataFactory.createXmlDocument("doc9b", xmltest, createXMLPlanNested2b()); //$NON-NLS-1$
+        Table doc10 = RealMetadataFactory.createXmlDocument("doc10", xmltest, createXMLPlanNestedWithChoice()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc10, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.!
 order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc10L = FakeMetadataFactory.createVirtualGroup("xmltest.doc10L", xmltest, createXMLPlanNestedWithLookupChoice()); //$NON-NLS-1$
-        List docE10L = FakeMetadataFactory.createElements(doc10L, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.P!
 rocessingOrders.order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
+        Table doc10L = RealMetadataFactory.createXmlDocument("doc10L", xmltest, createXMLPlanNestedWithLookupChoice()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc10L, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order. at OrderID" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderDate", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.order.OrderQuantity", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders!
 .order.OrderStatus", "Catalogs.Catalog.items.item.suppliers.supplier.orders.ProcessingOrders" ,"Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder. at OrderID", "Catalogs.Catalog.items.item.suppliers.supplier.ProcessingOrders.otherorder"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$ //$NON-NLS-18$ //$NON-NLS-19$ //$NON-NLS-20$ //$NON-NLS-21$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
 
-        FakeMetadataObject doc11 = FakeMetadataFactory.createVirtualGroup("xmltest.doc11", xmltest, createXMLPlanMultipleDocs()); //$NON-NLS-1$
-        List docE11 = FakeMetadataFactory.createElements(doc11, new String[] { "Item", "Item. at ItemID", "Item.Name", "Item.Quantity", "Item.Suppliers", "Item.Suppliers.Supplier", "Item.Suppliers.Supplier. at SupplierID", "Item.Suppliers.Supplier.Name", "Item.Suppliers.Supplier.Zip"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ 
+        Table doc11 = RealMetadataFactory.createXmlDocument("doc11", xmltest, createXMLPlanMultipleDocs()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc11, new String[] { "Item", "Item. at ItemID", "Item.Name", "Item.Quantity", "Item.Suppliers", "Item.Suppliers.Supplier", "Item.Suppliers.Supplier. at SupplierID", "Item.Suppliers.Supplier.Name", "Item.Suppliers.Supplier.Zip"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ 
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
         //variations on the same recursive doc====================
@@ -428,92 +481,92 @@
         int recursionlimit = -1;
         boolean exceptionOnLimit = false;
 
-        FakeMetadataObject doc12 = FakeMetadataFactory.createVirtualGroup("xmltest.doc12", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
-        FakeMetadataObject doc12a = FakeMetadataFactory.createVirtualGroup("xmltest.doc12a", xmltest, createXMLPlanRecursiveA(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc12", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc12a", xmltest, createXMLPlanRecursiveA(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
 
         useRecursiveCriteria = true;
-        FakeMetadataObject doc13 = FakeMetadataFactory.createVirtualGroup("xmltest.doc13", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc13", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
         useRecursiveCriteria = false;
         recursionlimit = 2;
-        FakeMetadataObject doc14 = FakeMetadataFactory.createVirtualGroup("xmltest.doc14", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc14", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
         exceptionOnLimit = true;
-        FakeMetadataObject doc15 = FakeMetadataFactory.createVirtualGroup("xmltest.doc15", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc15", xmltest, createXMLPlanRecursive(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
 
         useRecursiveCriteria = false;
         recursionlimit = -1;
         exceptionOnLimit = false;
-        FakeMetadataObject doc16 = FakeMetadataFactory.createVirtualGroup("xmltest.doc16", xmltest, createXMLPlanRecursive2(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc16", xmltest, createXMLPlanRecursive2(useRecursiveCriteria, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
 
-        FakeMetadataObject doc17 = FakeMetadataFactory.createVirtualGroup("xmltest.doc17", xmltest, createXMLPlanWithComment()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc17", xmltest, createXMLPlanWithComment()); //$NON-NLS-1$
 
-        FakeMetadataObject doc_5266a = FakeMetadataFactory.createVirtualGroup("xmltest.doc_5266a", xmltest, createXMLPlanNestedWithChoiceFor5266()); //$NON-NLS-1$
-        List doc_E5266a = FakeMetadataFactory.createElements(doc_5266a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Table doc_5266a = RealMetadataFactory.createXmlDocument("doc_5266a", xmltest, createXMLPlanNestedWithChoiceFor5266()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc_5266a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                                                              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 
 
-        FakeMetadataObject doc_8917 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_8917", xmltest, createXMLPlan_defect8917()); //$NON-NLS-1$
-        FakeMetadataObject doc_9446 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_9446", xmltest, createXMLPlan_defect9446()); //$NON-NLS-1$
-        FakeMetadataObject doc_9530 = FakeMetadataFactory.createVirtualGroup("xmltest.doc_9530", xmltest, createXMLPlan_defect_9530()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc_8917", xmltest, createXMLPlan_defect8917()); //$NON-NLS-1$
+        Table doc_9446 = RealMetadataFactory.createXmlDocument("doc_9446", xmltest, createXMLPlan_defect9446()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc_9530", xmltest, createXMLPlan_defect_9530()); //$NON-NLS-1$
 
-        List docE_9446 = FakeMetadataFactory.createElements(doc_9446, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item.XXXXX", "Catalogs.Catalog.items.item.XXXXX", "Catalogs.Catalog.items.item.XXXXX"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
+        RealMetadataFactory.createElements(doc_9446, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item.XXXXX"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
         
         //Test doc w/ update mapping class transformation
-        FakeMetadataObject docUpdateTest = FakeMetadataFactory.createVirtualGroup("xmltest.docUpdateTest", xmltest, createUpdateTestDoc()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("docUpdateTest", xmltest, createUpdateTestDoc()); //$NON-NLS-1$
 
-        FakeMetadataObject doc_9893 = FakeMetadataFactory.createVirtualGroup("xmltest.doc9893", xmltest, createXMLPlan_9893()); //$NON-NLS-1$
-        List docE_9893 = FakeMetadataFactory.createElements(doc_9893, new String[] { "Root", "Root.ItemName"}, //$NON-NLS-1$ //$NON-NLS-2$
+        Table doc_9893 = RealMetadataFactory.createXmlDocument("doc9893", xmltest, createXMLPlan_9893()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc_9893, new String[] { "Root", "Root.ItemName"}, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc18 = FakeMetadataFactory.createVirtualGroup("xmltest.doc18", xmltest, createXMLPlanNested("xmltest.suppliersX")); //$NON-NLS-1$ //$NON-NLS-2$
-        List docE18 = FakeMetadataFactory.createElements(doc18, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
+        Table doc18 = RealMetadataFactory.createXmlDocument("doc18", xmltest, createXMLPlanNested("xmltest.suppliersX")); //$NON-NLS-1$ //$NON-NLS-2$
+        RealMetadataFactory.createElements(doc18, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name" },  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc12260 = FakeMetadataFactory.createVirtualGroup("xmltest.doc12260", xmltest, createXMLPlanCorrelatedSubqueryTransform()); //$NON-NLS-1$
-        List docE12260 = FakeMetadataFactory.createElements(doc12260, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+        Table doc12260 = RealMetadataFactory.createXmlDocument("doc12260", xmltest, createXMLPlanCorrelatedSubqueryTransform()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc12260, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc8373 = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373", xmltest, createXMLPlan_defect8373()); //$NON-NLS-1$
-        List docE8373 = FakeMetadataFactory.createElements(doc8373, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+        Table doc8373 = RealMetadataFactory.createXmlDocument("doc8373", xmltest, createXMLPlan_defect8373()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc8373, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc8373a = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373a", xmltest, createXMLPlan_defect8373a()); //$NON-NLS-1$
-        List docE8373a = FakeMetadataFactory.createElements(doc8373a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+        Table doc8373a = RealMetadataFactory.createXmlDocument("doc8373a", xmltest, createXMLPlan_defect8373a()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc8373a, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc8373b = FakeMetadataFactory.createVirtualGroup("xmltest.doc8373b", xmltest, createXMLPlan_defect8373b()); //$NON-NLS-1$
-        List docE8373b = FakeMetadataFactory.createElements(doc8373b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
+        Table doc8373b = RealMetadataFactory.createXmlDocument("doc8373b", xmltest, createXMLPlan_defect8373b()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc8373b, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.numSuppliers" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-8$
                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
 
-        FakeMetadataObject doc13617 = FakeMetadataFactory.createVirtualGroup("xmltest.doc13617", xmltest, createXMLPlanDefect13617()); //$NON-NLS-1$
-        List docE13617 = FakeMetadataFactory.createElements(doc13617, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
+        Table doc13617 = RealMetadataFactory.createXmlDocument("doc13617", xmltest, createXMLPlanDefect13617()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc13617, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity" },  //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-7$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER});
         
 
         // recursive + staging ========================================================
 
-        FakeMetadataObject doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.doc19", xmltest, createXMLPlanRecursiveStaging(true, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc19", xmltest, createXMLPlanRecursiveStaging(true, recursionlimit, exceptionOnLimit)); //$NON-NLS-1$
         
         // root temp group
         QueryNode doc19TempQuery = new QueryNode("SELECT employeeNum, firstName, lastName, supervisorNum FROM stock.employees"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject tempDoc19 = FakeMetadataFactory.createVirtualGroup("xmltest.doc19temp", xmltest, doc19TempQuery); //$NON-NLS-1$
-        List doc19TempQueryE = FakeMetadataFactory.createElements(tempDoc19, 
+        Table tempDoc19 = RealMetadataFactory.createVirtualGroup("doc19temp", xmltest, doc19TempQuery); //$NON-NLS-1$
+        RealMetadataFactory.createElements(tempDoc19, 
                                                               new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
                                                               new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
         
 
         //create employees - not connected to any of the above
         QueryNode rsEmployeesDoc19 = new QueryNode("SELECT employeeNum, firstName, lastName FROM xmltest.doc19temp WHERE supervisorNum IS NULL"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject mc1Doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.employeesDoc19", xmltest, rsEmployeesDoc19); //$NON-NLS-1$
-        List mc1Doc19E = FakeMetadataFactory.createElements(mc1Doc19, 
+        Table mc1Doc19 = RealMetadataFactory.createVirtualGroup("employeesDoc19", xmltest, rsEmployeesDoc19); //$NON-NLS-1$
+        RealMetadataFactory.createElements(mc1Doc19, 
                                                                   new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
                                                                   new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 
         //recursive piece
         QueryNode rsEmployeesRecursiveDoc19 = new QueryNode("SELECT employeeNum, firstName, lastName FROM xmltest.doc19temp WHERE supervisorNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsEmployeesRecursiveDoc19.addBinding("xmltest.employeesDoc19.employeeNum"); //$NON-NLS-1$
-        FakeMetadataObject mc2Doc19 = FakeMetadataFactory.createVirtualGroup("xmltest.employeesRecursiveDoc19", xmltest, rsEmployeesRecursiveDoc19); //$NON-NLS-1$
-        List mc2Doc19E = FakeMetadataFactory.createElements(mc2Doc19, 
+        Table mc2Doc19 = RealMetadataFactory.createVirtualGroup("employeesRecursiveDoc19", xmltest, rsEmployeesRecursiveDoc19); //$NON-NLS-1$
+        RealMetadataFactory.createElements(mc2Doc19, 
                                                             new String[] { "employeeNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
         
@@ -522,217 +575,71 @@
         //========================================================
 
         // Stored queries
-        FakeMetadataObject rsX = FakeMetadataFactory.createResultSet("xmltest.rsX", xmltest, new String[] { "supplierNum", "supplierName", "supplierZipCode" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        FakeMetadataObject rsXp1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rsX);  //$NON-NLS-1$
-        FakeMetadataObject rsXp2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        ColumnSet<Procedure> rsX = RealMetadataFactory.createResultSet("xmltest.rsX", new String[] { "supplierNum", "supplierName", "supplierZipCode" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+        ProcedureParameter rsXp2 = RealMetadataFactory.createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
         //there is an extra statement in this proc so that the procedure wrapper is not removed
         QueryNode sqXn1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string x; SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = xmltest.sqX.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sqX = FakeMetadataFactory.createVirtualProcedure("xmltest.sqX", xmltest, Arrays.asList(new FakeMetadataObject[] { rsXp1, rsXp2 }), sqXn1);  //$NON-NLS-1$
+        Procedure sqX = RealMetadataFactory.createVirtualProcedure("sqX", xmltest, Arrays.asList(rsXp2), sqXn1);  //$NON-NLS-1$
+        sqX.setResultSet(rsX);
        
         // Documents for Text Normalization Test 
         // normDoc1 - for collapse
         // normDoc2 - for replace
         // normDoc3 - for preserve
-        FakeMetadataObject normDoc1 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc1", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_COLLAPSE)); //$NON-NLS-1$
-        List normDocE1 = FakeMetadataFactory.createElements(normDoc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
+        Table normDoc1 = RealMetadataFactory.createXmlDocument("normDoc1", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_COLLAPSE)); //$NON-NLS-1$
+        RealMetadataFactory.createElements(normDoc1, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
                                                         new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        FakeMetadataObject normDoc2 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc2", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_REPLACE)); //$NON-NLS-1$
-        List normDocE2 = FakeMetadataFactory.createElements(normDoc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
+        Table normDoc2 = RealMetadataFactory.createXmlDocument("normDoc2", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_REPLACE)); //$NON-NLS-1$
+        RealMetadataFactory.createElements(normDoc2, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
  
-        FakeMetadataObject normDoc3 = FakeMetadataFactory.createVirtualGroup("xmltest.normDoc3", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_PRESERVE)); //$NON-NLS-1$
-        List normDocE3 = FakeMetadataFactory.createElements(normDoc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-N!
 LS-17$
+        Table normDoc3 = RealMetadataFactory.createXmlDocument("normDoc3", xmltest, createXMLPlanNormalization(MappingNodeConstants.NORMALIZE_TEXT_PRESERVE)); //$NON-NLS-1$
+        RealMetadataFactory.createElements(normDoc3, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.DiscontinuedItem", "Catalogs.Catalog.items.DiscontinuedItem. at ItemID", "Catalogs.Catalog.items.DiscontinuedItem.Name", "Catalogs.Catalog.items.DiscontinuedItem.Quantity", "Catalogs.Catalog.items.StatusUnknown", "Catalogs.Catalog.items.StatusUnknown. at ItemID", "Catalogs.Catalog.items.StatusUnknown.Name", "Catalogs.Catalog.items.StatusUnknown.Quantity", "Catalogs.Catalog.items.Shouldn't see", "Catalogs.Catalog.items.Shouldn't see 2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$ //$NON-NLS-17$
                                                             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
         
         QueryNode vspqn1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN insert into #temp select * from stock.items where itemquantity < param; SELECT * FROM xmltest.doc1 where Item.Quantity < (select avg(itemquantity) from #temp); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsprs1 = FakeMetadataFactory.createResultSet("pm1.vsprs1", xmltest, new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vspp1 = FakeMetadataFactory.createParameter("param", 1, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, vsprs1); //$NON-NLS-1$
-        FakeMetadataObject vspp2 = FakeMetadataFactory.createParameter("ret", 2, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.XML, vsprs1); //$NON-NLS-1$
-        FakeMetadataObject vsp1 = FakeMetadataFactory.createVirtualProcedure("xmltest.vsp1", xmltest, Arrays.asList(vspp1, vspp2 ), vspqn1); //$NON-NLS-1$
+        ColumnSet<Procedure> vsprs1 = RealMetadataFactory.createResultSet("pm1.vsprs1", new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.XML }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vspp1 = RealMetadataFactory.createParameter("param", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        Procedure vsp1 = RealMetadataFactory.createVirtualProcedure("vsp1", xmltest, Arrays.asList(vspp1 ), vspqn1); //$NON-NLS-1$
+        vsp1.setResultSet(vsprs1);
 
-        // Add all objects to the store
-        store.addObject(stock);
-        store.addObject(items);
-        store.addObject(item_supplier);
-   
-        store.addObject(suppliers);
-        store.addObject(orders);
-        store.addObject(employees);
-        store.addObjects(itemElements);
-        store.addObjects(itemSupplierElements);
-        store.addObjects(supplierElements);
-        store.addObjects(stockOrders);
-        store.addObjects(supplierEmployees);
-     
-        store.addObject(xmltest);
-        store.addObject(rs);
-        store.addObject(rs2);
-        store.addObject(rs3);
-        store.addObject(rs4);
-        store.addObject(rs4a);
-        store.addObject(rs5);
-        store.addObject(rs5a);
-        store.addObject(temp);
-        store.addObject(temp2);
-        store.addObject(rs3a);
-        store.addObject(temp3b);
-        store.addObject(rs3b);
-        store.addObject(rsQX);
-        store.addObject(rs12260);
-        store.addObject(rs8373);
-        store.addObject(rs8373a);
-        store.addObject(rs8373b);
-        
-        //Stored query
-        store.addObject(rsX);
-        store.addObject(sqX);
-  
-        store.addObject(rsUpdate);
-        store.addObjects(rsElements);
-        store.addObjects(rsElements2);
-        store.addObjects(rsElements3);
-        store.addObjects(rsElements4);
-        store.addObjects(rsElements4a);
-        store.addObjects(rsElements5);
-        store.addObjects(rsElements5a);
-        store.addObjects(tempElements);
-        store.addObjects(tempElements2);
-        store.addObjects(rsElements3a);
-        store.addObjects(tempElements3b);
-        store.addObjects(rsElements3b);
-        store.addObjects(rsUpdateElement);
-        store.addObjects(rsElementsX);
-        store.addObjects(rsElements12260);
-        store.addObjects(rsElements8373);
-        store.addObjects(rsElements8373a);
-        store.addObjects(rsElements8373b);
-
-        store.addObject(doc1);
-        store.addObject(docBounded);
-        store.addObject(doc1a);
-        store.addObject(doc1b);
-        store.addObject(doc1c);
-        store.addObject(doc2);
-        store.addObject(doc2a);
-        store.addObject(doc2b);
-        store.addObject(doc2c);
-        store.addObject(doc2d);
-        store.addObject(doc2e);
-        store.addObject(doc3);
-        store.addObject(doc4);
-        store.addObject(doc5);
- 
-        store.addObject(normDoc1);
-        store.addObject(normDoc2);
-        store.addObject(normDoc3);
-
-        store.addObject(doc6);
-        store.addObject(doc7);
-        store.addObject(doc8);
-        store.addObject(doc9);
-        store.addObject(doc9a);
-        store.addObject(doc9b);
-     
-        store.addObject(doc10);
-        store.addObject(doc10L);
-        store.addObject(doc11);
-        store.addObject(doc12);
-        store.addObject(doc12a);
-        store.addObject(doc13);
-        store.addObject(doc14);
-        store.addObject(doc15);
-        store.addObject(doc16);
-        store.addObject(doc17);
-        store.addObject(doc_8917);
-        store.addObject(doc_9446);
-        store.addObject(doc_9530);
-        store.addObject(docUpdateTest);
-        store.addObject(doc_9893);
-        store.addObject(doc18);
-        store.addObject(doc12260);
-        store.addObject(doc8373);
-        store.addObject(doc8373a);
-        store.addObject(doc8373b);
-        store.addObject(doc13617);
-        store.addObject(doc19);
-        store.addObject(tempDoc19);
-        store.addObject(mc1Doc19);
-        store.addObject(mc2Doc19);
-        store.addObject(doc_5266a);
-
-        store.addObjects(doc19TempQueryE);
-        store.addObjects(mc1Doc19E);
-        store.addObjects(mc2Doc19E);
-        
-        store.addObjects(docE1);
-        store.addObjects(docE1b);
-        store.addObjects(docE1c);
-        store.addObjects(docBoundedElements);
-        store.addObjects(docE2);
-        store.addObjects(docE3);
-        store.addObjects(docE4);
-        store.addObjects(docE5);
-        store.addObjects(normDocE1);
-        store.addObjects(normDocE2);
-        store.addObjects(normDocE3);
-        store.addObjects(docE6);
-        store.addObjects(docE7);
-        store.addObjects(docE8);
-        store.addObjects(docE9);
-        store.addObjects(docE9a);
-        store.addObjects(docE_9446);
-        store.addObjects(docE_9893);
-        store.addObjects(docE18);
-        store.addObjects(docE12260);
-        store.addObjects(docE8373);
-        store.addObjects(docE8373a);
-        store.addObjects(docE8373b);
-        store.addObjects(docE13617);
-        store.addObjects(doc_E5266a);
-        
-        store.addObjects(docE10);
-        store.addObjects(docE10L);
-        store.addObjects(docE11);
-        
-        store.addObject(vsp1);        
-        return facade;
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
     }
 
-    public FakeMetadataFacade exampleMetadataNestedWithSibling() {
-		FakeMetadataStore store = new FakeMetadataStore();
-		FakeMetadataFacade facade = new FakeMetadataFacade(store);
+    public static QueryMetadataInterface exampleMetadataNestedWithSibling() {
+		MetadataStore metadataStore = new MetadataStore();
         
 		// Create models
-		FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
-		FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");  //$NON-NLS-1$
+		Schema stock = RealMetadataFactory.createPhysicalModel("stock", metadataStore); //$NON-NLS-1$
+		Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore);  //$NON-NLS-1$
 
 		// Create physical groups
-		FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
-		FakeMetadataObject item_supplier = FakeMetadataFactory.createPhysicalGroup("stock.item_supplier", stock); //$NON-NLS-1$
-		FakeMetadataObject item_order = FakeMetadataFactory.createPhysicalGroup("stock.item_order", stock); //$NON-NLS-1$
-		FakeMetadataObject orders = FakeMetadataFactory.createPhysicalGroup("stock.orders", stock); //$NON-NLS-1$
-		FakeMetadataObject suppliers = FakeMetadataFactory.createPhysicalGroup("stock.suppliers", stock); //$NON-NLS-1$
+		Table items = RealMetadataFactory.createPhysicalGroup("items", stock); //$NON-NLS-1$
+		Table item_supplier = RealMetadataFactory.createPhysicalGroup("item_supplier", stock); //$NON-NLS-1$
+		Table item_order = RealMetadataFactory.createPhysicalGroup("item_order", stock); //$NON-NLS-1$
+		Table orders = RealMetadataFactory.createPhysicalGroup("orders", stock); //$NON-NLS-1$
+		Table suppliers = RealMetadataFactory.createPhysicalGroup("suppliers", stock); //$NON-NLS-1$
 		      
 		// Create physical elements
-		List itemElements = FakeMetadataFactory.createElements(items, 
+		RealMetadataFactory.createElements(items, 
 			new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
 		//many-to-many join table
-		List itemSupplierElements = FakeMetadataFactory.createElements(item_supplier, 
+		RealMetadataFactory.createElements(item_supplier, 
 			new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 
-		List supplierElements = FakeMetadataFactory.createElements(suppliers, 
+		RealMetadataFactory.createElements(suppliers, 
 			new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 
 		//many-to-many join table
-		List itemOrderElements = FakeMetadataFactory.createElements(item_order, 
+		RealMetadataFactory.createElements(item_order, 
 			new String[] { "itemNum", "orderNum" }, //$NON-NLS-1$ //$NON-NLS-2$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 
-		List stockOrders = FakeMetadataFactory.createElements(orders, 
+		RealMetadataFactory.createElements(orders, 
 			new String[] { "orderNum", "orderName", "orderZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 	
@@ -740,288 +647,204 @@
 
 		// Create virtual groups
 		QueryNode rsQuery1 = new QueryNode("SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject rs1 = FakeMetadataFactory.createVirtualGroup("xmltest.group.items", xmltest, rsQuery1); //$NON-NLS-1$
+		Table rs1 = RealMetadataFactory.createVirtualGroup("group.items", xmltest, rsQuery1); //$NON-NLS-1$
 
 		QueryNode rsQuery2 = new QueryNode("SELECT concat(stock.suppliers.supplierNum, '') as supplierNum, supplierName, supplierZipCode FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
 		rsQuery2.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-		FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xmltest.suppliers", xmltest, rsQuery2); //$NON-NLS-1$
+		Table rs2 = RealMetadataFactory.createVirtualGroup("suppliers", xmltest, rsQuery2); //$NON-NLS-1$
 
 		QueryNode rsQuery3 = new QueryNode("SELECT concat(stock.orders.orderNum, '') as orderNum, orderName, orderZipCode FROM stock.orders, stock.item_order WHERE stock.orders.orderNum = stock.item_order.orderNum AND stock.item_order.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
 		rsQuery3.addBinding("xmltest.group.items.itemNum"); //$NON-NLS-1$
-		FakeMetadataObject rs3= FakeMetadataFactory.createVirtualGroup("xmltest.orders", xmltest, rsQuery3); //$NON-NLS-1$
+		Table rs3= RealMetadataFactory.createVirtualGroup("orders", xmltest, rsQuery3); //$NON-NLS-1$
 
 		// Create virtual elements
-		List rsElements1 = FakeMetadataFactory.createElements(rs1, 
+		RealMetadataFactory.createElements(rs1, 
 			new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 		
-		List rsElements2 = FakeMetadataFactory.createElements(rs2, 
+		RealMetadataFactory.createElements(rs2, 
 			new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 		
-		List rsElements3 = FakeMetadataFactory.createElements(rs3, 
+		RealMetadataFactory.createElements(rs3, 
 			new String[] { "orderNum", "orderName", "orderZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 	
 // =========================================================================================================
 
 		// Create virtual docs
-		FakeMetadataObject doc9c= FakeMetadataFactory.createVirtualGroup("xmltest.doc9c", xmltest, createXMLPlanNested2c()); //$NON-NLS-1$
-		List docE9c = FakeMetadataFactory.createElements(doc9c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.orders", "Catalogs.Catalog.items.item.orders.order", "Catalogs.Catalog.items.item.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.orders.order.zip", "Catalogs.Catalog.items.item.orders.order.Name"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ !
 //$NON-NLS-16$ //$NON-NLS-17$
+		Table doc9c= RealMetadataFactory.createXmlDocument("doc9c", xmltest, createXMLPlanNested2c()); //$NON-NLS-1$
+		RealMetadataFactory.createElements(doc9c, new String[] { "Catalogs", "Catalogs.Catalog", "Catalogs.Catalog.items", "Catalogs.Catalog.items.item", "Catalogs.Catalog.items.item. at ItemID", "Catalogs.Catalog.items.item.Name", "Catalogs.Catalog.items.item.Quantity", "Catalogs.Catalog.items.item.suppliers", "Catalogs.Catalog.items.item.suppliers.supplier", "Catalogs.Catalog.items.item.suppliers.supplier. at SupplierID", "Catalogs.Catalog.items.item.suppliers.supplier.zip", "Catalogs.Catalog.items.item.suppliers.supplier.Name", "Catalogs.Catalog.items.item.orders", "Catalogs.Catalog.items.item.orders.order", "Catalogs.Catalog.items.item.orders.order. at OrderID" ,"Catalogs.Catalog.items.item.orders.order.zip", "Catalogs.Catalog.items.item.orders.order.Name"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ //$NON-NLS-13$ //$NON-NLS-14$ //$NON-NLS-15$ //$NON-NLS-16$!
  //$NON-NLS-17$
 			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
 		
-		//========================================================
-
-		// Add all objects to the store
-		store.addObject(stock);
-		
-		store.addObject(items);
-		store.addObject(item_supplier);
-		store.addObject(item_order);
-		store.addObject(suppliers);
-		store.addObject(orders);
-		
-		store.addObjects(itemElements);
-		store.addObjects(itemSupplierElements);
-		store.addObjects(supplierElements);
-		store.addObjects(stockOrders);
-		store.addObjects(itemOrderElements);
-
-		store.addObject(xmltest);
-		store.addObject(rs1);
-		store.addObject(rs2);
-		store.addObject(rs3);
-		
-		store.addObjects(rsElements1);
-		store.addObjects(rsElements2);
-		store.addObjects(rsElements3);
-
-		store.addObject(doc9c);
-		store.addObjects(docE9c);
-     
-		// Create the facade from the store
-		return facade;		
+		return RealMetadataFactory.createTransformationMetadata(metadataStore, "nestedWithSibling");		
 	}
 	
-    public static FakeMetadataFacade exampleMetadata2() { 
-        FakeMetadataStore store = new FakeMetadataStore();
-        FakeMetadataFacade facade = new FakeMetadataFacade(store);
+    public static TransformationMetadata exampleMetadata2() { 
+    	MetadataStore metadataStore = new MetadataStore();
         
         // Create models
-        FakeMetadataObject xqt = FakeMetadataFactory.createPhysicalModel("xqt"); //$NON-NLS-1$
-        FakeMetadataObject xqttest = FakeMetadataFactory.createVirtualModel("xqttest");     //$NON-NLS-1$
+        Schema xqt = RealMetadataFactory.createPhysicalModel("xqt", metadataStore); //$NON-NLS-1$
+        Schema xqttest = RealMetadataFactory.createVirtualModel("xqttest", metadataStore);     //$NON-NLS-1$
 
         // Create physical groups
-        FakeMetadataObject xqtGroup = FakeMetadataFactory.createPhysicalGroup("xqt.data", xqt); //$NON-NLS-1$
+        Table xqtGroup = RealMetadataFactory.createPhysicalGroup("data", xqt); //$NON-NLS-1$
                 
         // Create physical elements
-        List xqtData = FakeMetadataFactory.createElements(xqtGroup, 
+        RealMetadataFactory.createElements(xqtGroup, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
         // Create new XML recursion tests virtual groups
         QueryNode xqtDataGroup = new QueryNode("SELECT intKey as key, intNum as data, (intKey + 2) as nextKey FROM xqt.data"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject objData = FakeMetadataFactory.createVirtualGroup("xqttest.xqtData", xqttest, xqtDataGroup); //$NON-NLS-1$
+        Table objData = RealMetadataFactory.createVirtualGroup("xqtData", xqttest, xqtDataGroup); //$NON-NLS-1$
         
         QueryNode rsGroup = new QueryNode("SELECT key as ID, data as CODE, nextKey as supervisorID FROM xqttest.xqtData"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject objGroup = FakeMetadataFactory.createVirtualGroup("xqttest.group", xqttest, rsGroup); //$NON-NLS-1$
+        Table objGroup = RealMetadataFactory.createVirtualGroup("group", xqttest, rsGroup); //$NON-NLS-1$
         
         QueryNode rsSupervisor = new QueryNode("SELECT key as ID, data as CODE, nextKey as groupID FROM xqttest.xqtData WHERE key = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsSupervisor.addBinding("xqttest.group.supervisorID"); //$NON-NLS-1$
-        FakeMetadataObject objSupervisor = FakeMetadataFactory.createVirtualGroup("xqttest.supervisor", xqttest, rsSupervisor); //$NON-NLS-1$
+        Table objSupervisor = RealMetadataFactory.createVirtualGroup("supervisor", xqttest, rsSupervisor); //$NON-NLS-1$
 
         QueryNode rsGroup1 = new QueryNode("SELECT key as ID, data as CODE, nextKey as supervisorID FROM xqttest.xqtData WHERE key = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsGroup1.addBinding("xqttest.supervisor.groupID"); //$NON-NLS-1$
-        FakeMetadataObject objGroup1 = FakeMetadataFactory.createVirtualGroup("xqttest.group1", xqttest, rsGroup1); //$NON-NLS-1$
+        Table objGroup1 = RealMetadataFactory.createVirtualGroup("group1", xqttest, rsGroup1); //$NON-NLS-1$
         
         // Create virtual elements
         
-        List elemXQTData = FakeMetadataFactory.createElements(objData, 
+        RealMetadataFactory.createElements(objData, 
             new String[] { "key", "data", "nextKey" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
 
-        List elemGroup = FakeMetadataFactory.createElements(objGroup, 
+        RealMetadataFactory.createElements(objGroup, 
             new String[] { "ID", "code", "supervisorID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
 
-        List elemSupervisor = FakeMetadataFactory.createElements(objSupervisor, 
+        RealMetadataFactory.createElements(objSupervisor, 
             new String[] { "ID", "code", "groupID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
 
-        List elemGroup1 = FakeMetadataFactory.createElements(objGroup1, 
+        RealMetadataFactory.createElements(objGroup1, 
             new String[] { "ID", "code", "supervisorID" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER });
         
         // Create virtual groups
         QueryNode rsQuery = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey=13"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs = FakeMetadataFactory.createVirtualGroup("xqttest.data", xqttest, rsQuery); //$NON-NLS-1$
+        Table rs = RealMetadataFactory.createVirtualGroup("data", xqttest, rsQuery); //$NON-NLS-1$
         
         QueryNode rsQuery2 = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery2.addBinding("xqttest.data.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs2 = FakeMetadataFactory.createVirtualGroup("xqttest.data2", xqttest, rsQuery2); //$NON-NLS-1$
+        Table rs2 = RealMetadataFactory.createVirtualGroup("data2", xqttest, rsQuery2); //$NON-NLS-1$
 
         QueryNode rsQuery3 = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery3.addBinding("xqttest.data2.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs3 = FakeMetadataFactory.createVirtualGroup("xqttest.data3", xqttest, rsQuery3); //$NON-NLS-1$
+        Table rs3 = RealMetadataFactory.createVirtualGroup("data3", xqttest, rsQuery3); //$NON-NLS-1$
 
         QueryNode rsQuery4 = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery4.addBinding("xqttest.data.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs4 = FakeMetadataFactory.createVirtualGroup("xqttest.data4", xqttest, rsQuery4); //$NON-NLS-1$
+        Table rs4 = RealMetadataFactory.createVirtualGroup("data4", xqttest, rsQuery4); //$NON-NLS-1$
 
         QueryNode rsQuery5 = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery5.addBinding("xqttest.data4.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs5 = FakeMetadataFactory.createVirtualGroup("xqttest.data5", xqttest, rsQuery5); //$NON-NLS-1$
+        Table rs5 = RealMetadataFactory.createVirtualGroup("data5", xqttest, rsQuery5); //$NON-NLS-1$
 
         QueryNode rsQuery6 = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey = ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery6.addBinding("xqttest.data5.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs6 = FakeMetadataFactory.createVirtualGroup("xqttest.data6", xqttest, rsQuery6); //$NON-NLS-1$
+        Table rs6 = RealMetadataFactory.createVirtualGroup("data6", xqttest, rsQuery6); //$NON-NLS-1$
 
         
         QueryNode rsQuery7 = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs7 = FakeMetadataFactory.createVirtualGroup("xqttest.data7", xqttest, rsQuery7); //$NON-NLS-1$
+        Table rs7 = RealMetadataFactory.createVirtualGroup("data7", xqttest, rsQuery7); //$NON-NLS-1$
 
         QueryNode rsQuery8 = new QueryNode("SELECT intKey, intNum, stringNum FROM xqt.data WHERE intKey < ?"); //$NON-NLS-1$ //$NON-NLS-2$
         rsQuery8.addBinding("xqttest.data7.intNum"); //$NON-NLS-1$
-        FakeMetadataObject rs8 = FakeMetadataFactory.createVirtualGroup("xqttest.data8", xqttest, rsQuery8); //$NON-NLS-1$
+        Table rs8 = RealMetadataFactory.createVirtualGroup("data8", xqttest, rsQuery8); //$NON-NLS-1$
 
         // Create virtual elements
-        List rsElements = FakeMetadataFactory.createElements(rs, 
+        RealMetadataFactory.createElements(rs, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
-        List rsElements2 = FakeMetadataFactory.createElements(rs2, 
+        RealMetadataFactory.createElements(rs2, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
-        List rsElements3 = FakeMetadataFactory.createElements(rs3, 
+        RealMetadataFactory.createElements(rs3, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
-        List rsElements4 = FakeMetadataFactory.createElements(rs4, 
+        RealMetadataFactory.createElements(rs4, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
-        List rsElements5 = FakeMetadataFactory.createElements(rs5, 
+        RealMetadataFactory.createElements(rs5, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
-        List rsElements6 = FakeMetadataFactory.createElements(rs6, 
+        RealMetadataFactory.createElements(rs6, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
-        List rsElements7 = FakeMetadataFactory.createElements(rs7, 
+        RealMetadataFactory.createElements(rs7, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
-        List rsElements8 = FakeMetadataFactory.createElements(rs8, 
+        RealMetadataFactory.createElements(rs8, 
             new String[] { "intKey", "intNum", "stringNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
 
 
-        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("xqttest.doc1", xqttest,   createXQTPlanRecursive_5988()); //$NON-NLS-1$
-        FakeMetadataObject doc1a = FakeMetadataFactory.createVirtualGroup("xqttest.doc1a", xqttest, createXQTPlanRecursive1a_5988()); //$NON-NLS-1$
-        FakeMetadataObject doc2 = FakeMetadataFactory.createVirtualGroup("xqttest.doc2", xqttest,   createXQTPlanRecursiveSiblings()); //$NON-NLS-1$
-        FakeMetadataObject doc3 = FakeMetadataFactory.createVirtualGroup("xqttest.doc3", xqttest,   createXQTPlanRecursive3_5988()); //$NON-NLS-1$
-        FakeMetadataObject doc4 = FakeMetadataFactory.createVirtualGroup("xqttest.doc4", xqttest,   createXQTPlanChoice_6796()); //$NON-NLS-1$
-        FakeMetadataObject doc5 = FakeMetadataFactory.createVirtualGroup("xqttest.doc5", xqttest,   createChoiceDefect24651()); //$NON-NLS-1$
-        FakeMetadataObject groupDoc = FakeMetadataFactory.createVirtualGroup("xqttest.groupDoc", xqttest,   createGroupDoc()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc1", xqttest,   createXQTPlanRecursive_5988()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc1a", xqttest, createXQTPlanRecursive1a_5988()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc2", xqttest,   createXQTPlanRecursiveSiblings()); //$NON-NLS-1$
+        RealMetadataFactory.createXmlDocument("doc3", xqttest,   createXQTPlanRecursive3_5988()); //$NON-NLS-1$
+        Table doc4 = RealMetadataFactory.createXmlDocument("doc4", xqttest,   createXQTPlanChoice_6796()); //$NON-NLS-1$
+        Table doc5 = RealMetadataFactory.createXmlDocument("doc5", xqttest,   createChoiceDefect24651()); //$NON-NLS-1$
+        Table groupDoc = RealMetadataFactory.createXmlDocument("groupDoc", xqttest,   createGroupDoc()); //$NON-NLS-1$
 
-        List elemGroupDoc = FakeMetadataFactory.createElements(groupDoc, new String[] { "group", "group.pseudoID" /*, etc...*/ }, //$NON-NLS-1$ //$NON-NLS-2$
+        RealMetadataFactory.createElements(groupDoc, new String[] { "group", "group.pseudoID" /*, etc...*/ }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
         
-        List elemGroupDoc4 = FakeMetadataFactory.createElements(doc4, new String[] { "root", "root.key", "root.key.keys", "root.key.keys.nestedkey", "root.wrapper.key", "root.wrapper.key.keys", "root.wrapper.key.keys.nestedkey"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
+        RealMetadataFactory.createElements(doc4, new String[] { "root", "root.key", "root.key.keys", "root.key.keys.nestedkey", "root.wrapper.key", "root.wrapper.key.keys", "root.wrapper.key.keys.nestedkey"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
                                                                new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
         
-        List elemGroupDoc5 = FakeMetadataFactory.createElements(doc5, new String[] { "root", "root.wrapper.key" }, //$NON-NLS-1$ //$NON-NLS-2$
+        RealMetadataFactory.createElements(doc5, new String[] { "root", "root.wrapper.key" }, //$NON-NLS-1$ //$NON-NLS-2$
                                                                 new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
          
-        store.addObject(xqt);
-        store.addObject(xqtGroup);
-        store.addObjects(xqtData);
-
-        store.addObject(xqttest);
-        
-        store.addObject(objData);
-        store.addObject(objGroup);
-        store.addObject(objSupervisor);
-        store.addObject(objGroup1);
-        store.addObjects(elemXQTData);
-        store.addObjects(elemGroup);
-        store.addObjects(elemSupervisor);
-        store.addObjects(elemGroup1);
-        
-        store.addObject(rs);
-        store.addObject(rs2);
-        store.addObject(rs3);
-        store.addObject(rs4);
-        store.addObject(rs5);
-        store.addObject(rs6);
-        store.addObject(rs7);
-        store.addObject(rs8);
-        store.addObjects(rsElements);
-        store.addObjects(rsElements2);
-        store.addObjects(rsElements3);
-        store.addObjects(rsElements4);
-        store.addObjects(rsElements5);
-        store.addObjects(rsElements6);
-        store.addObjects(rsElements7);
-        store.addObjects(rsElements8);
-
-        store.addObject(doc1);
-        store.addObject(doc1a);
-        store.addObject(doc2);
-        store.addObject(doc3);
-        store.addObject(doc4);
-        store.addObject(doc5);
-        store.addObject(groupDoc);
-        store.addObjects(elemGroupDoc);
-        store.addObjects(elemGroupDoc4);
-        store.addObjects(elemGroupDoc5);
-
-        return facade;
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example2");
     }
 
-    public static FakeMetadataFacade exampleMetadataSoap1() {
-        FakeMetadataStore store = new FakeMetadataStore();
-        FakeMetadataFacade facade = new FakeMetadataFacade(store);
+    public static TransformationMetadata exampleMetadataSoap1() {
+    	MetadataStore metadataStore = new MetadataStore();
         
         // Create models
-        FakeMetadataObject taxReport = FakeMetadataFactory.createPhysicalModel("taxReport"); //$NON-NLS-1$
-        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
+        Schema taxReport = RealMetadataFactory.createPhysicalModel("taxReport", metadataStore); //$NON-NLS-1$
+        Schema xmltest = RealMetadataFactory.createVirtualModel("xmltest", metadataStore);     //$NON-NLS-1$
 
         // Create physical groups
-        FakeMetadataObject arrayOfItem = FakeMetadataFactory.createPhysicalGroup("taxReport.TaxIDs", taxReport); //$NON-NLS-1$
+        Table arrayOfItem = RealMetadataFactory.createPhysicalGroup("TaxIDs", taxReport); //$NON-NLS-1$
 
         // Create physical elements
-        List itemElements = FakeMetadataFactory.createElements(arrayOfItem, 
+        RealMetadataFactory.createElements(arrayOfItem, 
             new String[] { "ID" }, //$NON-NLS-1$
             new String[] {DataTypeManager.DefaultDataTypes.STRING});
 
 
         QueryNode rsQuerySoap = new QueryNode("SELECT ID FROM taxReport.TaxIDs"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rsSoap = FakeMetadataFactory.createVirtualGroup("xmltest.group.TaxIDs", xmltest, rsQuerySoap); //$NON-NLS-1$
+        Table rsSoap = RealMetadataFactory.createVirtualGroup("group.TaxIDs", xmltest, rsQuerySoap); //$NON-NLS-1$
 
-        List rsSoapElements = FakeMetadataFactory.createElements(rsSoap, 
+        RealMetadataFactory.createElements(rsSoap, 
         new String[] { "ID"}, //$NON-NLS-1$
         new String[] {DataTypeManager.DefaultDataTypes.STRING});        
 
-        FakeMetadataObject doc_SOAP = FakeMetadataFactory.createVirtualGroup("xmltest.docSoap", xmltest, createXMLPlanSOAP()); //$NON-NLS-1$
-        List doc_SOAPE1 = FakeMetadataFactory.createElements(doc_SOAP, new String[] { "TaxReports", "TaxReports.TaxReport", "TaxReports.TaxReport.ArrayOfTaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID.ID"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+        Table doc_SOAP = RealMetadataFactory.createXmlDocument("docSoap", xmltest, createXMLPlanSOAP()); //$NON-NLS-1$
+        RealMetadataFactory.createElements(doc_SOAP, new String[] { "TaxReports", "TaxReports.TaxReport", "TaxReports.TaxReport.ArrayOfTaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID","TaxReports.TaxReport.ArrayOfTaxID.TaxID.ID"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
                                                
-        store.addObject(taxReport);
-        store.addObject(arrayOfItem);
-        store.addObjects(itemElements);
-
-        store.addObject(xmltest);
-        store.addObject(rsSoap);
-        store.addObjects(rsSoapElements); 
-        store.addObject(doc_SOAP);
-        store.addObjects(doc_SOAPE1);
-        return facade;
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "soap1");
     }
 	
-    private static MappingNode createXQTPlanChoice_6796() {
+    private static MappingDocument createXQTPlanChoice_6796() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
 
@@ -1050,7 +873,7 @@
         return doc;
     }
     
-    private static MappingNode createChoiceDefect24651() {
+    private static MappingDocument createChoiceDefect24651() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
 
@@ -1070,7 +893,7 @@
      * Method createXQTPlanRecursive.
      * @return Object
      */
-    private static MappingNode createXQTPlanRecursive_5988() {
+    private static MappingDocument createXQTPlanRecursive_5988() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
         
@@ -1102,7 +925,7 @@
 	 * Method createXQTPlanRecursive.
 	 * @return Object
 	 */
-    private static MappingNode createXQTPlanRecursive1a_5988() {
+    private static MappingDocument createXQTPlanRecursive1a_5988() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
 
@@ -1135,7 +958,7 @@
      * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
      * @return Object
      */
-    private static MappingNode createXQTPlanRecursive3_5988() {   
+    private static MappingDocument createXQTPlanRecursive3_5988() {   
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
 
@@ -1160,7 +983,7 @@
     }
     
     
-    private static MappingNode createXQTPlanRecursiveSiblings() {
+    private static MappingDocument createXQTPlanRecursiveSiblings() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("recursiveTest")); //$NON-NLS-1$
 
@@ -1184,7 +1007,7 @@
 	 * Method createXMLPlanNested.
 	 * @return MappingNode root of mapping doc
 	 */
-	private static MappingNode createXMLPlanNested() {
+	private static MappingDocument createXMLPlanNested() {
 
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
@@ -1227,7 +1050,7 @@
     /**
      * for defect 9929
      */
-    static MappingNode createXMLPlanNested(String queryGroup) {
+    static MappingDocument createXMLPlanNested(String queryGroup) {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = new MappingElement("Catalogs"); //$NON-NLS-1$
         doc.addChildElement(root);
@@ -1268,7 +1091,7 @@
     /**
      * for defect 12260
      */
-    private static MappingNode createXMLPlanCorrelatedSubqueryTransform() {
+    private static MappingDocument createXMLPlanCorrelatedSubqueryTransform() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
         
@@ -1291,7 +1114,7 @@
         return doc;  
     }
 
-    private static MappingNode createXMLPlan_9893() {
+    private static MappingDocument createXMLPlan_9893() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
         
@@ -1307,7 +1130,7 @@
     /** 
      * DEFECT 8373
      */
-    private static Object createXMLPlan_defect8373() {
+    private static MappingDocument createXMLPlan_defect8373() {
         
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -1327,7 +1150,7 @@
     /** 
      * DEFECT 8373
      */
-    private static Object createXMLPlan_defect8373a() {        
+    private static MappingDocument createXMLPlan_defect8373a() {        
         MappingDocument doc = new MappingDocument(true);
         
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -1348,7 +1171,7 @@
     /** 
      * DEFECT 8373
      */
-    private static Object createXMLPlan_defect8373b() {
+    private static MappingDocument createXMLPlan_defect8373b() {
         
         MappingDocument doc = new MappingDocument(true);
         
@@ -1367,7 +1190,7 @@
         return doc;
     }    
     
-    private static MappingNode createXMLPlanNested2() {
+    private static MappingDocument createXMLPlanNested2() {
         
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -1408,7 +1231,7 @@
     }
 
 	/** nested with sibling*/
-	private MappingNode createXMLPlanNested2c() {
+	private static MappingDocument createXMLPlanNested2c() {
         
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -1445,13 +1268,13 @@
 	}
 
 
-    private static MappingNode createXMLPlanNested2a() {
+    private static MappingDocument createXMLPlanNested2a() {
         
         MappingDocument doc = new MappingDocument(true);
         
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
 
-        root.setStagingTables(Arrays.asList(new String[] {"tempGroup.orders", "tempGroup.orders2"})); //$NON-NLS-1$ //$NON-NLS-2$
+        root.setStagingTables(Arrays.asList(new String[] {"xmltest.doc9a.tempGroup.orders", "xmltest.doc9a.tempGroup.orders2"})); //$NON-NLS-1$ //$NON-NLS-2$
         
         MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
         MappingElement items = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
@@ -1489,7 +1312,7 @@
     }
 
     // for doc 9b - test temp group w/ bindings
-    private static MappingNode createXMLPlanNested2b() {
+    private static MappingDocument createXMLPlanNested2b() {
         
         MappingDocument doc = new MappingDocument(true);
         
@@ -1538,12 +1361,12 @@
         return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$
     }
 
-    private static MappingNode createXMLPlanNestedWithChoiceFor5266() {
+    private static MappingDocument createXMLPlanNestedWithChoiceFor5266() {
         MappingCriteriaNode critNode = new MappingCriteriaNode("xmltest.orders.orderStatus = 'shipped'", true); //$NON-NLS-1$
         return baseXMLPlanNestedWithLookupChoice("xmltest.orders.orderStatus = 'processing'", critNode); //$NON-NLS-1$        
     }
     
-    private static MappingNode createXMLPlanNestedWithLookupChoice() {
+    private static MappingDocument createXMLPlanNestedWithLookupChoice() {
         MappingCriteriaNode critNode = new MappingCriteriaNode(); 
         MappingElement defaltElement = critNode.addChildElement(new MappingElement("OtherOrder"));//$NON-NLS-1$
         defaltElement.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum"));//$NON-NLS-1$ //$NON-NLS-2$                
@@ -1601,7 +1424,7 @@
     }
 
 
-    private static MappingNode createTestAttributePlan() {
+    private static MappingDocument createTestAttributePlan() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("FixedValueTest")); //$NON-NLS-1$
         
@@ -1624,7 +1447,7 @@
         return doc;
     }
 
-    private static Object createUpdateTestDoc() {
+    private static MappingDocument createUpdateTestDoc() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("UpdateTest")); //$NON-NLS-1$
         
@@ -1634,7 +1457,7 @@
         return doc;
     }
 
-    private static MappingNode createXMLPlanWithComment(){
+    private static MappingDocument createXMLPlanWithComment(){
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Root")); //$NON-NLS-1$
         
@@ -1667,13 +1490,13 @@
         return doc;
     }
     
-    private static MappingNode createXMLPlan2(boolean format, boolean testNillable, int cardinality ) {
+    private static MappingDocument createXMLPlan2(boolean format, boolean testNillable, int cardinality ) {
         MappingDocument doc = new MappingDocument(format);
         doc.addChildElement(createXMLPlan1Unformatted(testNillable, cardinality));
         return doc;
     }    
     
-    private static MappingNode createXMLPlanSOAP() {
+    private static MappingDocument createXMLPlanSOAP() {
 
         Namespace namespace = new Namespace("ORG", "http://www.mm.org/dummy"); //$NON-NLS-1$ //$NON-NLS-2$
 
@@ -1732,7 +1555,7 @@
         return root;                                
     }
 
-    private static MappingNode createXMLPlanDefect13617() {
+    private static MappingDocument createXMLPlanDefect13617() {
 
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -1755,7 +1578,7 @@
     }     
     
 
-    private static MappingNode createXMLPlan2(int numChoices, int numDefaultChoice, boolean exception_on_Default) {
+    private static MappingDocument createXMLPlan2(int numChoices, int numDefaultChoice, boolean exception_on_Default) {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
         MappingElement cat = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
@@ -1818,7 +1641,7 @@
         return doc;                                
     }
 
-    private static MappingNode createXMLPlanUltraAdvanced() {
+    private static MappingDocument createXMLPlanUltraAdvanced() {
 
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -1860,10 +1683,8 @@
         
         return doc;        
     }
-    
-  
 
-    private static MappingNode createXMLPlanUltraAdvancedExceptionOnDefault() {
+    private static MappingDocument createXMLPlanUltraAdvancedExceptionOnDefault() {
 
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -1898,7 +1719,7 @@
     }
 
     //advanced tests of namespace declarations, use and scope; also fixed values
-    private static MappingNode createXMLPlanAdvanced() {
+    private static MappingDocument createXMLPlanAdvanced() {
         //add to previous example
         MappingDocument doc = createXMLPlanWithDefaults();
         MappingElement root = (MappingElement)doc.getRootNode();
@@ -1938,7 +1759,7 @@
      * Method createXMLPlanNested.
      * @return MappingNode root of mapping doc
      */
-    private static MappingNode createXMLPlanMultipleDocs() {
+    private static MappingDocument createXMLPlanMultipleDocs() {
 
         MappingDocument doc = new MappingDocument(true);
         
@@ -1966,7 +1787,7 @@
         return doc;  
     }
 
-    private static MappingNode createXMLPlanRecursive(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+    private static MappingDocument createXMLPlanRecursive(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
         
@@ -1997,7 +1818,7 @@
     /*
      * Recursion root mapping class is anchored at sequence node instead of "Employee" node
      */
-    private static MappingNode createXMLPlanRecursiveA(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+    private static MappingDocument createXMLPlanRecursiveA(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("OrgHierarchy")); //$NON-NLS-1$
 
@@ -2027,8 +1848,7 @@
         return doc;  
     }
     
-    
-    private static MappingNode createXMLPlanRecursiveStaging(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+    private static MappingDocument createXMLPlanRecursiveStaging(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
         
         MappingDocument doc = new MappingDocument(true);
         
@@ -2060,7 +1880,7 @@
         return doc;  
     }
     
-    private static MappingNode createXMLPlanRecursive2(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
+    private static MappingDocument createXMLPlanRecursive2(boolean useRecursiveCriteria, int recursionLimit, boolean exceptionOnLimit) {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Employees")); //$NON-NLS-1$
 
@@ -2089,7 +1909,7 @@
 
     //this is for testing how "optional" XML elements are included/
     //excluded from the result document
-    private static MappingNode createXMLPlan_defect8917() {
+    private static MappingDocument createXMLPlan_defect8917() {
         
         Namespace namespace1 = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
         
@@ -2192,7 +2012,7 @@
     /*
      * Test of identically named nodes
      */
-    private static MappingNode createXMLPlan_defect9446() {
+    private static MappingDocument createXMLPlan_defect9446() {
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
 
@@ -2207,7 +2027,7 @@
         return doc;                                
     }
     
-    private static MappingNode createXMLPlan_defect_9530() {        
+    private static MappingDocument createXMLPlan_defect_9530() {        
         Namespace namespace = new Namespace("mm", "http://www.duh.org/duh"); //$NON-NLS-1$ //$NON-NLS-2$
         Namespace namespace2 = new Namespace("mm", "http://www.duh2.org/duh2"); //$NON-NLS-1$ //$NON-NLS-2$
         Namespace namespace3 = new Namespace("mm2", "http://www.duh3.org/duh3"); //$NON-NLS-1$ //$NON-NLS-2$
@@ -2231,7 +2051,7 @@
         return doc;                              
     }    
     
-    private static MappingNode createGroupDoc() {
+    private static MappingDocument createGroupDoc() {
         MappingDocument doc = new MappingDocument(true);
         
         MappingElement root = doc.addChildElement(new MappingElement("group")); //$NON-NLS-1$
@@ -2262,391 +2082,247 @@
         group1.setMaxOccurrs(-1);
         return doc;         
     }
-
      
-    // Helper to create a list of elements - used in creating sample data
-    private static List createElements(List elementIDs) { 
-        List elements = new ArrayList();
-        for(int i=0; i<elementIDs.size(); i++) {
-            FakeMetadataObject elementID = (FakeMetadataObject) elementIDs.get(i);            
-            ElementSymbol element = new ElementSymbol(elementID.getName());
-            elements.add(element);
-        }        
-        
-        return elements;
-    }    
-
-    public static FakeDataManager exampleDataManager(FakeMetadataFacade metadata) {
+    public static FakeDataManager exampleDataManager(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) {
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }                    
 
-    public static FakeDataManager exampleDataManager15117(FakeMetadataFacade metadata) {
+    public static FakeDataManager exampleDataManager15117(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", " Lamp ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "  Screw  driver  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", " Goat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", " Lamp ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "002", "  Screw  driver  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", " Goat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }     
 
     /** unusual characters in text */
-    public static FakeDataManager exampleDataManager15117a(FakeMetadataFacade metadata) {
+    public static FakeDataManager exampleDataManager15117a(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "\t \n\r", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "  >Screw< \n driver  &", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", " >>\rGoat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", "\t \n\r", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "002", "  >Screw< \n driver  &", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", " >>\rGoat ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }    
     
-    public static FakeDataManager exampleDataManager14905(FakeMetadataFacade metadata) {
+    public static FakeDataManager exampleDataManager14905(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { " ", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "  ", "  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { " ", " ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { " ", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "  ", "  ", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { " ", " ", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }     
     
-    public static FakeDataManager exampleDataManager13617(FakeMetadataFacade metadata) {
+    public static FakeDataManager exampleDataManager13617(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", null, new Integer(1), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ 
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "004", null, new Integer(1), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ 
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
-        
+
         return dataMgr;
     }     
     
-    public static FakeDataManager exampleDataManagerNested(FakeMetadataFacade metadata) {
+    public static FakeDataManager exampleDataManagerNested(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-
-            // Group stock.supplier
-            FakeMetadataObject groupID2 = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
-
-            // Group stock.orders
-            FakeMetadataObject groupID3 = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
-
-            // Group stock.item_supplier
-            FakeMetadataObject groupID1_2join = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
-
-            // Group stock.employees
-            FakeMetadataObject groupEmployees = (FakeMetadataObject) metadata.getGroupID("stock.employees"); //$NON-NLS-1$
-
-            // Items
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
-            // Supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupID2);
-            List supplierElementSymbols = createElements(elementIDs);
-
-            // Orders
-            elementIDs = metadata.getElementIDsInGroupID(groupID3);
-            List ordersElementSymbols = createElements(elementIDs);
-
-            // Item_supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupID1_2join);
-            List itemSupplierElementSymbols = createElements(elementIDs);
-
-            // Employees
-            elementIDs = metadata.getElementIDsInGroupID(groupEmployees);
-            List employeeSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
             dataMgr.registerTuples(
-                groupID1_2join,
-                itemSupplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    } );    
+                metadata,
+                "stock.item_supplier", new List[] { 
+					    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    } );    
 
 
             dataMgr.registerTuples(
-                groupID2,
-                supplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.suppliers", new List[] { 
+					    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
             dataMgr.registerTuples(
-                groupID3,
-                ordersElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "1", "002", "54", "Nugent Co.", "10/23/01", new Integer(5), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "2", "001", "52", "Biff's Stuff", "12/31/01", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "3", "003", "56", "Microsoft", "02/31/02", new Integer(12), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "4", "003", "56", "Microsoft", "05/31/02", new Integer(9), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "5", "002", "56", "Microsoft", "06/01/02", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "6", "002", "56", "Microsoft", "07/01/02", new Integer(1), null } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "7", "002", "56", "bad data, shouldn't see", "07/01/02", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    } );    
+                metadata,
+                "stock.orders", new List[] { 
+					    Arrays.asList( new Object[] { "1", "002", "54", "Nugent Co.", "10/23/01", new Integer(5), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "2", "001", "52", "Biff's Stuff", "12/31/01", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "3", "003", "56", "Microsoft", "02/31/02", new Integer(12), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "4", "003", "56", "Microsoft", "05/31/02", new Integer(9), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "5", "002", "56", "Microsoft", "06/01/02", new Integer(87), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "6", "002", "56", "Microsoft", "07/01/02", new Integer(1), null } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "7", "002", "56", "bad data, shouldn't see", "07/01/02", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    } );    
 
             dataMgr.registerTuples(
-                groupEmployees,
-                employeeSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "01", "1", null, "Ted", "Nugent" } ), //ceo, Nugent Co. //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-                    Arrays.asList( new Object[] { "02", "1", "01", "Bill", "Squier" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "03", "1", "01", "John", "Smith" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "04", "1", "02", "Leland", "Sklar" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "05", "1", "03", "Kevin", "Moore" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "06", "1", "04", "John", "Zorn" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "07", "2", null, "Geoff", "Tate" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-                    Arrays.asList( new Object[] { "08", "2", "07", "Les", "Claypool" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "09", "2", "08", "Meat", "Loaf" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "10", "2", "08", "Keith", "Sweat" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "11", "1", "06", "Mike", "Patton" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "12", "1", "06", "Devin", "Townsend" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "13", "1", "11", "Puffy", "Bordin" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    } );    
+                metadata,
+                "stock.employees", new List[] { 
+					    Arrays.asList( new Object[] { "01", "1", null, "Ted", "Nugent" } ), //ceo, Nugent Co. //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+					    Arrays.asList( new Object[] { "02", "1", "01", "Bill", "Squier" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "03", "1", "01", "John", "Smith" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "04", "1", "02", "Leland", "Sklar" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "05", "1", "03", "Kevin", "Moore" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "06", "1", "04", "John", "Zorn" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "07", "2", null, "Geoff", "Tate" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+					    Arrays.asList( new Object[] { "08", "2", "07", "Les", "Claypool" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "09", "2", "08", "Meat", "Loaf" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "10", "2", "08", "Keith", "Sweat" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "11", "1", "06", "Mike", "Patton" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "12", "1", "06", "Devin", "Townsend" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "13", "1", "11", "Puffy", "Bordin" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    } );    
 
 
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
-        
+
         return dataMgr;
     }                    
 
-	private FakeDataManager exampleDataManagerNestedWithSibling(FakeMetadataFacade metadata) {
+	static FakeDataManager exampleDataManagerNestedWithSibling(QueryMetadataInterface metadata) {
 		FakeDataManager dataMgr = new FakeDataManager();
     
 		try { 
-			// Group stock.items
-			FakeMetadataObject groupID1 = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
 
-			// Group stock.supplier
-			FakeMetadataObject groupID2 = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
-
-			// Group stock.orders
-			FakeMetadataObject groupID3 = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
-
-			// Group stock.item_supplier
-			FakeMetadataObject groupID1_2join = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
-
-			// Group stock.item_order
-			FakeMetadataObject groupID1_3join = (FakeMetadataObject) metadata.getGroupID("stock.item_order"); //$NON-NLS-1$
-
-			// Items
-			List elementIDs = metadata.getElementIDsInGroupID(groupID1);
-			List elementSymbols = createElements(elementIDs);
-
-			// Supplier
-			elementIDs = metadata.getElementIDsInGroupID(groupID2);
-			List supplierElementSymbols = createElements(elementIDs);
-
-			// Orders
-			elementIDs = metadata.getElementIDsInGroupID(groupID3);
-			List ordersElementSymbols = createElements(elementIDs);
-
-			// Item_supplier
-			elementIDs = metadata.getElementIDsInGroupID(groupID1_2join);
-			List itemSupplierElementSymbols = createElements(elementIDs);
-
-			// Item_order
-			elementIDs = metadata.getElementIDsInGroupID(groupID1_3join);
-			List itemOrderElementSymbols = createElements(elementIDs);
-        
 			dataMgr.registerTuples(
-				groupID1,
-				elementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
+				metadata,
+				"stock.items", new List[] { 
+						Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						} );    
 
 			dataMgr.registerTuples(
-				groupID1_2join,
-				itemSupplierElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					} );    
+				metadata,
+				"stock.item_supplier", new List[] { 
+						Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						} );    
 
 
 			dataMgr.registerTuples(
-				groupID2,
-				supplierElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
+				metadata,
+				"stock.suppliers", new List[] { 
+						Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						} );    
 
 			dataMgr.registerTuples(
-				groupID3,
-				ordersElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "1", "KMart", "12345" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "2", "Sun", "94040" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "3", "Cisco", "94041" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "4", "Doc", "94042" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "5", "Excite", "21098" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "6", "Yahoo", "94043" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					Arrays.asList( new Object[] { "7", "Inktomi", "94044" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-					} );    
+				metadata,
+				"stock.orders", new List[] { 
+						Arrays.asList( new Object[] { "1", "KMart", "12345" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "2", "Sun", "94040" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "3", "Cisco", "94041" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "4", "Doc", "94042" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "5", "Excite", "21098" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "6", "Yahoo", "94043" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						Arrays.asList( new Object[] { "7", "Inktomi", "94044" } ),  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+						} );    
 
 			dataMgr.registerTuples(
-				groupID1_3join,
-				itemOrderElementSymbols,
-                
-				new List[] { 
-					Arrays.asList( new Object[] { "001", "1" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "2" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "3" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "001", "4" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "5" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "002", "6" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					Arrays.asList( new Object[] { "003", "7" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-					} );    
+				metadata,
+				"stock.item_order", new List[] { 
+						Arrays.asList( new Object[] { "001", "1" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "001", "2" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "001", "3" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "001", "4" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "002", "5" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "002", "6" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						Arrays.asList( new Object[] { "003", "7" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+						} );    
 
 
 
-		} catch(Throwable e) { 
-			e.printStackTrace();
-			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-		}
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
+        }
         
 		return dataMgr;
 	}                    
@@ -2655,43 +2331,30 @@
      * Returned with some null values in the tuples, to test default/fixed attributes of nodes
      * as well as nillable nodes
      */
-    private FakeDataManager exampleDataManagerWithNulls(FakeMetadataFacade metadata) {
+    private FakeDataManager exampleDataManagerWithNulls(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }                    
 
-    public static FakeDataManager exampleDataManagerForSoap1(FakeMetadataFacade metadata, boolean makeEmpty) {
+    public static FakeDataManager exampleDataManagerForSoap1(QueryMetadataInterface metadata, boolean makeEmpty) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("taxReport.TaxIDs"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            List[] tuples = null;
+            List<?>[] tuples = null;
             if (makeEmpty){
                 tuples = new List[0];
             } else {
@@ -2703,93 +2366,60 @@
             }
         
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                tuples );    
+                metadata,
+                "taxReport.TaxIDs", tuples );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     } 
 
-    /** data has a null value */
-    private FakeDataManager exampleDataManager_8917(FakeMetadataFacade metadata) {
+    /** data has a null value 
+     * @throws TeiidComponentException 
+     * @throws QueryResolverException */
+    private FakeDataManager exampleDataManager_8917(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
         FakeDataManager dataMgr = new FakeDataManager();
     
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
+        dataMgr.registerTuples(
+            metadata,
+            "stock.items", new List[] { 
+				    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+				    } );    
         return dataMgr;
     } 
 
     /** data has a NON-EMPTY WHITESPACE string */
-    private FakeDataManager exampleDataManager_8917a(FakeMetadataFacade metadata) {
+    private FakeDataManager exampleDataManager_8917a(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", " ", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }
 
-    /** data has an EMPTY STRING */
-    private FakeDataManager exampleDataManager_8917b(FakeMetadataFacade metadata) {
+    /** data has an EMPTY STRING 
+     * @throws TeiidComponentException 
+     * @throws QueryResolverException */
+    private FakeDataManager exampleDataManager_8917b(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
         FakeDataManager dataMgr = new FakeDataManager();
     
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
+        dataMgr.registerTuples(
+            metadata,
+            "stock.items", new List[] { 
+				    Arrays.asList( new Object[] { "001", "", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				    } );    
         
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
         return dataMgr;
     }    
     
@@ -2797,30 +2427,19 @@
 	 * Duplicate records in data
 	 * @param metadata
 	 * @return FakeDataManager
+	 * @throws TeiidComponentException 
+	 * @throws QueryResolverException 
 	 */
-	private FakeDataManager exampleDataManagerWithDuplicates(FakeMetadataFacade metadata) {
+	private FakeDataManager exampleDataManagerWithDuplicates(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
 		FakeDataManager dataMgr = new FakeDataManager();
     
-		try { 
-			// Group stock.items
-			FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-			List elementIDs = metadata.getElementIDsInGroupID(groupID);
-			List elementSymbols = createElements(elementIDs);
-        
-			dataMgr.registerTuples(
-				groupID,
-				elementSymbols,
-                
-				new List[] { 
+		dataMgr.registerTuples(
+			metadata,
+			"stock.items", new List[] { 
 					Arrays.asList( new Object[] { "001", "Goat", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 					Arrays.asList( new Object[] { "002", "Screwdriver",new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 					Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 					} );    
-
-		} catch(Throwable e) { 
-			e.printStackTrace();
-			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-		}
         
 		return dataMgr;
 	}                    
@@ -2830,94 +2449,65 @@
 	 * Duplicate records in data to test more than two order by elements at the same depth
 	 * @param metadata
 	 * @return FakeDataManager
+	 * @throws TeiidComponentException 
+	 * @throws QueryResolverException 
      */
-	private FakeDataManager exampleDataManagerWithDuplicates1(FakeMetadataFacade metadata) {
+	private FakeDataManager exampleDataManagerWithDuplicates1(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
 		FakeDataManager dataMgr = new FakeDataManager();
     
-		try { 
-			// Group stock.items
-			FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-			List elementIDs = metadata.getElementIDsInGroupID(groupID);
-			List elementSymbols = createElements(elementIDs);
-        
-			dataMgr.registerTuples(
-				groupID,
-				elementSymbols,
-                
-				new List[] { 
+		dataMgr.registerTuples(
+			metadata,
+			"stock.items", new List[] { 
 					Arrays.asList( new Object[] { "001", "Goat", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 					Arrays.asList( new Object[] { "003", "Screwdriver",new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 					Arrays.asList( new Object[] { "001", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 					} );    
 
-		} catch(Throwable e) { 
-			e.printStackTrace();
-			fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-		}
-        
 		return dataMgr;
 	}                   
 		
     /**
      * Deluxe example
+     * @throws TeiidComponentException 
+     * @throws QueryResolverException 
      */
-    private FakeDataManager exampleDataManagerDuJour(FakeMetadataFacade metadata) {
+    private FakeDataManager exampleDataManagerDuJour(QueryMetadataInterface metadata) throws QueryResolverException, TeiidComponentException {
         FakeDataManager dataMgr = new FakeDataManager();
     
-        try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
-            dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", "Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "006", "Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
-
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        
+        dataMgr.registerTuples(
+            metadata,
+            "stock.items", new List[] { 
+				    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+				    Arrays.asList( new Object[] { "002", "Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				    Arrays.asList( new Object[] { "004", "Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
+				    Arrays.asList( new Object[] { "006", "Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				    } );    
         return dataMgr;
     }   
 
-    public static FakeDataManager exampleXQTDataManager(FakeMetadataFacade metadata) throws Exception {
+    public static FakeDataManager exampleXQTDataManager(QueryMetadataInterface metadata) throws Exception {
         FakeDataManager dataMgr = new FakeDataManager();
     
         // Group stock.items
-        FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("xqt.data"); //$NON-NLS-1$
-        List elementIDs = metadata.getElementIDsInGroupID(groupID);
-        List xqtData = createElements(elementIDs);
-    
         dataMgr.registerTuples(
-            groupID,
-            xqtData,
-            
-            new List[] { 
-                Arrays.asList( new Object[] { new Integer(1),  new Integer(-2), "-2" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(2),  new Integer(-1), null } ),        
-                Arrays.asList( new Object[] { new Integer(3),  null,            "0" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(4),  new Integer(1),  "1" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(5),  new Integer(2),  "2" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(6),  new Integer(3),  "3" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(7),  new Integer(4),  "4" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(8),  new Integer(5),  null } ),        
-                Arrays.asList( new Object[] { new Integer(9),  null,            "6" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(10), new Integer(7),  "7" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(11), new Integer(8),  "8" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(12), new Integer(9),  "9" } ),         //$NON-NLS-1$
-                Arrays.asList( new Object[] { new Integer(13), new Integer(10), "10" } ),         //$NON-NLS-1$
-                } );    
+            metadata,
+            "xqt.data", new List[] { 
+				    Arrays.asList( new Object[] { new Integer(1),  new Integer(-2), "-2" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(2),  new Integer(-1), null } ),        
+				    Arrays.asList( new Object[] { new Integer(3),  null,            "0" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(4),  new Integer(1),  "1" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(5),  new Integer(2),  "2" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(6),  new Integer(3),  "3" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(7),  new Integer(4),  "4" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(8),  new Integer(5),  null } ),        
+				    Arrays.asList( new Object[] { new Integer(9),  null,            "6" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(10), new Integer(7),  "7" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(11), new Integer(8),  "8" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(12), new Integer(9),  "9" } ),         //$NON-NLS-1$
+				    Arrays.asList( new Object[] { new Integer(13), new Integer(10), "10" } ),         //$NON-NLS-1$
+				    } );    
 
         return dataMgr;
     }                    
@@ -2930,16 +2520,16 @@
         return command;
     }
 
-    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, FakeMetadataFacade metadata, FakeDataManager dataMgr) throws Exception{
+    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, QueryMetadataInterface metadata, FakeDataManager dataMgr) throws Exception{
         return helpTestProcess(sql, expectedDoc, metadata, dataMgr, null);
     }
 
-    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, FakeMetadataFacade metadata, FakeDataManager dataMgr, Class expectedException) throws Exception{
+    static ProcessorPlan helpTestProcess(String sql, String expectedDoc, QueryMetadataInterface metadata, FakeDataManager dataMgr, Class<?> expectedException) throws Exception{
 
         return helpTestProcess(sql, metadata, dataMgr, expectedException, new DefaultCapabilitiesFinder(), expectedDoc);
     }
 
-    static ProcessorPlan helpTestProcess(String sql, FakeMetadataFacade metadata, FakeDataManager dataMgr, Class expectedException, CapabilitiesFinder capFinder, String... expectedDoc) throws Exception{
+    static ProcessorPlan helpTestProcess(String sql, QueryMetadataInterface metadata, FakeDataManager dataMgr, Class<?> expectedException, CapabilitiesFinder capFinder, String... expectedDoc) throws Exception{
         Command command = helpGetCommand(sql, metadata);
         AnalysisRecord analysisRecord = new AnalysisRecord(false, DEBUG);
 
@@ -2951,7 +2541,7 @@
             if(DEBUG) {
                 System.out.println(analysisRecord.getDebugLog());
             }
-            List[] expected = new List[expectedDoc.length];
+            List<?>[] expected = new List[expectedDoc.length];
             for (int i = 0; i < expectedDoc.length; i++) {
 				expected[i] = Arrays.asList(expectedDoc[i]);
 			}
@@ -2976,7 +2566,7 @@
     // =============================================================================================
 
     @Test public void test1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3003,7 +2593,7 @@
     }
     
     @Test public void testOrderBy1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3030,7 +2620,7 @@
     }
 
     @Test public void testOrderBy1a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3057,7 +2647,7 @@
     }
     
     @Test public void testOrderBy1b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3084,7 +2674,7 @@
     }
                
     @Test public void testOrderBy2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3111,7 +2701,7 @@
     }
     
     @Test public void testOrderBy3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3176,7 +2766,7 @@
     }   
     
     @Test public void testOrderBy3a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3241,7 +2831,7 @@
     }      
     
     @Test public void testOrderBy4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -3261,7 +2851,7 @@
     }     
      
     @Test public void testOrderBy5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
          String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3288,7 +2878,7 @@
     } 
     
     @Test public void testOrderBy6() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3396,14 +2986,14 @@
    
     //order by with temp group at the root    
     @Test public void testOrderBy7() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         helpTestProcess("SELECT * FROM xmltest.doc9a ORDER BY ItemID DESC", EXPECTED_ORDERED_DOC9A, metadata, dataMgr);         //$NON-NLS-1$
     }   
            
     //order by with multiple elements and criteria with long name, short name doesn't work
     @Test public void testOrderBy8() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3474,7 +3064,7 @@
 
     /*    
     @Test public void testOrderBy9() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata();
+        QueryMetadataInterface metadata = exampleMetadata();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = "";
           
@@ -3487,7 +3077,7 @@
     */
   
     @Test public void testOrderBy10() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -3511,13 +3101,13 @@
     }     
     
      @Test public void testOrderBy11() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         helpTestProcess("SELECT * FROM xmltest.doc9a WHERE ItemID='001' OR ItemID='002' OR ItemID='003' ORDER BY ItemID DESC", EXPECTED_ORDERED_DOC9A, metadata, dataMgr);         //$NON-NLS-1$
     }   
 
     @Test public void testOrderBy13() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -3545,7 +3135,7 @@
     }
         
     @Test public void testOrderBy14() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3652,7 +3242,7 @@
     }   
      
     @Test public void testOrderBy15() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -3681,7 +3271,7 @@
 
     /** test null elements*/
     @Test public void testOrderBy17() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
         
         String expectedDoc = 
@@ -3710,7 +3300,7 @@
     
     /**  test duplicate elements*/
     @Test public void testOrderBy18() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithDuplicates(metadata);
         
         String expectedDoc = 
@@ -3739,7 +3329,7 @@
     
     /**  test more than two parallel elements*/
     @Test public void testOrderBy19() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithDuplicates1(metadata);
         
         String expectedDoc = 
@@ -3767,7 +3357,7 @@
     }
     
     @Test public void testOrderBy20() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc =
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -3825,7 +3415,7 @@
      * ORDER BY clause of an XML doc query
      */
     @Test public void testOrderBy_defect9803() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
                
         try {
@@ -3841,7 +3431,7 @@
         
     //defect 8130
     @Test public void test1CriteriaWithUnmappedElementFails() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Catalog = 'something'", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$
@@ -3849,14 +3439,14 @@
 
     //defect 8130
     @Test public void test1CriteriaWithUnmappedElementFails2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc1 WHERE Item = 'something'", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$
     }  
     
     @Test public void testNested() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4062,7 +3652,7 @@
             "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
             
     @Test public void testNested2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2;
         helpTestProcess("SELECT * FROM xmltest.doc9", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
@@ -4073,14 +3663,14 @@
      * selects from B
      */
     @Test public void testNested2aTempGroup() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2;
         helpTestProcess("SELECT * FROM xmltest.doc9a", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
     }   
 
     @Test public void testNested2aTempGroupCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4160,7 +3750,7 @@
 
     /** defect 13172, CSE Case 1811 */
     @Test public void testNested2aTempGroupCompoundCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4241,7 +3831,7 @@
 
     /** defect 13172, CSE Case 1811 */
     @Test public void testNested2aTempGroupCompoundCriteria1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4322,7 +3912,7 @@
 
     /** defect 13172, CSE Case 1811 */
     @Test public void testNested2aTempGroupCompoundCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4408,7 +3998,7 @@
     }
 
     @Test public void testNested2cTempGroup() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_3;
         helpTestProcess("SELECT * FROM xmltest.doc9a WHERE ItemID = '001'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
@@ -4419,7 +4009,7 @@
      * some ancestor mapping classes ( we no longer support bindings on staging tables)
      */
     public void defer_testNested2bTempGroup() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2;
         helpTestProcess("SELECT * FROM xmltest.doc9b", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
@@ -4427,7 +4017,7 @@
 
     @Test public void testNested2WithCriteria() throws Exception {
 
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4484,7 +4074,7 @@
      * @see #testNested2WithCriteria2a
      */
     @Test public void testNested2WithCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4544,7 +4134,7 @@
      * @see #testNested2WithCriteria2a
      */
     @Test public void testNested2WithCriteria2_defect9802() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4594,7 +4184,7 @@
      * @see #testNested2WithCriteria2
      */
     @Test public void testNested2WithCriteria2_function() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc =
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //$NON-NLS-1$
@@ -4650,7 +4240,7 @@
      * the criteria is actually specified on.</p>
      */
     @Test public void testNested2WithCriteria2a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4699,7 +4289,7 @@
 
 
     @Test public void testNested2WithContextCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4746,7 +4336,7 @@
     }
 
     @Test public void testNested2WithContextCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4799,7 +4389,7 @@
     }
 
     @Test public void testNested2WithContextCriteria3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -4892,7 +4482,7 @@
 
 
     @Test public void testNested2WithContextCriteria4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
 
@@ -4900,7 +4490,7 @@
     }
 
     @Test public void testNested2WithContextCriteria4a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
 
@@ -4908,7 +4498,7 @@
     }
 
     @Test public void testNested2WithContextCriteria4b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_4;
 
@@ -4994,7 +4584,7 @@
             "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
 
     @Test public void testNested2WithContextCriteria5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
 
@@ -5002,7 +4592,7 @@
     }
 
     @Test public void testNested2WithContextCriteria5a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
 
@@ -5010,7 +4600,7 @@
     }
 
     @Test public void testNested2WithContextCriteria5b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_5;
 
@@ -5031,19 +4621,17 @@
     }
 
     @Test public void testNested2WithContextCriteria5Fail() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = ""; //doesn't matter //$NON-NLS-1$
 
-        boolean shouldSucceed = false;
-        Class expectedException = QueryPlannerException.class;
-        String shouldFailMsg = "expected failure since two different contexts were specified in conjunct"; //$NON-NLS-1$
+        Class<?> expectedException = QueryPlannerException.class;
 
         helpTestProcess("SELECT * FROM xmltest.doc9 WHERE context(Item, OrderID)='5' OR context(SupplierID, OrderID)='2'", expectedDoc, metadata, dataMgr, expectedException);         //$NON-NLS-1$
     }
 
     @Test public void testNested2WithContextCriteria6() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5056,7 +4644,7 @@
     }
 
     @Test public void testNested2WithContextCriteria6b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5106,14 +4694,14 @@
             "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
 
     @Test public void testNested2WithContextCriteria7() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
         helpTestProcess("SELECT * FROM xmltest.doc9 WHERE CONTEXT(SupplierID, OrderID)='5' AND context(OrderID, OrderID)='5'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
     }
 
     @Test public void testNested2WithContextCriteria7b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
         String query = "SELECT * FROM xmltest.doc9 WHERE CONTEXT(Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID, " //$NON-NLS-1$
@@ -5122,7 +4710,7 @@
     }
 
     @Test public void testNested2WithContextCriteria7c() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = EXPECTED_DOC_NESTED_2_WITH_CONTEXT_CRITERIA_7;
         String query = "SELECT * FROM xmltest.doc9 WHERE CONTEXT(Catalogs.Catalog.Items.Item.Suppliers.Supplier.SupplierID, " //$NON-NLS-1$
@@ -5134,7 +4722,7 @@
      * per defect 7333
      */
     @Test public void testNested2WithContextCriteria_7333() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5173,7 +4761,7 @@
      * per defect 7333
      */
     @Test public void testNested2WithContextCriteria_7333b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5212,7 +4800,7 @@
      * per defect 7333
      */
     @Test public void testNested2WithContextCriteria_7333c() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5228,7 +4816,7 @@
      * per defect 7333
      */
     @Test public void testNested2WithContextCriteria_7333d() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5244,7 +4832,7 @@
      * Select a single item, and then limit the suppliers based on an order #
      */
     @Test public void testNested2WithContextCriteria8() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5280,7 +4868,7 @@
     }
 
     @Test public void testNestedWithChoice() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5369,7 +4957,7 @@
      * Does not use 'context' operator
      */
     @Test public void testNestedWithChoiceAndCriteria2_6796() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5413,7 +5001,7 @@
      * Uses the 'context' operator
      */
     @Test public void testNestedWithChoiceAndCriteria2a_6796() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5491,7 +5079,7 @@
      * Does not use 'context' operator
      */
     @Test public void testNestedWithLookupChoice() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -5533,7 +5121,7 @@
     }    
     
     @Test public void test1Unformatted() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +  //$NON-NLS-1$
@@ -5563,7 +5151,7 @@
     // jhTODO: complete this
 
     @Test public void testChoice_5266a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5642,7 +5230,7 @@
     
     
     @Test public void test1WithCriteriaShortName() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5665,7 +5253,7 @@
     }
 
     @Test public void test1WithCriteriaLongName() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5688,7 +5276,7 @@
     }
 
     @Test public void test2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5707,7 +5295,7 @@
     }
 
     @Test public void test2a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5734,13 +5322,13 @@
     }
 
     @Test public void test2b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         helpTestProcess("SELECT * FROM xmltest.doc2b", null, metadata, dataMgr, TeiidComponentException.class);         //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void test2c() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5763,7 +5351,7 @@
     }
 
     @Test public void test2d() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5790,7 +5378,7 @@
     }
 
     @Test public void test2e() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5817,7 +5405,7 @@
     }
 
     @Test public void testWithNillableNode() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5844,7 +5432,7 @@
     }
 
     @Test public void testWithDefault() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5871,7 +5459,7 @@
     }
 
     @Test public void testWithNamespaces() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5904,7 +5492,7 @@
     }
 
     @Test public void testWithNewIter3Properties() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -5943,7 +5531,7 @@
     }
 
     @Test public void testWithNewIter3PropertiesException() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerDuJour(metadata);
         
         Command command = helpGetCommand("SELECT * FROM xmltest.doc6", metadata); //$NON-NLS-1$
@@ -5965,7 +5553,7 @@
     }
 
     @Test public void testAttributeBug() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
 
         String expectedDoc = 
@@ -5989,7 +5577,7 @@
     }
 
     @Test public void testMultipleDocs() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
 
         String expectedDoc1 = 
@@ -6056,7 +5644,7 @@
     }
 
     @Test public void testRecursive() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
 
         String expectedDoc = 
@@ -6141,7 +5729,7 @@
     }
 
     @Test public void testRecursiveA() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
 
         String expectedDoc = 
@@ -6239,7 +5827,7 @@
      * @throws Exception
      */
     @Test public void testRecursive2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
 
         String expectedDoc = 
@@ -6301,7 +5889,7 @@
         helpTestProcess("SELECT * FROM xmltest.doc13", expectedDoc, metadata, dataMgr); //$NON-NLS-1$
     }
     @Test public void testRecursive3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
 
         String expectedDoc = 
@@ -6363,7 +5951,7 @@
     }
 
     @Test public void testRecursive4Exception() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         helpTestProcess("SELECT * FROM xmltest.doc15", null, metadata, dataMgr, TeiidComponentException.class); //$NON-NLS-1$ //$NON-NLS-2$
     }
@@ -6372,7 +5960,7 @@
      * Seems to be failing as a result of changes for defect 12288 
      */
     @Test public void testRecursive5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
 
         String expectedDoc = 
@@ -6423,7 +6011,7 @@
      * @throws Exception
      */
     @Test public void testRecursiveWithStagingTable_defect15607() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
 
         String expectedDoc = 
@@ -6490,7 +6078,7 @@
      * all nested "anchor" nodes are named "srcNestedRecursive".  Test of defect #5988
      */
     @Test public void testXQTRecursive_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
+        QueryMetadataInterface metadata = exampleMetadata2();
         FakeDataManager dataMgr = exampleXQTDataManager(metadata);
 
         String expectedDoc = 
@@ -6566,7 +6154,7 @@
      * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
      */
     public void DEFER_testXQTRecursive1a_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
+        QueryMetadataInterface metadata = exampleMetadata2();
         FakeDataManager dataMgr = exampleXQTDataManager(metadata);
 
         String expectedDoc = 
@@ -6618,7 +6206,7 @@
      * all nested "anchor" nodes are named "srcNested".  Test of defect #5988
      */
     @Test public void testXQTRecursive2_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
+        QueryMetadataInterface metadata = exampleMetadata2();
         FakeDataManager dataMgr = exampleXQTDataManager(metadata);
 
         String expectedDoc = 
@@ -6670,7 +6258,7 @@
      * for defect 5988
      */
     @Test public void testXQTRecursiveSiblings_5988() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadata2();
+        QueryMetadataInterface metadata = exampleMetadata2();
         FakeDataManager dataMgr = exampleXQTDataManager(metadata);
 
         String expectedDoc = 
@@ -6806,7 +6394,7 @@
     }
 
     @Test public void testSelectElement1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -6830,7 +6418,7 @@
     }
      
     @Test public void testSelectElement2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -6907,7 +6495,7 @@
     
     /** select element in the reverse order of depth*/
     @Test public void testSelectElement3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -6984,7 +6572,7 @@
     
     /** two select elements at the same level*/
     @Test public void testSelectElement4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7014,7 +6602,7 @@
     
     /** defect 9756 */
     @Test public void testSelectElement4_defect9756() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7034,7 +6622,7 @@
     
     /** three select elements with two of them at the same level and there are other nodes with the same name*/
     @Test public void testSelectElement5() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -7119,7 +6707,7 @@
     
     /** check element.* case */
     @Test public void testSelectElement6() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7147,7 +6735,7 @@
     
     /** check element.* case without attribute in order by*/
     @Test public void testSelectElement6a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7175,7 +6763,7 @@
     }
     
     @Test public void testSelectElement7() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7203,7 +6791,7 @@
     }
     
     @Test public void testSelectElement8() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7232,7 +6820,7 @@
     
     /** SELECT clause has element.*, but the sibling elements should not be included, only subtree should */
     @Test public void testSelectElement9() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7268,7 +6856,7 @@
     }         
     
     @Test public void testSelectElement9a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7301,7 +6889,7 @@
              
     /** check element.* case with criteria and order by clause */
     @Test public void testSelectElement10() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7329,7 +6917,7 @@
     }
     
     @Test public void testSelectElement12() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7382,7 +6970,7 @@
     }
     
     @Test public void testSelectElement13() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7404,7 +6992,7 @@
     }
 
     @Test public void testSelectElement14() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc =
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7458,7 +7046,7 @@
     }
     
     @Test public void testSelectElement15() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc =
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7511,7 +7099,7 @@
     }
 
     @Test public void testSelectElement16() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc =
                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7565,7 +7153,7 @@
 
     /**  CSE query 0 */
     @Test public void testSelectElement17() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
 
         String expectedDoc = 
@@ -7666,7 +7254,7 @@
 
     /**  CSE query 1 */
     @Test public void testSelectElement18() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7711,7 +7299,7 @@
 
     /**  CSE query 2 */
     @Test public void testSelectElement19() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7757,7 +7345,7 @@
 
     /**  CSE query 3 */
     @Test public void testSelectElement20() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7790,7 +7378,7 @@
 
     /**  CSE query 3a */
     @Test public void testSelectElement20a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7820,7 +7408,7 @@
 
     /**  CSE query 4 */
     @Test public void testSelectElement21() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7907,7 +7495,7 @@
 
     /**  CSE query 4a */
     @Test public void testSelectElement21a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -7970,7 +7558,7 @@
     
     /**  CSE query 5 */
     @Test public void testSelectElement22() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
 
         String expectedDoc = 
@@ -8029,7 +7617,7 @@
     
     /**  CSE query 5a */
     @Test public void testSelectElement22a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
 
         String expectedDoc = 
@@ -8085,7 +7673,7 @@
     
     /**  CSE query 6 */
     @Test public void testSelectElement23() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
 
         String expectedDoc = 
@@ -8127,7 +7715,7 @@
     
     /**  CSE query 6a */
     @Test public void testSelectElement23a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8166,7 +7754,7 @@
                      
     /** test with order by and the element in the criteria is not in the select elements*/
     @Test public void testSelectElement24() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8206,7 +7794,7 @@
 
     /** test element.* with order by and the element in the criteria is not in the select elements*/
     @Test public void testSelectElement24a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8258,7 +7846,7 @@
             "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
         
         
-        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ItemID, Order.* " + //$NON-NLS-1$
+        helpTestProcess("SELECT Catalogs.Catalog.Items.Item.ItemID, \"Order\".* " + //$NON-NLS-1$
             " FROM xmltest.doc9c " + //$NON-NLS-1$
             " WHERE SupplierID > '54' " + //$NON-NLS-1$
             " ORDER BY ItemID DESC, OrderID DESC", //$NON-NLS-1$
@@ -8267,7 +7855,7 @@
                          
     /** test with order by with only necessary sub-mapping classes are queried*/
     @Test public void testSelectElement25() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8308,7 +7896,7 @@
     
     /** test element.* with order by with only necessary sub-mapping classes are queried*/
     @Test public void testSelectElement25a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8375,7 +7963,7 @@
      *  and case_insensitive nodes in the mapping tree
      */
     @Test public void testSelectElement25b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8439,7 +8027,7 @@
     }
     
     @Test public void testSelectElement26() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8506,7 +8094,7 @@
      * --> refer to Defect9497, this should fail
      */
     @Test public void testSelectElement27() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8534,7 +8122,7 @@
         
     /** test special element, root element */
     @Test public void testSelectElement28() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8558,7 +8146,7 @@
     
     /** test special element */
     @Test public void testSelectElement28a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc =  
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8584,7 +8172,7 @@
 
     /** test model.document.* */
     @Test public void testSelectElement28b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8615,7 +8203,7 @@
         
     /** test special element, root element */
     @Test public void testSelectElement29() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8640,7 +8228,7 @@
     
     /** test simple case for two elements in a mapping class */
     @Test public void testSelectElement30() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -8661,7 +8249,7 @@
                         
     /** test NullPointerException*/
     @Test public void testDefect_9496_1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8725,7 +8313,7 @@
     }
 
     @Test public void testDefect_9496_2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8782,7 +8370,7 @@
     
     /** test StringIndexOutOfBoundsException */
     @Test public void testDefect_9496_3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -8887,7 +8475,7 @@
     
     /** should fail: because there are other element other than "xml" */
     /*@Test public void testResolver1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = ""; 
 
@@ -8903,7 +8491,7 @@
 
     /** should fail: partial qualified element name and "model.document.xml" */
     /*@Test public void testResolver2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = ""; 
 
@@ -8919,7 +8507,7 @@
 
     /** should fail: test XMLResolver validatation for model.* */
     /*@Test public void testDefect_9498_1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = ""; 
 
@@ -8932,7 +8520,7 @@
 
     /** should fail: test XMLResolver validatation for model.document.* */
     /*@Test public void testDefect_9498_2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = ""; 
 
@@ -8945,7 +8533,7 @@
 
     /** should fail: test XMLResolver validatation for xml.* */
     /*@Test public void testDefect_9498_3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = ""; 
 
@@ -8960,7 +8548,7 @@
      *  and case_insensitive nodes in the mapping tree
      */
     @Test public void testCommentNodeInDoc() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9009,7 +8597,7 @@
         "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
 
     @Test public void testDefect8917() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager_8917(metadata);
         
 //        helpTestProcess("SELECT * FROM xmltest.doc_8917 WHERE Catalog.Items.Item.ItemID = '001'",
@@ -9020,7 +8608,7 @@
      * jhTODO
      */
     @Test public void testNillableOptional() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -9039,7 +8627,7 @@
      * jhTODO
      */
     @Test public void testNillableNonOptional() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         String expectedDoc = 
@@ -9061,7 +8649,7 @@
      * see also defect 15117
      */
     @Test public void testDefect11789() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager_8917a(metadata);
 
         String expected = 
@@ -9123,7 +8711,7 @@
      * testDefect8917
      */
     @Test public void testDefect11789b() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager_8917b(metadata);
 
         helpTestProcess("SELECT * FROM xmltest.doc_8917", //$NON-NLS-1$
@@ -9131,7 +8719,7 @@
     }    
     
     @Test public void testDefect9446() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager_8917(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9152,7 +8740,7 @@
     } 
 
     @Test public void testDefect9446_2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager_8917(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9167,7 +8755,7 @@
     } 
 
     @Test public void testDefect_9530() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9198,7 +8786,7 @@
     } 
 
     @Test public void testSubqueryInXMLQueryCriteria() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9225,7 +8813,7 @@
     }
 
     @Test public void testSubqueryInXMLQueryCriteria2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9252,7 +8840,7 @@
     }
 
     @Test public void testSubqueryInXMLQueryCriteria3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9278,35 +8866,8 @@
         helpTestProcess("SELECT * FROM xmltest.doc1 WHERE NOT (ItemID IN (SELECT itemNum FROM stock.items WHERE itemNum = '001') )", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
     }
 
-    public void XXXtestSubqueryInXMLQueryCriteria4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
-        FakeDataManager dataMgr = exampleDataManager(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<Catalogs xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\r\n" + //$NON-NLS-1$
-            "    <Catalog>\r\n" +  //$NON-NLS-1$
-            "        <Items>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"001\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Lamp</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>5</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"002\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Screwdriver</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>100</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "            <Item ItemID=\"003\">\r\n" +  //$NON-NLS-1$
-            "                <Name>Goat</Name>\r\n" +  //$NON-NLS-1$
-            "                <Quantity>4</Quantity>\r\n" +  //$NON-NLS-1$
-            "            </Item>\r\n" +  //$NON-NLS-1$
-            "        </Items>\r\n" +  //$NON-NLS-1$
-            "    </Catalog>\r\n" +  //$NON-NLS-1$
-            "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
-        
-        helpTestProcess("SELECT * FROM xmltest.doc1 WHERE EXISTS (SELECT itemNum FROM stock.items WHERE itemNum = '001')", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
-    }
-
     @Test public void testSubqueryInXMLQueryCriteriaNestedSubquery() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9333,7 +8894,7 @@
     }
 
     @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9398,7 +8959,7 @@
     }  
 
     @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass2() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9463,7 +9024,7 @@
     } 
 
     @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9528,7 +9089,7 @@
     }
 
     @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass3a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9594,7 +9155,7 @@
 
 
     @Test public void testSubqueryInXMLQueryCriteriaNestedMappingClass4() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9661,7 +9222,7 @@
     }
 
     @Test public void testCritNestedMappingClass() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9726,7 +9287,7 @@
     }
 
     @Test public void testDefect_9893() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9741,7 +9302,7 @@
     }
 
     @Test public void testDefect_9893_2() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9756,7 +9317,7 @@
     }
 
     @Test public void testDefect_9893_3() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9771,7 +9332,7 @@
     }
 
     @Test public void testDefect_9893_4() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataNestedWithSibling();
+        QueryMetadataInterface metadata = exampleMetadataNestedWithSibling();
         FakeDataManager dataMgr = exampleDataManagerNestedWithSibling(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9785,13 +9346,12 @@
             "    </Catalog>\r\n" +  //$NON-NLS-1$
             "</Catalogs>\r\n\r\n"; //$NON-NLS-1$
         
-        final boolean SHOULD_SUCCEED = true;
         helpTestProcess("SELECT Item FROM xmltest.doc9c", //$NON-NLS-1$
             expectedDoc, metadata, dataMgr, null);       
     }
 
     @Test public void testNestedWithStoredQueryInMappingClass() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9857,7 +9417,7 @@
 
     /** homegenous, simple array elements */
     @Test public void testWithSOAPEncoding1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataSoap1();
+        QueryMetadataInterface metadata = exampleMetadataSoap1();
         FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, false);
          
         String expectedDoc = 
@@ -9891,7 +9451,7 @@
      * whole fragment
      */        
     @Test public void testWithSOAPEncodingNoRows() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataSoap1();
+        QueryMetadataInterface metadata = exampleMetadataSoap1();
         FakeDataManager dataMgr = exampleDataManagerForSoap1(metadata, true);
          
         String expectedDoc = 
@@ -9917,7 +9477,7 @@
     }  
     
     @Test public void testDefect12260() throws Exception{
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -9957,7 +9517,7 @@
     
     @Test public void testDefect8373() throws Exception{
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
          
         String expectedDoc = 
@@ -9998,7 +9558,7 @@
 
     @Test public void testDefect8373a() throws Exception{
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
          
         String expectedDoc = 
@@ -10039,7 +9599,7 @@
 
     @Test public void testDefect8373b() throws Exception{
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerWithNulls(metadata);
          
         String expectedDoc = 
@@ -10079,7 +9639,7 @@
     }    
 
     @Test public void testDefect13617() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager13617(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10103,7 +9663,7 @@
     }       
 
     @Test public void testDefect13617a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager13617(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10134,7 +9694,7 @@
      * @since 4.2
      */
     @Test public void testDefect14905() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager14905(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10161,7 +9721,7 @@
     }    
 
     @Test public void testTextUnnormalizedDefect15117() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager15117(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10188,7 +9748,7 @@
     }
 
     @Test public void testTextUnnormalizedDefect15117a() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager15117a(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10216,7 +9776,7 @@
     
     @Test public void testRecursiveGroupDoc() throws Exception {
 
-        FakeMetadataFacade metadata = exampleMetadata2();
+        QueryMetadataInterface metadata = exampleMetadata2();
         FakeDataManager dataMgr = exampleXQTDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10250,7 +9810,7 @@
     
     @Test public void testCase2951MaxRows() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10317,7 +9877,7 @@
     /** test rowlimitexception() doesn't throw exception is rowlimit isn't passed */
     @Test public void testDefect19173RowLimitException() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10384,7 +9944,7 @@
     /** test criteria can be written backwards */
     @Test public void testDefect19173RowLimitExceptionBackwardsCriteria() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10450,7 +10010,7 @@
     
     @Test public void testCase2951MaxRows2() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10505,7 +10065,7 @@
     /** test processing exception is thrown if row limit is passed */
     @Test public void testDefect19173RowLimitException2() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10514,7 +10074,7 @@
     /** Two row limits on the same mapping class should be harmless as long as the row limits are identical. */
     @Test public void testCase2951MaxRows2a() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10569,7 +10129,7 @@
     /** test processing exception is thrown if row limit is passed */
     @Test public void testDefect19173RowLimitException2a() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2 AND rowlimitexception(supplierid) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10578,7 +10138,7 @@
     /** compound criteria */
     @Test public void testCase2951MaxRows3() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10609,7 +10169,7 @@
     /** compound criteria */
     @Test public void testDefect19173RowLimitException3() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE ItemID='002' AND rowlimitexception(supplier) = 2", null, metadata, dataMgr, TeiidProcessingException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10617,7 +10177,7 @@
     
     @Test public void testCase2951MaxRows4() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10661,7 +10221,7 @@
 
     @Test public void testCase2951AndDefect19173MixTwoFunctions() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10716,7 +10276,7 @@
     /** arg to rowlimit function isn't in the scope of any mapping class */
     @Test public void testCase2951MaxRowsFails() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(catalogs) = 2", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10725,7 +10285,7 @@
     /** two conflicting row limits on the same mapping class */
     @Test public void testCase2951MaxRowsFails2() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimit(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10734,7 +10294,7 @@
     /** arg to rowlimitexception function isn't in the scope of any mapping class */
     @Test public void testDefect19173RowLimitExceptionFails() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(catalogs) = 2", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10743,7 +10303,7 @@
     /** two conflicting rowlimitexceptions on the same mapping class */
     @Test public void testDefect19173RowLimitExceptionFails2() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimitexception(supplier) = 2 AND rowlimitexception(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10752,7 +10312,7 @@
     /** two conflicting rowlimit and rowlimitexceptions on the same mapping class fails planning */
     @Test public void testDefect19173RowLimitAndRowLimitExceptionMixFails2() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         
         helpTestProcess("SELECT * FROM xmltest.doc8 WHERE rowlimit(supplier) = 2 AND rowlimitexception(supplierID) = 3", null, metadata, dataMgr, QueryPlannerException.class);         //$NON-NLS-1$ //$NON-NLS-2$
@@ -10761,7 +10321,7 @@
     /** try rowlimit criteria written the reverse way */
     @Test public void testCase2951MaxRows5() throws Exception {
         
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNested(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10815,7 +10375,7 @@
     
     
     @Test public void testNormalizationCollapse() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNormalization(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10854,7 +10414,7 @@
     }
     
     @Test public void testNormalizationReplace() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNormalization(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10892,7 +10452,7 @@
         helpTestProcess("SELECT * FROM xmltest.normDoc2", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
     }
     @Test public void testNormalizationPreserve() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManagerNormalization2(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -10933,66 +10493,50 @@
     /**
      * Deluxe example
      */
-    private FakeDataManager exampleDataManagerNormalization(FakeMetadataFacade metadata) {
+    private FakeDataManager exampleDataManagerNormalization(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", " \n Screwdriver \t    \r", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "       \t\rGoat \n", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", "Flux \t\r\n Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "006", " Feta               Matrix       ", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", " \n Screwdriver \t    \r", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", "       \t\rGoat \n", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "004", "Flux \t\r\n Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "005", "Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "006", " Feta               Matrix       ", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }   
-    private FakeDataManager exampleDataManagerNormalization2(FakeMetadataFacade metadata) {
+    private FakeDataManager exampleDataManagerNormalization2(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupID = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-            List elementIDs = metadata.getElementIDsInGroupID(groupID);
-            List elementSymbols = createElements(elementIDs);
-
             dataMgr.registerTuples(
-                groupID,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "My Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "My Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "004", "My Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "005", "My Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "006", "My Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", null, new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "My Screwdriver", null, "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", "My Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "004", "My Flux Capacitor", new Integer(2), "discontinued" } ), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "005", "My Milkshake", new Integer(88), null } ), //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "006", "My Feta Matrix", new Integer(0), "discontinued" } ) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
     }   
     
-    private static MappingNode createXMLPlanNormalization(String normMode) {
+    private static MappingDocument createXMLPlanNormalization(String normMode) {
 
         MappingDocument doc = new MappingDocument(true);
         MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
@@ -11039,116 +10583,70 @@
         return doc;        
     }
 
-    static FakeDataManager exampleDataManagerCase3225(FakeMetadataFacade metadata) {
+    static FakeDataManager exampleDataManagerCase3225(QueryMetadataInterface metadata) {
         FakeDataManager dataMgr = new FakeDataManager();
     
         try { 
-            // Group stock.items
-            FakeMetadataObject groupItems = (FakeMetadataObject) metadata.getGroupID("stock.items"); //$NON-NLS-1$
-
-            // Group stock.supplier
-            FakeMetadataObject groupSuppliers = (FakeMetadataObject) metadata.getGroupID("stock.suppliers"); //$NON-NLS-1$
-
-            // Group stock.orders
-            FakeMetadataObject groupOrders = (FakeMetadataObject) metadata.getGroupID("stock.orders"); //$NON-NLS-1$
-
-            // Group stock.employees
-            FakeMetadataObject groupEmployees = (FakeMetadataObject) metadata.getGroupID("stock.employees"); //$NON-NLS-1$
-            
-            // Group stock.item_supplier
-            FakeMetadataObject groupItemSupplier = (FakeMetadataObject) metadata.getGroupID("stock.item_supplier"); //$NON-NLS-1$
-
-            // Items
-            List elementIDs = metadata.getElementIDsInGroupID(groupItems);
-            List elementSymbols = createElements(elementIDs);
-
-            // Supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupSuppliers);
-            List supplierElementSymbols = createElements(elementIDs);
-
-            // Orders
-            elementIDs = metadata.getElementIDsInGroupID(groupOrders);
-            List ordersElementSymbols = createElements(elementIDs);
-
-            // Employees
-            elementIDs = metadata.getElementIDsInGroupID(groupEmployees);
-            List employeesElementSymbols = createElements(elementIDs);
-            
-            // Item_supplier
-            elementIDs = metadata.getElementIDsInGroupID(groupItemSupplier);
-            List itemSupplierElementSymbols = createElements(elementIDs);
-        
             dataMgr.registerTuples(
-                groupItems,
-                elementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.items", new List[] { 
+					    Arrays.asList( new Object[] { "001", "Lamp", new Integer(5), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "002", "Screwdriver", new Integer(100), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "003", "Goat", new Integer(4), "okay" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
             dataMgr.registerTuples(
-                groupItemSupplier,
-                itemSupplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
-                    } );    
+                metadata,
+                "stock.item_supplier", new List[] { 
+					    Arrays.asList( new Object[] { "001", "51" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "001", "52" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "001", "53" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "001", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "54" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "55" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "002", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    Arrays.asList( new Object[] { "003", "56" } ),         //$NON-NLS-1$ //$NON-NLS-2$
+					    } );    
 
 
             dataMgr.registerTuples(
-                groupSuppliers,
-                supplierElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-                    } );    
+                metadata,
+                "stock.suppliers", new List[] { 
+					    Arrays.asList( new Object[] { "51", "Chucky", "11111" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "52", "Biff's Stuff", "22222" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "53", "AAAA", "33333" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "54", "Nugent Co.", "44444" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "55", "Zeta", "55555" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    Arrays.asList( new Object[] { "56", "Microsoft", "66666" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+					    } );    
 
             dataMgr.registerTuples(
-                groupOrders,
-                ordersElementSymbols,
-                
-                new List[] { 
-                    Arrays.asList( new Object[] { "1", "001", "51", "2/13/05", new Integer(2), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "2", "001", "52", "3/13/05", new Integer(1), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "3", "002", "53", "4/13/05", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "4", "002", "56", "5/13/05", new Integer(1), "cancelled" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    Arrays.asList( new Object[] { "5", "003", "56", "6/13/05", new Integer(800), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-                    } );    
+                metadata,
+                "stock.orders", new List[] { 
+					    Arrays.asList( new Object[] { "1", "001", "51", "2/13/05", new Integer(2), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "2", "001", "52", "3/13/05", new Integer(1), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "3", "002", "53", "4/13/05", new Integer(1), "complete" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "4", "002", "56", "5/13/05", new Integer(1), "cancelled" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    Arrays.asList( new Object[] { "5", "003", "56", "6/13/05", new Integer(800), "processing" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+					    } );    
 
             dataMgr.registerTuples(
-                groupEmployees,
-                employeesElementSymbols,
-               
-                new List[] { 
-                    Arrays.asList( new Object[] { "1001", "51", "001", "1004", "Albert", "Pujols" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1002", "51", "001", "1004", "Jim", "Edmunds" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1003", "54", "002", "1004", "David", "Eckstein" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1004", null, null, "1009", "Tony", "LaRussa" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-                    Arrays.asList( new Object[] { "1005", "56", "001", "1007", "Derrek", "Lee" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1006", "56", "003", "1007", "Corey", "Patterson" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1007", null, null, "1010", "Dusty", "Baker" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
-                    Arrays.asList( new Object[] { "1008", "56", "002", "1007", "Carlos", "Zambrano" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-                    Arrays.asList( new Object[] { "1009", null, null, null, "Bill", "DeWitt" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-                    Arrays.asList( new Object[] { "1010", null, null, null, "Some", "Guy" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-                    } );             
+                metadata,
+                "stock.employees", new List[] { 
+					    Arrays.asList( new Object[] { "1001", "51", "001", "1004", "Albert", "Pujols" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "1002", "51", "001", "1004", "Jim", "Edmunds" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "1003", "54", "002", "1004", "David", "Eckstein" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "1004", null, null, "1009", "Tony", "LaRussa" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+					    Arrays.asList( new Object[] { "1005", "56", "001", "1007", "Derrek", "Lee" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "1006", "56", "003", "1007", "Corey", "Patterson" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "1007", null, null, "1010", "Dusty", "Baker" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ 
+					    Arrays.asList( new Object[] { "1008", "56", "002", "1007", "Carlos", "Zambrano" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+					    Arrays.asList( new Object[] { "1009", null, null, null, "Bill", "DeWitt" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+					    Arrays.asList( new Object[] { "1010", null, null, null, "Some", "Guy" } ),         //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+					    } );             
             
-        } catch(Throwable e) { 
-            e.printStackTrace();
-            fail("Exception building test data (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
+        } catch(TeiidException e) { 
+        	throw new RuntimeException(e);
         }
         
         return dataMgr;
@@ -11159,7 +10657,7 @@
      * @throws Exception
      */
     @Test public void testCase3225() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
         String expectedDoc = 
         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -11477,7 +10975,7 @@
      * @throws Exception
      */
     @Test public void testCase3225WithCriteria() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
         helpTestProcess("select * from xmltest.itemsdoc where employee. at supervisorID='1004' and order.orderquantity > 1", CASE_3225_WITH_CRITERIA_EXPECTED_DOC, metadata, dataMgr);         //$NON-NLS-1$
     }    
@@ -11499,7 +10997,7 @@
      * @throws Exception
      */
     @Test public void testCase3225WithCriteriaReversed() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
         helpTestProcess("select * from xmltest.itemsdoc where order.orderquantity > 1 and employee. at supervisorID='1004'", CASE_3225_WITH_CRITERIA_EXPECTED_DOC, metadata, dataMgr);         //$NON-NLS-1$
     }      
@@ -11511,7 +11009,7 @@
      * @throws Exception
      */
     @Test public void testCase3225WithEmptyDocCriteria() throws Exception {
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -11531,7 +11029,7 @@
      */
     @Test public void testBaseballPlayersDoc() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -11623,7 +11121,7 @@
      */
     @Test public void testBaseballPlayersDocCriteria() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -11678,70 +11176,25 @@
      */
     @Test public void testBaseballPlayersDocContextCriteria() throws Exception {
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleCase3225();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
         FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
-        String expectedDoc = 
-            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
-            "<BaseballPlayers>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1001\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Albert</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Pujols</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1002\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Jim</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Edmunds</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1003\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>David</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Eckstein</LastName>\r\n" + //$NON-NLS-1$
-            "      <Manager ManagerID=\"1004\">\r\n" + //$NON-NLS-1$
-            "         <FirstName>Tony</FirstName>\r\n" + //$NON-NLS-1$
-            "         <LastName>LaRussa</LastName>\r\n" + //$NON-NLS-1$
-            "         <Owner OwnerID=\"1009\">\r\n" + //$NON-NLS-1$
-            "            <FirstName>Bill</FirstName>\r\n" + //$NON-NLS-1$
-            "            <LastName>DeWitt</LastName>\r\n" + //$NON-NLS-1$
-            "         </Owner>\r\n" + //$NON-NLS-1$
-            "      </Manager>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1005\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Derrek</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Lee</LastName>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1006\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Corey</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Patterson</LastName>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "   <Player PlayerID=\"1008\">\r\n" + //$NON-NLS-1$
-            "      <FirstName>Carlos</FirstName>\r\n" + //$NON-NLS-1$
-            "      <LastName>Zambrano</LastName>\r\n" + //$NON-NLS-1$
-            "   </Player>\r\n" + //$NON-NLS-1$
-            "</BaseballPlayers>\r\n\r\n"; //$NON-NLS-1$
         
-        helpTestProcess("select * from xmltest.playersDoc where context(manager, owner. at ownerid) = '1009'", expectedDoc, metadata, dataMgr);         //$NON-NLS-1$
+        helpTestProcess("select * from xmltest.playersDoc where context(manager, owner. at ownerid) = '1009'", CARDS_MANAGER, metadata, dataMgr);         //$NON-NLS-1$
         
     }    
     
+    @Test public void testBaseballPlayersPseudoGroup() throws Exception {
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleCase3225();
+        FakeDataManager dataMgr = exampleDataManagerCase3225(metadata);
+
+    	helpTestProcess("select * from xmltest.playersDoc where context(manager, manager.firstname) > ALL (select firstname from BaseballPlayers.player)", CARDS_MANAGER, metadata, dataMgr);         //$NON-NLS-1$
+    }
+    
     /**
      * Ensures that temp tables are still visible when processing criteria
      */
     @Test public void testProcedureAndXML() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -11763,7 +11216,7 @@
     }
     
     @Test public void testProcedureAndXML1() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc1 = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$
@@ -11808,7 +11261,7 @@
      * of bounded, but result set is returning more results then it should fail.
      */
     public void defer_testMinMaxOnSourceNode() throws Exception {
-        FakeMetadataFacade metadata = exampleMetadataCached();
+        QueryMetadataInterface metadata = exampleMetadataCached();
         FakeDataManager dataMgr = exampleDataManager(metadata);
         String expectedDoc = 
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +  //$NON-NLS-1$

Modified: branches/as7/engine/src/test/java/org/teiid/query/resolver/TestAlterResolving.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/resolver/TestAlterResolving.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/resolver/TestAlterResolving.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -49,12 +49,12 @@
 	}
 	
 	@Test public void testAlterTriggerInsert() {
-		AlterTrigger alterTrigger = (AlterTrigger) helpResolve("alter trigger on SmallA_2589 instead of insert as for each row select new.intkey;", RealMetadataFactory.exampleBQTCached());
+		AlterTrigger alterTrigger = (AlterTrigger) helpResolve("alter trigger on SmallA_2589 instead of insert as for each row begin atomic select new.intkey; end", RealMetadataFactory.exampleBQTCached());
 		assertNotNull(alterTrigger.getTarget().getMetadataID());
 	}
 	
 	@Test public void testAlterTriggerInsert_Invalid() {
-		helpResolveException("alter trigger on SmallA_2589 instead of insert as for each row select old.intkey;", RealMetadataFactory.exampleBQTCached());
+		helpResolveException("alter trigger on SmallA_2589 instead of insert as for each row begin atomic select old.intkey; end", RealMetadataFactory.exampleBQTCached());
 	}
 	
 	@Test public void testAlterView_Invalid() {

Modified: branches/as7/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/resolver/TestFunctionResolving.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,7 +36,7 @@
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.XMLSerialize;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 public class TestFunctionResolving {
@@ -45,7 +45,7 @@
         Function function = new Function("convert", new Expression[] {new Constant(new Character('a')), new Constant(DataTypeManager.DefaultDataTypes.DATE)}); //$NON-NLS-1$
         
         try {
-            ResolverVisitor.resolveLanguageObject(function, FakeMetadataFactory.example1Cached());
+            ResolverVisitor.resolveLanguageObject(function, RealMetadataFactory.example1Cached());
             fail("excpetion expected"); //$NON-NLS-1$
         } catch (QueryResolverException err) {
             assertEquals("Error Code:ERR.015.008.0037 Message:The conversion from char to date is not allowed.", err.getMessage()); //$NON-NLS-1$
@@ -59,7 +59,7 @@
         e1.setMetadataID(new Object()); 
         Function function = new Function("abs", new Expression[] {e1}); //$NON-NLS-1$
         
-        ResolverVisitor.resolveLanguageObject(function, FakeMetadataFactory.example1Cached());
+        ResolverVisitor.resolveLanguageObject(function, RealMetadataFactory.example1Cached());
         
         assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, function.getType());
     }
@@ -67,7 +67,7 @@
     @Test public void testResolveConvertReference() throws Exception {
         Function function = new Function("convert", new Expression[] {new Reference(0), new Constant(DataTypeManager.DefaultDataTypes.BOOLEAN)}); //$NON-NLS-1$
         
-        ResolverVisitor.resolveLanguageObject(function, FakeMetadataFactory.example1Cached());
+        ResolverVisitor.resolveLanguageObject(function, RealMetadataFactory.example1Cached());
         
         assertEquals(DataTypeManager.DefaultDataClasses.BOOLEAN, function.getType());
         assertEquals(DataTypeManager.DefaultDataClasses.BOOLEAN, function.getArgs()[0].getType());
@@ -77,7 +77,7 @@
         Function function = new Function("LCASE", new Expression[] {new Reference(0)}); //$NON-NLS-1$
         
         try {
-        	ResolverVisitor.resolveLanguageObject(function, FakeMetadataFactory.example1Cached());
+        	ResolverVisitor.resolveLanguageObject(function, RealMetadataFactory.example1Cached());
             fail("excpetion expected"); //$NON-NLS-1$
         } catch (QueryResolverException err) {
             assertEquals("Error Code:ERR.015.008.0036 Message:The function 'LCASE(?)' has more than one possible signature.", err.getMessage()); //$NON-NLS-1$
@@ -130,7 +130,7 @@
 	public static Expression getExpression(String sql) throws QueryParserException,
 			TeiidComponentException, QueryResolverException {
 		Expression func = QueryParser.getQueryParser().parseExpression(sql);
-		ResolverVisitor.resolveLanguageObject(func, FakeMetadataFactory.example1Cached());
+		ResolverVisitor.resolveLanguageObject(func, RealMetadataFactory.example1Cached());
 		return func;
 	}
 	

Modified: branches/as7/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/resolver/TestProcedureResolving.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,17 +24,15 @@
 
 import static org.junit.Assert.*;
 
-import java.util.Arrays;
 import java.util.Map;
 
 import org.junit.Test;
 import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.api.exception.query.QueryResolverException;
-import org.teiid.client.metadata.ParameterInfo;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.types.DataTypeManager;
-import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.metadata.Table;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataAdapter;
 import org.teiid.query.metadata.TempMetadataStore;
@@ -53,34 +51,15 @@
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.CommandCollectorVisitor;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 
-
 public class TestProcedureResolving {
 
- 	private QueryMetadataInterface exampleStoredProcedure(String procedure) {
-		FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        
-        FakeMetadataObject pm1 = metadata.getStore().findObject("pm1",FakeMetadataObject.MODEL); //$NON-NLS-1$
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode(procedure); 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        metadata.getStore().addObject(rs2);
-        metadata.getStore().addObject(sq1);
-        
-        return metadata;
-	}
- 	
-    private void helpFailUpdateProcedure(String procedure, String userUpdateStr, String procedureType) {
+    private void helpFailUpdateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
         helpFailUpdateProcedure(procedure, userUpdateStr, procedureType, null);
     }
     
-	private void helpFailUpdateProcedure(String procedure, String userUpdateStr, String procedureType, String msg) {
+	private void helpFailUpdateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType, String msg) {
         // resolve
         try {
     		helpResolveUpdateProcedure(procedure, userUpdateStr, procedureType);
@@ -112,7 +91,7 @@
             
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        Command command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
+        Command command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
         Map tempIDs = command.getTemporaryMetadata();
         assertNotNull(tempIDs);
         assertNull(tempIDs.get("LOOPCURSOR")); //$NON-NLS-1$
@@ -131,8 +110,8 @@
         assertNull(tempIDs.get("LOOPCURSOR2")); //$NON-NLS-1$
     }
     
-	private CreateUpdateProcedureCommand helpResolveUpdateProcedure(String procedure, String userUpdateStr, String procedureType) throws QueryParserException, QueryResolverException, TeiidComponentException {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+	private CreateUpdateProcedureCommand helpResolveUpdateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) throws QueryParserException, QueryResolverException, TeiidComponentException {
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
 		return resolveProcedure(userUpdateStr, metadata);
 	}
 
@@ -149,6 +128,7 @@
 	private void helpResolveException(String userUpdateStr, QueryMetadataInterface metadata, String msg) throws QueryParserException, TeiidComponentException {
 		try {
 			helpResolve(userUpdateStr, metadata);
+			fail();
 		} catch (QueryResolverException e) {
 			assertEquals(msg, e.getMessage());
 		}
@@ -162,7 +142,7 @@
      *  Constants will now auto resolve if they are consistently representable in the target type
      */
     @Test public void testDefect23257() throws Exception{
-    	CreateUpdateProcedureCommand command = helpResolve("EXEC pm5.vsp59()", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+    	CreateUpdateProcedureCommand command = helpResolve("EXEC pm6.vsp59()", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         
         CommandStatement cs = (CommandStatement)command.getBlock().getStatements().get(1);
         
@@ -187,19 +167,19 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         CreateUpdateProcedureCommand command = helpResolveUpdateProcedure(proc.toString(), userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     Table.TriggerEvent.UPDATE);
         
         Block block = command.getBlock();
         
         AssignmentStatement assStmt = (AssignmentStatement)block.getStatements().get(1);
         assertEquals(ProcedureReservedWords.VARIABLES, assStmt.getVariable().getGroupSymbol().getCanonicalName());
-        assertEquals(ProcedureReservedWords.VARIABLES, ((ElementSymbol)assStmt.getValue()).getGroupSymbol().getCanonicalName());
+        assertEquals(ProcedureReservedWords.VARIABLES, ((ElementSymbol)assStmt.getExpression()).getGroupSymbol().getCanonicalName());
         
         Block inner = ((LoopStatement)block.getStatements().get(2)).getBlock();
         
         assStmt = (AssignmentStatement)inner.getStatements().get(0);
         
-        ElementSymbol value = ElementCollectorVisitor.getElements(assStmt.getValue(), false).iterator().next();
+        ElementSymbol value = ElementCollectorVisitor.getElements(assStmt.getExpression(), false).iterator().next();
         
         assertEquals("LOOPCURSOR", value.getGroupSymbol().getCanonicalName()); //$NON-NLS-1$
     }
@@ -217,7 +197,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// variable resolution, variable used in if statement, invalid operation on variable
@@ -232,7 +212,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }    
     
 	// variable resolution, variables declared in different blocks local variables
@@ -251,7 +231,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE, "Variable var1 was previously declared."); //$NON-NLS-1$
+									 Table.TriggerEvent.UPDATE, "Variable var1 was previously declared."); //$NON-NLS-1$
     }
     
 	// variable resolution, variables declared in different blocks local variables
@@ -270,7 +250,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// variable resolution, variables declared in different blocks local variables
@@ -290,7 +270,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }     
     
 	// variable resolution, variables declared in different blocks local variables
@@ -310,7 +290,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }    
     
 	// special variable ROWS_UPDATED resolution
@@ -326,7 +306,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// special variable ROWS_UPDATED used with declared variable
@@ -341,7 +321,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// special variable INPUT used with declared variable
@@ -356,7 +336,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// special variable CHANGING used with declared variable
@@ -374,7 +354,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// special variable CHANGING and INPUT used in compound criteria
@@ -392,7 +372,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// special variable CHANGING and INPUT used in compound criteria, with declared variables
@@ -410,7 +390,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// special variable CHANGING compared against integer no implicit conversion available
@@ -426,7 +406,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE, "Error Code:ERR.015.008.0027 Message:The expressions in this criteria are being compared but are of differing types (boolean and date) and no implicit conversion is available:  CHANGING.e4 = {d'2000-01-01'}"); //$NON-NLS-1$
+									 Table.TriggerEvent.UPDATE, "Error Code:ERR.015.008.0027 Message:The expressions in this criteria are being compared but are of differing types (boolean and date) and no implicit conversion is available:  CHANGING.e4 = {d'2000-01-01'}"); //$NON-NLS-1$
     }       
     
 	// virtual group elements used in procedure(HAS CRITERIA)
@@ -441,7 +421,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// virtual group elements used in procedure in if statement(HAS CRITERIA)
@@ -459,7 +439,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }    
     
 	// virtual group elements used in procedure(TRANSLATE CRITERIA)
@@ -474,7 +454,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// virtual group elements used in procedure(TRANSLATE CRITERIA)
@@ -489,7 +469,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using undefined variable should fail
@@ -505,7 +485,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using undefined variable declared is of invalid datatype
@@ -520,7 +500,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using declare variable that has parts
@@ -533,7 +513,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using declare variable is qualified
@@ -546,7 +526,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using declare variable is qualified but has more parts
@@ -559,7 +539,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using a variable that has not been declared in an assignment stmt
@@ -572,7 +552,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using a variable that has not been declared in an assignment stmt
@@ -585,7 +565,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using invalid function in assignment expr
@@ -599,7 +579,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }    
     
 	// using invalid function in assignment expr
@@ -613,7 +593,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// using a variable being used inside a subcomand
@@ -627,7 +607,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// variable resolution, variables declared in different blocks local variables
@@ -648,7 +628,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// physical elements used on criteria of the if statement
@@ -665,7 +645,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE, "Symbol pm1.g1.e2 is specified with an unknown group context"); //$NON-NLS-1$
+									 Table.TriggerEvent.UPDATE, "Symbol pm1.g1.e2 is specified with an unknown group context"); //$NON-NLS-1$
     }
     
 	// virtual elements used on criteria of the if statement
@@ -682,7 +662,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// physical elements used on criteria of the if statement
@@ -699,7 +679,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }          
     
 	// TranslateCriteria on criteria of the if statement
@@ -716,7 +696,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// validating Translate CRITERIA, elements on it should be virtual group elements
@@ -731,7 +711,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// physical elements used on criteria of the if statement
@@ -748,7 +728,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// TranslateCriteria on criteria of the if statement
@@ -765,7 +745,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// TranslateCriteria on criteria of the if statement
@@ -782,7 +762,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// TranslateCriteria on criteria of the if statement
@@ -799,7 +779,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// TranslateCriteria on criteria of the if statement
@@ -812,7 +792,7 @@
 //        procedure = procedure + "UPDATE pm1.g1 SET pm1.g1.e1 = INPUTS.e1, pm1.g1.e2 = INPUTS.e2;\n";
         procedure = procedure + "END\n"; //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);
 
         Command procCommand = QueryParser.getQueryParser().parseCommand(procedure);
 		GroupSymbol virtualGroup = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
@@ -833,7 +813,7 @@
         String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.INSERT_PROCEDURE);
+									 Table.TriggerEvent.INSERT);
     }
     
 	// special variable CHANGING compared against integer no implicit conversion available
@@ -848,7 +828,7 @@
 
         Command procCommand = QueryParser.getQueryParser().parseCommand(procedure);
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.INSERT_PROCEDURE, procedure);        
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.INSERT, procedure);        
         
 		GroupSymbol virtualGroup = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
 		virtualGroup.setMetadataID(metadata.getGroupID("vm1.g1")); //$NON-NLS-1$
@@ -865,7 +845,7 @@
 
         Command procCommand = QueryParser.getQueryParser().parseCommand(procedure);
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);        
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure);        
         
 		GroupSymbol virtualGroup = new GroupSymbol("vm1.g1"); //$NON-NLS-1$
 		virtualGroup.setMetadataID(metadata.getGroupID("vm1.g1")); //$NON-NLS-1$
@@ -887,7 +867,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
 	
 	// validating Translate CRITERIA, elements(left elements on  on it should be virtual group elements
@@ -901,7 +881,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
 
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
 	
 	// resolving Translate CRITERIA, right element should be present on the command
@@ -914,7 +894,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
 
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
 	
 	// resolving criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
@@ -931,7 +911,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
 	
 	// resolving Translate CRITERIA, right side expression in the translate criteria should be elements on the command
@@ -947,7 +927,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
 	
 	// validating Translate CRITERIA, elements on it should be virtual group elements
@@ -963,7 +943,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
 	
 	// resolving AssignmentStatement, variable type and assigned type 
@@ -979,7 +959,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
 	
 	// resolving AssignmentStatement, variable type and assigned type 
@@ -995,7 +975,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}
     
 	// resolving AssignmentStatement, variable type and assigned type 
@@ -1011,7 +991,7 @@
 		String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
 	}	
 
     @Test public void testDefect14912_CreateUpdateProcedure57_FunctionWithElementParamInAssignmentStatement() {
@@ -1025,7 +1005,7 @@
         
         String userCommand = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
 
-        helpFailUpdateProcedure(procedure, userCommand, FakeMetadataObject.Props.UPDATE_PROCEDURE, "Element \"badElement\" is not defined by any relevant group."); //$NON-NLS-1$
+        helpFailUpdateProcedure(procedure, userCommand, Table.TriggerEvent.UPDATE, "Element \"badElement\" is not defined by any relevant group."); //$NON-NLS-1$
     }
     
 	// addresses Cases 4624.  Before change to UpdateProcedureResolver,
@@ -1044,7 +1024,7 @@
         
         String userCommand = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
 
-        helpFailUpdateProcedure(procedure, userCommand, FakeMetadataObject.Props.UPDATE_PROCEDURE, "Group does not exist: Bert_MAP.BERT3.RACK"); //$NON-NLS-1$
+        helpFailUpdateProcedure(procedure, userCommand, Table.TriggerEvent.UPDATE, "Group does not exist: Bert_MAP.BERT3.RACK"); //$NON-NLS-1$
     }
 
 	// addresses Cases 5474.  
@@ -1055,32 +1035,28 @@
         procedure = procedure + "VARIABLES.NLEVELS = SELECT COUNT(*) FROM (SELECT oi.e1 AS Col1, oi.e2 AS Col2, oi.e3 FROM pm1.g2 AS oi) AS TOBJ, pm2.g2 AS TModel WHERE TModel.e3 = TOBJ.e3;\n"; //$NON-NLS-1$
         procedure = procedure + "END\n"; //$NON-NLS-1$
         
-        TestResolver.helpResolve(procedure, FakeMetadataFactory.example1Cached());
+        TestResolver.helpResolve(procedure, RealMetadataFactory.example1Cached());
     }
     
-    @Test public void testIssue174102() throws Exception {
-        String procedure = "CREATE VIRTUAL PROCEDURE  \n"; //$NON-NLS-1$
+	// addresses Cases 5474.  
+    @Test public void testProcWithReturn() throws Exception {
+        String procedure = "CREATE VIRTUAL PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE string crit = 'WHERE pm1.sq2.in = \"test\"';\n"; //$NON-NLS-1$
-        procedure = procedure + "CREATE LOCAL TEMPORARY TABLE #TTable (e1 string);"; //$NON-NLS-1$
-        procedure = procedure + "EXECUTE STRING ('SELECT e1 FROM pm1.sq2 ' || crit ) AS e1 string INTO #TTable;\n"; //$NON-NLS-1$
+        procedure = procedure + "call sptest9(1);\n"; //$NON-NLS-1$
         procedure = procedure + "END\n"; //$NON-NLS-1$
         
-        TestResolver.helpResolve(procedure, FakeMetadataFactory.example1Cached());
+        TestResolver.helpResolve(procedure, RealMetadataFactory.exampleBQTCached());
     }
     
-    // Address Issue 174519.
-    // Expected result is resolver failure, but with different error.
-    @Test public void testIssue174519() throws Exception {
+    @Test public void testIssue174102() throws Exception {
         String procedure = "CREATE VIRTUAL PROCEDURE  \n"; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
-        procedure = procedure + "DECLARE string VARIABLES.l_in = pm1.sq1.in;\n"; //$NON-NLS-1$
-        procedure = procedure + "INSERT INTO #temp \n"; //$NON-NLS-1$
-        procedure = procedure + "SELECT pm1.sq3.e1 FROM pm1.sq3 WHERE pm1.sq3.in = VARIABLES.l_in;\n"; //$NON-NLS-1$
+        procedure = procedure + "DECLARE string crit = 'WHERE pm1.sq2.in = \"test\"';\n"; //$NON-NLS-1$
+        procedure = procedure + "CREATE LOCAL TEMPORARY TABLE #TTable (e1 string);"; //$NON-NLS-1$
+        procedure = procedure + "EXECUTE STRING ('SELECT e1 FROM pm1.sq2 ' || crit ) AS e1 string INTO #TTable;\n"; //$NON-NLS-1$
         procedure = procedure + "END\n"; //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = exampleStoredProcedure(procedure);
-        helpResolveException("EXEC pm1.sq1(1)", metadata, "Error Code:ERR.015.008.0010 Message:INSERT statement must have the same number of elements and values specified.  This statement has 0 elements and 0 values."); //$NON-NLS-1$ //$NON-NLS-2$
+        TestResolver.helpResolve(procedure, RealMetadataFactory.example1Cached());
     }
     
 	/*@Test public void testCommandUpdatingCountFromLastStatement() throws Exception {
@@ -1106,7 +1082,7 @@
         
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
 
-        helpFailUpdateProcedure(procedure, userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
+        helpFailUpdateProcedure(procedure, userUpdateStr, Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testDynamicIntoInProc() throws Exception {
@@ -1119,7 +1095,7 @@
                                 .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
                                 .append("END\n"); //$NON-NLS-1$
         helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
-                                   FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                   Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testDynamicStatement() throws Exception {
@@ -1131,7 +1107,7 @@
                                 .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
                                 .append("END\n"); //$NON-NLS-1$
         helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
-                                   FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                   Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testDynamicStatementType() {
@@ -1143,7 +1119,7 @@
                                 .append("execute string VARIABLES.X;\n") //$NON-NLS-1$
                                 .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
                                 .append("END\n"); //$NON-NLS-1$
-        helpFailUpdateProcedure(procedure.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
+        helpFailUpdateProcedure(procedure.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
     }
 
 	// variable resolution
@@ -1158,7 +1134,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1=1"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// variable resolution, variable used in if statement
@@ -1174,7 +1150,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpResolveUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
 
     @Test public void testSelectIntoInProc() throws Exception {
@@ -1187,7 +1163,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     Table.TriggerEvent.UPDATE);
         
         procedure = new StringBuffer("CREATE PROCEDURE  ") //$NON-NLS-1$
                                 .append("BEGIN\n") //$NON-NLS-1$
@@ -1195,7 +1171,7 @@
                                 .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
                                 .append("END\n"); //$NON-NLS-1$
         helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
-                                   FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                   Table.TriggerEvent.UPDATE);
     }
 
     @Test public void testSelectIntoInProcNoFrom() throws Exception {
@@ -1208,7 +1184,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     Table.TriggerEvent.UPDATE);
         
         procedure = new StringBuffer("CREATE PROCEDURE  ") //$NON-NLS-1$
                                 .append("BEGIN\n") //$NON-NLS-1$
@@ -1216,7 +1192,7 @@
                                 .append("ROWS_UPDATED =0;\n") //$NON-NLS-1$
                                 .append("END\n"); //$NON-NLS-1$
         helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
-                                   FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                   Table.TriggerEvent.UPDATE);
     }
     
     /*@Test public void testCommandUpdating3() throws Exception{
@@ -1229,7 +1205,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         Command command = helpResolveUpdateProcedure(procedure.toString(), userUpdateStr,
-                                   FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                   Table.TriggerEvent.UPDATE);
         assertEquals(2, command.updatingModelCount(metadata));
     }*/
 
@@ -1245,7 +1221,7 @@
         String userUpdateStr = "INSERT into vm1.g1 (e1) values('x')"; //$NON-NLS-1$
         
         Command command = helpResolveUpdateProcedure(procedure, userUpdateStr,
-                                     FakeMetadataObject.Props.INSERT_PROCEDURE);
+                                     Table.TriggerEvent.INSERT);
         assertEquals(2, command.updatingModelCount(metadata));
     }*/
     
@@ -1260,7 +1236,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpFailUpdateProcedure(procedure, userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE, "Variable rows_updated was previously declared."); //$NON-NLS-1$
+                                     Table.TriggerEvent.UPDATE, "Variable rows_updated was previously declared."); //$NON-NLS-1$
     }
     
     // validating INPUT element assigned
@@ -1275,7 +1251,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpFailUpdateProcedure(procedure, userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     Table.TriggerEvent.UPDATE);
     }
     
     // validating CHANGING element assigned
@@ -1290,7 +1266,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpFailUpdateProcedure(procedure, userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                                     Table.TriggerEvent.UPDATE);
     }
     
     // variables cannot be used among insert elements
@@ -1305,7 +1281,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
 
         helpFailUpdateProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.UPDATE_PROCEDURE, "Column variables do not reference columns on group \"pm1.g1\": [Unable to resolve 'var1': Element \"var1\" is not defined by any relevant group.]"); //$NON-NLS-1$
+                Table.TriggerEvent.UPDATE, "Column variables do not reference columns on group \"pm1.g1\": [Unable to resolve 'var1': Element \"var1\" is not defined by any relevant group.]"); //$NON-NLS-1$
     }
     
     // variables cannot be used among insert elements
@@ -1320,7 +1296,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
 
         helpFailUpdateProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.UPDATE_PROCEDURE, "Column variables do not reference columns on group \"pm1.g1\": [Unable to resolve 'INPUTS.x': Symbol INPUTS.x is specified with an unknown group context]"); //$NON-NLS-1$
+                Table.TriggerEvent.UPDATE, "Column variables do not reference columns on group \"pm1.g1\": [Unable to resolve 'INPUTS.x': Symbol INPUTS.x is specified with an unknown group context]"); //$NON-NLS-1$
     }
     
     //should resolve first to the table's column
@@ -1335,7 +1311,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
 
         helpResolveUpdateProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.UPDATE_PROCEDURE); 
+                Table.TriggerEvent.UPDATE); 
     }
     
     @Test public void testAmbigousInput() {
@@ -1347,7 +1323,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpFailUpdateProcedure(procedure, userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE, "Element \"e1\" is ambiguous, it exists in two or more groups."); //$NON-NLS-1$
+                                     Table.TriggerEvent.UPDATE, "Element \"e1\" is ambiguous, it exists in two or more groups."); //$NON-NLS-1$
     }
     
     @Test public void testLoopRedefinition() {
@@ -1366,7 +1342,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpFailUpdateProcedure(proc.toString(), userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE, "Nested Loop can not use the same cursor name as that of its parent."); //$NON-NLS-1$
+                                     Table.TriggerEvent.UPDATE, "Nested Loop can not use the same cursor name as that of its parent."); //$NON-NLS-1$
     }
     
     @Test public void testTempGroupElementShouldNotBeResolable() {
@@ -1379,7 +1355,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpFailUpdateProcedure(proc.toString(), userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE, "Symbol #temp.a is specified with an unknown group context"); //$NON-NLS-1$
+                                     Table.TriggerEvent.UPDATE, "Symbol #temp.a is specified with an unknown group context"); //$NON-NLS-1$
     }
     
     @Test public void testTempGroupElementShouldNotBeResolable1() {
@@ -1392,7 +1368,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
         helpFailUpdateProcedure(proc.toString(), userUpdateStr,
-                                     FakeMetadataObject.Props.UPDATE_PROCEDURE, "Symbol #temp.a is specified with an unknown group context"); //$NON-NLS-1$
+                                     Table.TriggerEvent.UPDATE, "Symbol #temp.a is specified with an unknown group context"); //$NON-NLS-1$
     }
     
     @Test public void testProcedureCreate() throws Exception {
@@ -1406,7 +1382,7 @@
         
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE); 
+        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE); 
     }
     
     /**
@@ -1423,7 +1399,7 @@
         
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        helpFailUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE, "Cannot create temporary table \"loopCursor\". A table with the same name already exists."); //$NON-NLS-1$
+        helpFailUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE, "Cannot create temporary table \"loopCursor\". An object with the same name already exists."); //$NON-NLS-1$
     }
     
     @Test public void testProcedureCreateDrop() {
@@ -1435,7 +1411,7 @@
         
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        helpFailUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE, "Group does not exist: t1"); //$NON-NLS-1$
+        helpFailUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE, "Group does not exist: t1"); //$NON-NLS-1$
     }
     
     @Test public void testProcedureCreateDrop1() throws Exception {
@@ -1447,7 +1423,7 @@
         
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE);
+        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testCreateAfterImplicitTempTable() throws Exception {
@@ -1459,7 +1435,7 @@
         
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE); 
+        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE); 
     }
     
     @Test public void testInsertAfterCreate() throws Exception {
@@ -1471,7 +1447,7 @@
         
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
-        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, FakeMetadataObject.Props.UPDATE_PROCEDURE); 
+        helpResolveUpdateProcedure(proc.toString(), userUpdateStr, Table.TriggerEvent.UPDATE); 
     }
     
 	/**
@@ -1487,11 +1463,11 @@
         String userUpdateStr = "delete from vm1.g1 where e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.DELETE_PROCEDURE, "Symbol INPUTS.e1 is specified with an unknown group context"); //$NON-NLS-1$
+									 Table.TriggerEvent.DELETE, "Symbol INPUTS.e1 is specified with an unknown group context"); //$NON-NLS-1$
 	}
 	
     @Test public void testInvalidVirtualProcedure3() throws Exception {
-    	helpResolveException("EXEC pm1.vsp18()", FakeMetadataFactory.example1Cached(), "Group does not exist: temptable"); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpResolveException("EXEC pm1.vsp18()", RealMetadataFactory.example1Cached(), "Group does not exist: temptable"); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     // variable resolution, variable compared against
@@ -1506,7 +1482,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1=1"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-				 FakeMetadataObject.Props.UPDATE_PROCEDURE, "Error Code:ERR.015.008.0041 Message:Cannot set symbol 'pm1.g1.e4' with expected type double to expression 'convert(var1, string)'"); //$NON-NLS-1$
+				 Table.TriggerEvent.UPDATE, "Error Code:ERR.015.008.0041 Message:Cannot set symbol 'pm1.g1.e4' with expected type double to expression 'convert(var1, string)'"); //$NON-NLS-1$
     }
     
     // special variable INPUT compared against invalid type
@@ -1521,48 +1497,48 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailUpdateProcedure(procedure, userUpdateStr,
-				 FakeMetadataObject.Props.UPDATE_PROCEDURE, "Error Code:ERR.015.008.0041 Message:Cannot set symbol 'pm1.g1.e2' with expected type integer to expression 'INPUTS.e1'"); //$NON-NLS-1$
+				 Table.TriggerEvent.UPDATE, "Error Code:ERR.015.008.0041 Message:Cannot set symbol 'pm1.g1.e2' with expected type integer to expression 'INPUTS.e1'"); //$NON-NLS-1$
     }
     
     @Test public void testVirtualProcedure() throws Exception {
-        helpResolve("EXEC pm1.vsp1()", FakeMetadataFactory.example1Cached());   //$NON-NLS-1$
+        helpResolve("EXEC pm1.vsp1()", RealMetadataFactory.example1Cached());   //$NON-NLS-1$
     }
     
     @Test public void testVirtualProcedure2() throws Exception {
-        helpResolve("EXEC pm1.vsp14()", FakeMetadataFactory.example1Cached());   //$NON-NLS-1$
+        helpResolve("EXEC pm1.vsp14()", RealMetadataFactory.example1Cached());   //$NON-NLS-1$
     }
     
     @Test public void testVirtualProcedurePartialParameterReference() throws Exception {
-        helpResolve("EXEC pm1.vsp58(5)", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpResolve("EXEC pm1.vsp58(5)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
     
     //cursor starts with "#" Defect14924
     @Test public void testVirtualProcedureInvalid1() throws Exception {
-    	helpResolveException("EXEC pm1.vsp32()",FakeMetadataFactory.example1Cached(), "Cursor names cannot begin with \"#\" as that indicates the name of a temporary table: #mycursor.");   //$NON-NLS-1$ //$NON-NLS-2$
+    	helpResolveException("EXEC pm1.vsp32()",RealMetadataFactory.example1Cached(), "Cursor names cannot begin with \"#\" as that indicates the name of a temporary table: #mycursor.");   //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testVirtualProcedureWithOrderBy() throws Exception {
-        helpResolve("EXEC pm1.vsp29()", FakeMetadataFactory.example1Cached());   //$NON-NLS-1$
+        helpResolve("EXEC pm1.vsp29()", RealMetadataFactory.example1Cached());   //$NON-NLS-1$
     }
     
     @Test public void testVirtualProcedureWithTempTableAndOrderBy() throws Exception {
-        helpResolve("EXEC pm1.vsp33()", FakeMetadataFactory.example1Cached());   //$NON-NLS-1$
+        helpResolve("EXEC pm1.vsp33()", RealMetadataFactory.example1Cached());   //$NON-NLS-1$
     }
     
     @Test public void testVirtualProcedureWithConstAndOrderBy() throws Exception {
-        helpResolve("EXEC pm1.vsp34()", FakeMetadataFactory.example1Cached());   //$NON-NLS-1$
+        helpResolve("EXEC pm1.vsp34()", RealMetadataFactory.example1Cached());   //$NON-NLS-1$
     }
     
     @Test public void testVirtualProcedureWithNoFromAndOrderBy() throws Exception {
-        helpResolve("EXEC pm1.vsp28()", FakeMetadataFactory.example1Cached());   //$NON-NLS-1$
+        helpResolve("EXEC pm1.vsp28()", RealMetadataFactory.example1Cached());   //$NON-NLS-1$
     }
     
     @Test public void testInvalidVirtualProcedure2() throws Exception {
-        helpResolveException("EXEC pm1.vsp12()", FakeMetadataFactory.example1Cached(), "Symbol mycursor.e2 is specified with an unknown group context"); //$NON-NLS-1$ //$NON-NLS-2$
+        helpResolveException("EXEC pm1.vsp12()", RealMetadataFactory.example1Cached(), "Symbol mycursor.e2 is specified with an unknown group context"); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testLoopRedefinition2() throws Exception {
-        helpResolveException("EXEC pm1.vsp11()", FakeMetadataFactory.example1Cached(), "Nested Loop can not use the same cursor name as that of its parent."); //$NON-NLS-1$ //$NON-NLS-2$
+        helpResolveException("EXEC pm1.vsp11()", RealMetadataFactory.example1Cached(), "Nested Loop can not use the same cursor name as that of its parent."); //$NON-NLS-1$ //$NON-NLS-2$
     }
         
     @Test public void testVariableResolutionWithIntervening() throws Exception {
@@ -1574,11 +1550,11 @@
         .append("\n  y = '1';") //$NON-NLS-1$
         .append("\nEND"); //$NON-NLS-1$
         
-        TestResolver.helpResolve(proc.toString(), FakeMetadataFactory.example1Cached()); 
+        TestResolver.helpResolve(proc.toString(), RealMetadataFactory.example1Cached()); 
     }
     
     @Test public void testVDBQualified() throws Exception {
-        helpResolve("EXEC myvdb.pm1.vsp29()", FakeMetadataFactory.example1Cached());   //$NON-NLS-1$
+        helpResolve("EXEC example1.pm1.vsp29()", RealMetadataFactory.example1Cached());   //$NON-NLS-1$
     }
     
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/resolver/TestResolver.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/resolver/TestResolver.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/resolver/TestResolver.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -47,6 +47,13 @@
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.Table.TriggerEvent;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.function.FunctionDescriptor;
 import org.teiid.query.function.FunctionLibrary;
@@ -55,6 +62,7 @@
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TempMetadataID;
 import org.teiid.query.metadata.TempMetadataStore;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.optimizer.FakeFunctionMetadataSource;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.sql.LanguageObject;
@@ -85,26 +93,21 @@
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.symbol.Reference;
-import org.teiid.query.sql.symbol.SelectSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.visitor.CommandCollectorVisitor;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
 import org.teiid.query.sql.visitor.FunctionCollectorVisitor;
 import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.unittest.TimestampUtil;
 
 @SuppressWarnings("nls")
 public class TestResolver {
 
-	private FakeMetadataFacade metadata;
+	private QueryMetadataInterface metadata;
 
 	@Before public void setUp() {
-		metadata = FakeMetadataFactory.example1Cached();
+		metadata = RealMetadataFactory.example1Cached();
 	}
 
 	// ################################## TEST HELPERS ################################
@@ -131,9 +134,9 @@
 
         assertTrue("Expected variables size " + variableNames.length + " but was " + variables.size(),  //$NON-NLS-1$ //$NON-NLS-2$
                    variables.size() == variableNames.length);
-        Iterator variablesIter = variables.iterator();
+        Iterator<ElementSymbol> variablesIter = variables.iterator();
         for (int i=0; variablesIter.hasNext(); i++) {
-            ElementSymbol variable = (ElementSymbol)variablesIter.next();
+            ElementSymbol variable = variablesIter.next();
             assertTrue("Expected variable name " + variableNames[i] + " but was " + variable.getName(),  //$NON-NLS-1$ //$NON-NLS-2$
                        variable.getName().equalsIgnoreCase(variableNames[i]));
         }
@@ -277,44 +280,44 @@
 	
 	private void helpCheckFrom(Query query, String[] groupIDs) { 
 		From from = query.getFrom();
-		List groups = from.getGroups();			
+		List<GroupSymbol> groups = from.getGroups();			
 		assertEquals("Wrong number of group IDs: ", groupIDs.length, groups.size()); //$NON-NLS-1$
 		
 		for(int i=0; i<groups.size(); i++) { 
-			GroupSymbol group = (GroupSymbol) groups.get(i);
-            String matchString = null;
-            if(group.getMetadataID() instanceof FakeMetadataObject) {
-                matchString = ((FakeMetadataObject)group.getMetadataID()).getName();
-            } else if(group.getMetadataID() instanceof TempMetadataID) {
-                matchString = ((TempMetadataID)group.getMetadataID()).getID();
-            }
-			assertEquals("Group ID does not match: ", groupIDs[i].toUpperCase(), matchString.toUpperCase()); //$NON-NLS-1$
+			GroupSymbol group = groups.get(i);
+			assertNotNull(group.getMetadataID());
+			assertEquals("Group ID does not match: ", groupIDs[i].toUpperCase(), group.getNonCorrelationName().toUpperCase()); //$NON-NLS-1$
 		}
 	}
 	
 	private void helpCheckSelect(Query query, String[] elementNames) {
 		Select select = query.getSelect();
-		List elements = select.getSymbols();
+		List<SingleElementSymbol> elements = select.getProjectedSymbols();
 		assertEquals("Wrong number of select symbols: ", elementNames.length, elements.size()); //$NON-NLS-1$
 
 		for(int i=0; i<elements.size(); i++) {
-			SelectSymbol symbol = (SelectSymbol) elements.get(i);
+			SingleElementSymbol symbol = elements.get(i);
 			assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
 		}
 	}
 
 	private void helpCheckElements(LanguageObject langObj, String[] elementNames, String[] elementIDs) {
-		List elements = new ArrayList();
+		List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
 		ElementCollectorVisitor.getElements(langObj, elements);
 		assertEquals("Wrong number of elements: ", elementNames.length, elements.size()); //$NON-NLS-1$
 
 		for(int i=0; i<elements.size(); i++) { 
-			ElementSymbol symbol = (ElementSymbol) elements.get(i);
+			ElementSymbol symbol = elements.get(i);
 			assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
 			
-			FakeMetadataObject elementID = (FakeMetadataObject) symbol.getMetadataID();
-			assertNotNull("ElementSymbol " + symbol + " was not resolved and has no metadataID", elementID); //$NON-NLS-1$ //$NON-NLS-2$
-			assertEquals("ElementID name does not match: ", elementIDs[i].toUpperCase(), elementID.getName().toUpperCase()); //$NON-NLS-1$
+			Object elementID = symbol.getMetadataID();
+			try {
+				String name = metadata.getFullName(elementID);
+				assertNotNull("ElementSymbol " + symbol + " was not resolved and has no metadataID", elementID); //$NON-NLS-1$ //$NON-NLS-2$
+				assertEquals("ElementID name does not match: ", elementIDs[i].toUpperCase(), name.toUpperCase()); //$NON-NLS-1$
+			} catch (TeiidComponentException e) {
+				throw new RuntimeException(e);
+			}
 		}
 	}
     
@@ -390,84 +393,84 @@
 	}
 
     @Test public void testGroupWithVDB() {
-        String sql = "SELECT e1 FROM myvdb.pm1.g1"; //$NON-NLS-1$
+        String sql = "SELECT e1 FROM example1.pm1.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
         assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString()); //$NON-NLS-1$
     }
 
     @Test public void testAliasedGroupWithVDB() {
-        String sql = "SELECT e1 FROM myvdb.pm1.g1 AS x"; //$NON-NLS-1$
+        String sql = "SELECT e1 FROM example1.pm1.g1 AS x"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
         assertEquals("Resolved string form was incorrect ", sql, resolvedQuery.toString());         //$NON-NLS-1$
     }
     
     @Test public void testPartiallyQualifiedGroup1() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
     }    
     
     @Test public void testPartiallyQualifiedGroup2() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM cat1.g2"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.g2" }); //$NON-NLS-1$
     }
     
     @Test public void testPartiallyQualifiedGroup3() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM cat1.cat2.cat3.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
     }
     
     @Test public void testPartiallyQualifiedGroup4() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM cat2.g2"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm2.cat2.g2" }); //$NON-NLS-1$
     }
     
     @Test public void testPartiallyQualifiedGroup5() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM cat2.g3"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm1.cat2.g3" }); //$NON-NLS-1$
     }    
     
     @Test public void testPartiallyQualifiedGroup6() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM cat1.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm2.cat1.g1" }); //$NON-NLS-1$
     }    
     
     @Test public void testPartiallyQualifiedGroup7() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM g4"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
-        helpCheckFrom(resolvedQuery, new String[] { "pm2.g4" }); //$NON-NLS-1$
+        helpCheckFrom(resolvedQuery, new String[] { "pm3.g4" }); //$NON-NLS-1$
     }    
     
     @Test public void testPartiallyQualifiedGroup8() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT e1 FROM pm2.g3"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm2.g3" }); //$NON-NLS-1$
     }
     
     @Test public void testPartiallyQualifiedGroupWithAlias() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT X.e1 FROM cat2.cat3.g1 as X"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckFrom(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1" }); //$NON-NLS-1$
     } 
     
     @Test public void testPartiallyQualifiedElement1() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT cat2.cat3.g1.e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
@@ -475,7 +478,7 @@
 
     /** defect 12536 */
     @Test public void testPartiallyQualifiedElement2() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT cat3.g1.e1 FROM cat2.cat3.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
@@ -483,7 +486,7 @@
     
     /** defect 12536 */
     @Test public void testPartiallyQualifiedElement3() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT cat3.g1.e1 FROM cat2.cat3.g1, cat1.g2"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1" }); //$NON-NLS-1$
@@ -491,86 +494,86 @@
     
     /** defect 12536 */
     @Test public void testPartiallyQualifiedElement4() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT cat3.g1.e1, cat1.g2.e1 FROM cat2.cat3.g1, cat1.g2"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.g2.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
     } 
     
     @Test public void testPartiallyQualifiedElement5() {
-    	metadata = FakeMetadataFactory.example3();
-        String sql = "SELECT cat3.g1.e1, cat1.g2.e1 FROM myvdb.pm1.cat1.cat2.cat3.g1, pm1.cat1.g2"; //$NON-NLS-1$
+    	metadata = RealMetadataFactory.example3();
+        String sql = "SELECT cat3.g1.e1, cat1.g2.e1 FROM example3.pm1.cat1.cat2.cat3.g1, pm1.cat1.g2"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.g2.e1" }); //$NON-NLS-1$ //$NON-NLS-2$
     } 
     
     /** defect 12536 */
     @Test public void testPartiallyQualifiedElement6() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT cat3.g1.e1, e2 FROM cat2.cat3.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
 	    helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.cat2.cat3.g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
     } 
     
     @Test public void testPartiallyQualifiedElement7() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
         String sql = "SELECT cat3.g1.e1, cat2.cat3.g1.e2, g1.e3 FROM pm1.cat1.cat2.cat3.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckSelect(resolvedQuery, new String[] { "pm1.cat1.cat2.cat3.g1.e1", "pm1.cat1.cat2.cat3.g1.e2", "pm1.cat1.cat2.cat3.g1.e3" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     } 
     
     @Test public void testFailPartiallyQualifiedGroup1() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT e1 FROM cat3.g1"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedGroup2() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT e1 FROM g1"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedGroup3() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT e1 FROM g2"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedGroup4() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT e1 FROM g3"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedGroup5() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT e1 FROM g5");		 //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedElement1() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT cat3.g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedElement2() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT g1.e1 FROM pm1.cat1.cat2.cat3.g1, pm2.cat3.g1"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedElement3() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2, pm1.cat2.g3"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedElement4() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT cat3.g1.e1 FROM pm2.cat2.g2"); //$NON-NLS-1$
     }
     
     @Test public void testFailPartiallyQualifiedElement5() {
-    	metadata = FakeMetadataFactory.example3();
+    	metadata = RealMetadataFactory.example3();
 		helpResolveException("SELECT cat3.g1.e1 FROM g1"); //$NON-NLS-1$
     }    
 
     @Test public void testElementWithVDB() {
-        String sql = "SELECT myvdb.pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
+        String sql = "SELECT example1.pm1.g1.e1 FROM pm1.g1"; //$NON-NLS-1$
         Query resolvedQuery = (Query) helpResolve(sql);
         helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.e1" }); //$NON-NLS-1$
         helpCheckElements(resolvedQuery.getSelect(),
@@ -580,7 +583,7 @@
     }
 
     @Test public void testAliasedElementWithVDB() {
-        Query resolvedQuery = (Query) helpResolve("SELECT myvdb.pm1.g1.e1 AS x FROM pm1.g1"); //$NON-NLS-1$
+        Query resolvedQuery = (Query) helpResolve("SELECT example1.pm1.g1.e1 AS x FROM pm1.g1"); //$NON-NLS-1$
         helpCheckSelect(resolvedQuery, new String[] { "x" }); //$NON-NLS-1$
         helpCheckElements(resolvedQuery.getSelect(),
             new String[] { "pm1.g1.e1" }, //$NON-NLS-1$
@@ -590,7 +593,6 @@
 	@Test public void testSelectStar() {
 		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1"); //$NON-NLS-1$
 		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
 		helpCheckElements(resolvedQuery.getSelect(),
 			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
@@ -599,7 +601,6 @@
 	@Test public void testSelectStarFromAliasedGroup() {
 		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1 as x"); //$NON-NLS-1$
 		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
 		helpCheckElements(resolvedQuery.getSelect(),
 			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
@@ -608,7 +609,6 @@
 	@Test public void testSelectStarFromMultipleAliasedGroups() {
 		Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g1 as x, pm1.g1 as y"); //$NON-NLS-1$
 		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1", "pm1.g1" }); //$NON-NLS-1$ //$NON-NLS-2$
-		helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
 		helpCheckElements(resolvedQuery.getSelect(),
 			new String[] { "x.e1", "x.e2", "x.e3", "x.e4", "y.e1", "y.e2", "y.e3", "y.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
 			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4", "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
@@ -617,7 +617,6 @@
     @Test public void testSelectStarWhereSomeElementsAreNotSelectable() {
         Query resolvedQuery = (Query) helpResolve("SELECT * FROM pm1.g4"); //$NON-NLS-1$
         helpCheckFrom(resolvedQuery, new String[] { "pm1.g4" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "*" }); //$NON-NLS-1$
         helpCheckElements(resolvedQuery.getSelect(),
             new String[] { "pm1.g4.e1", "pm1.g4.e3" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { "pm1.g4.e1", "pm1.g4.e3" } ); //$NON-NLS-1$ //$NON-NLS-2$
@@ -626,7 +625,6 @@
     @Test public void testSelectGroupStarWhereSomeElementsAreNotSelectable() {
         Query resolvedQuery = (Query) helpResolve("SELECT pm1.g4.* FROM pm1.g4"); //$NON-NLS-1$
         helpCheckFrom(resolvedQuery, new String[] { "pm1.g4" }); //$NON-NLS-1$
-        helpCheckSelect(resolvedQuery, new String[] { "pm1.g4.*" }); //$NON-NLS-1$
         helpCheckElements(resolvedQuery.getSelect(),
             new String[] { "pm1.g4.e1", "pm1.g4.e3" }, //$NON-NLS-1$ //$NON-NLS-2$
             new String[] { "pm1.g4.e1", "pm1.g4.e3" } ); //$NON-NLS-1$ //$NON-NLS-2$
@@ -635,7 +633,6 @@
 	@Test public void testFullyQualifiedSelectStar() {
 		Query resolvedQuery = (Query) helpResolve("SELECT pm1.g1.* FROM pm1.g1"); //$NON-NLS-1$
 		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "pm1.g1.*" }); //$NON-NLS-1$
 		helpCheckElements(resolvedQuery.getSelect(),
 			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
@@ -644,7 +641,6 @@
 	@Test public void testSelectAllInAliasedGroup() {
 		Query resolvedQuery = (Query) helpResolve("SELECT x.* FROM pm1.g1 as x"); //$NON-NLS-1$
 		helpCheckFrom(resolvedQuery, new String[] { "pm1.g1" }); //$NON-NLS-1$
-		helpCheckSelect(resolvedQuery, new String[] { "x.*" }); //$NON-NLS-1$
 		helpCheckElements(resolvedQuery.getSelect(),
 			new String[] { "x.e1", "x.e2", "x.e3", "x.e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
 			new String[] { "pm1.g1.e1", "pm1.g1.e2", "pm1.g1.e3", "pm1.g1.e4" } ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
@@ -887,15 +883,15 @@
         StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq2('abc')"); //$NON-NLS-1$
         
         // Check number of resolved parameters
-        List params = proc.getParameters();
+        List<SPParameter> params = proc.getParameters();
         assertEquals("Did not get expected parameter count", 2, params.size()); //$NON-NLS-1$
         
         // Check resolved parameters
-        SPParameter param1 = (SPParameter) params.get(0);
-        helpCheckParameter(param1, ParameterInfo.RESULT_SET, 1, "pm1.sq2.ret", java.sql.ResultSet.class, null); //$NON-NLS-1$
+        SPParameter param1 = params.get(1);
+        helpCheckParameter(param1, ParameterInfo.RESULT_SET, 2, "pm1.sq2.ret", java.sql.ResultSet.class, null); //$NON-NLS-1$
 
-        SPParameter param2 = (SPParameter) params.get(1);
-        helpCheckParameter(param2, ParameterInfo.IN, 2, "pm1.sq2.in", DataTypeManager.DefaultDataClasses.STRING, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
+        SPParameter param2 = params.get(0);
+        helpCheckParameter(param2, ParameterInfo.IN, 1, "pm1.sq2.in", DataTypeManager.DefaultDataClasses.STRING, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
 	/**
@@ -911,18 +907,18 @@
 		StoredProcedure proc = (StoredProcedure) helpResolve("EXEC pm1.sq3a('abc', 123)"); //$NON-NLS-1$
 		
 		// Check number of resolved parameters
-		List params = proc.getParameters();
-		assertEquals("Did not get expected parameter count", 2, params.size()); //$NON-NLS-1$
+		List<SPParameter> params = proc.getParameters();
+		assertEquals("Did not get expected parameter count", 3, params.size()); //$NON-NLS-1$
         
 		// Check resolved parameters
-		SPParameter param1 = (SPParameter) params.get(0);
+		SPParameter param1 = params.get(0);
 		helpCheckParameter(param1, ParameterInfo.IN, 1, "pm1.sq3a.in", DataTypeManager.DefaultDataClasses.STRING, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 
-		SPParameter param2 = (SPParameter) params.get(1);
-		helpCheckParameter(param2, ParameterInfo.IN, 3, "pm1.sq3a.in2", DataTypeManager.DefaultDataClasses.INTEGER, new Constant(new Integer(123))); //$NON-NLS-1$
+		SPParameter param2 = params.get(1);
+		helpCheckParameter(param2, ParameterInfo.IN, 2, "pm1.sq3a.in2", DataTypeManager.DefaultDataClasses.INTEGER, new Constant(new Integer(123))); //$NON-NLS-1$
 	}    
     
-    private void helpCheckParameter(SPParameter param, int paramType, int index, String name, Class type, Expression expr) {
+    private void helpCheckParameter(SPParameter param, int paramType, int index, String name, Class<?> type, Expression expr) {
         assertEquals("Did not get expected parameter type", paramType, param.getParameterType()); //$NON-NLS-1$
         assertEquals("Did not get expected index for param", index, param.getIndex()); //$NON-NLS-1$
         assertEquals("Did not get expected name for param", name, param.getName()); //$NON-NLS-1$
@@ -1116,7 +1112,7 @@
             "WHERE (y.IntKey >= 10) AND (y.IntKey < 30) " + //$NON-NLS-1$
             "ORDER BY IntKey, FloatNum";  //$NON-NLS-1$
 
-        helpResolve(sql, FakeMetadataFactory.exampleBQTCached());
+        helpResolve(sql, RealMetadataFactory.exampleBQTCached());
     }
 
     @Test public void testSubQueryINClause1(){
@@ -1334,7 +1330,7 @@
         String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
         Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
         
-		FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                         
+		FunctionLibrary library = RealMetadataFactory.SFM.getSystemFunctionLibrary();                         
 		FunctionDescriptor fd = library.findFunction(FunctionLibrary.CONVERT, new Class[] { srcType, DataTypeManager.DefaultDataClasses.STRING });
 
 		Function conversion = new Function(fd.getName(), new Expression[] { expression, new Constant(tgtTypeName) });
@@ -1370,7 +1366,7 @@
 		String tgtTypeName = DataTypeManager.DefaultDataTypes.DATE;
 		Expression expression = new Constant("2003-02-27"); //$NON-NLS-1$
         
-		FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                        
+		FunctionLibrary library = RealMetadataFactory.SFM.getSystemFunctionLibrary();                        
 		FunctionDescriptor fd = library.findFunction(FunctionLibrary.CONVERT, new Class[] { srcType, DataTypeManager.DefaultDataClasses.STRING });
 
 		Function conversion = new Function(fd.getName(), new Expression[] { expression, new Constant(tgtTypeName) });
@@ -1488,13 +1484,13 @@
 	@Test public void testLookupFunctionVirtualGroup() throws Exception {     
 		String sql = "SELECT lookup('vm1.g1', 'e1', 'e2', e2)  FROM vm1.g1 "; //$NON-NLS-1$
 		Query command = (Query) helpParse(sql);
-		QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());  		
+		QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());  		
 	}
 	
 	@Test public void testLookupFunctionPhysicalGroup() throws Exception {     
 		String sql = "SELECT lookup('pm1.g1', 'e1', 'e2', e2)  FROM pm1.g1 "; //$NON-NLS-1$
 		Query command = (Query) helpParse(sql);
-		QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+		QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
 	}
 	
     @Test public void testLookupFunctionFailBadKeyElement() throws Exception {
@@ -1511,15 +1507,13 @@
 	@Test public void testNamespacedFunction() throws Exception {     
 		String sql = "SELECT namespace.func('e1')  FROM vm1.g1 "; //$NON-NLS-1$
 
-        FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new FakeFunctionMetadataSource()));
-        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.example1Cached().getMetadataStore(), "example1", new FunctionTree("foo", new FakeFunctionMetadataSource()));
 		
 		Query command = (Query) helpParse(sql);
 		QueryResolver.resolveCommand(command, metadata);
 		
 		command = (Query) helpParse("SELECT func('e1')  FROM vm1.g1 ");
 		QueryResolver.resolveCommand(command, metadata);  		
-		
 	}    
     
     // special test for both sides are String
@@ -1537,8 +1531,8 @@
    
         // resolve
         try { 
-            QueryResolver.resolveCriteria(expected, FakeMetadataFactory.exampleBQTCached());
-            QueryResolver.resolveCriteria(actual, FakeMetadataFactory.exampleBQTCached());
+            QueryResolver.resolveCriteria(expected, RealMetadataFactory.exampleBQTCached());
+            QueryResolver.resolveCriteria(actual, RealMetadataFactory.exampleBQTCached());
         } catch(TeiidException e) { 
             fail("Exception during resolution (" + e.getClass().getName() + "): " + e.getMessage());     //$NON-NLS-1$ //$NON-NLS-2$
         } 
@@ -1834,7 +1828,7 @@
         //String sql = "select intkey from SmallA where user() = 'bqt2'";
 
         // Expected left expression
-        FunctionLibrary library = FakeMetadataFactory.SFM.getSystemFunctionLibrary();                          
+        FunctionLibrary library = RealMetadataFactory.SFM.getSystemFunctionLibrary();                          
         FunctionDescriptor fd = library.findFunction(FunctionLibrary.USER, new Class[] { });
         Function user = new Function(fd.getName(), new Expression[] {});
         user.setFunctionDescriptor(fd);
@@ -1890,7 +1884,7 @@
  
     @Test public void testDefect10809(){
         String sql = "select * from LOB_TESTING_ONE where CLOB_COLUMN LIKE '%fff%'"; //$NON-NLS-1$
-        helpResolve(helpParse(sql), FakeMetadataFactory.exampleBQTCached());
+        helpResolve(helpParse(sql), RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testNonAutoConversionOfLiteralIntegerToShort() throws Exception {       
@@ -1898,7 +1892,7 @@
         Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE shortvalue = 5"); //$NON-NLS-1$
         
         // resolve
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.exampleBQTCached());
         
         // Check whether an implicit conversion was added on the correct side
         CompareCriteria crit = (CompareCriteria) command.getCriteria();
@@ -1912,7 +1906,7 @@
         Query command = (Query) QueryParser.getQueryParser().parseCommand("SELECT intkey FROM bqt1.smalla WHERE 5 = shortvalue"); //$NON-NLS-1$
         
         // resolve
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.exampleBQTCached());
         
         // Check whether an implicit conversion was added on the correct side
         CompareCriteria crit = (CompareCriteria) command.getCriteria();
@@ -1974,30 +1968,23 @@
         assertTrue(((Expression)command.getValues().get(0)).getType() == DataTypeManager.DefaultDataClasses.SHORT);
     }
     
-    public static FakeMetadataFacade example_12968() { 
+    public static TransformationMetadata example_12968() { 
+    	MetadataStore metadataStore = new MetadataStore();
         // Create models
-        FakeMetadataObject pm1 = FakeMetadataFactory.createPhysicalModel("myModel"); //$NON-NLS-1$
-        FakeMetadataObject pm2 = FakeMetadataFactory.createPhysicalModel("myModel2"); //$NON-NLS-1$
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("myModel", metadataStore); //$NON-NLS-1$
+        Schema pm2 = RealMetadataFactory.createPhysicalModel("myModel2", metadataStore); //$NON-NLS-1$
         
-        FakeMetadataObject pm1g1 = FakeMetadataFactory.createPhysicalGroup("myModel.myTable", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm2g1 = FakeMetadataFactory.createPhysicalGroup("myModel2.mySchema.myTable2", pm2); //$NON-NLS-1$
+        Table pm1g1 = RealMetadataFactory.createPhysicalGroup("myTable", pm1); //$NON-NLS-1$
+        Table pm2g1 = RealMetadataFactory.createPhysicalGroup("mySchema.myTable2", pm2); //$NON-NLS-1$
         
-        List pm1g1e = FakeMetadataFactory.createElements(pm1g1, 
+        RealMetadataFactory.createElements(pm1g1, 
             new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List pm2g1e = FakeMetadataFactory.createElements(pm2g1, 
+        RealMetadataFactory.createElements(pm2g1, 
             new String[] { "myColumn", "myColumn2" }, //$NON-NLS-1$ //$NON-NLS-2$ 
             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
         
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
-        store.addObject(pm2g1);     
-        store.addObjects(pm2g1e);
-        
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "12968");
     }
         
     @Test public void testDefect12968_union() {
@@ -2109,7 +2096,7 @@
     @Test public void testProcParamComparison_defect13653() {
         String userSql = "SELECT * FROM (EXEC mmspTest1.MMSP5('a')) AS a, (EXEC mmsptest1.mmsp6('b')) AS b"; //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         AnalysisRecord analysis = AnalysisRecord.createNonRecordingRecord();
         
         Query query = (Query) helpResolve(userSql, metadata);
@@ -2140,7 +2127,7 @@
         String userSql = "SELECT null as x"; //$NON-NLS-1$
         Query query = (Query)helpParse(userSql);
         
-        QueryResolver.resolveCommand(query, FakeMetadataFactory.exampleBQTCached());
+        QueryResolver.resolveCommand(query, RealMetadataFactory.exampleBQTCached());
         
         // Check type of resolved null constant
         SingleElementSymbol symbol = (SingleElementSymbol) query.getSelect().getSymbols().get(0);
@@ -2195,7 +2182,7 @@
     @Test public void testUnionInSubquery() throws Exception {
         String sql = "SELECT StringKey FROM (SELECT BQT2.SmallB.StringKey FROM BQT2.SmallB union SELECT convert(BQT2.SmallB.FloatNum, string) FROM BQT2.SmallB) x";  //$NON-NLS-1$
         Command command = QueryParser.getQueryParser().parseCommand(sql);
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.exampleBQTCached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.exampleBQTCached());
     }
 
     @Test public void testParameterError() throws Exception {
@@ -2357,7 +2344,7 @@
 
     @Test public void testCreateAlreadyExists() {
         String sql = "CREATE LOCAL TEMPORARY TABLE g1 (column1 string)"; //$NON-NLS-1$
-        helpResolveException(sql, "Cannot create temporary table \"g1\". A table with the same name already exists."); //$NON-NLS-1$
+        helpResolveException(sql, "Cannot create temporary table \"g1\". An object with the same name already exists."); //$NON-NLS-1$
     }
 
     @Test public void testCreateImplicitName() {
@@ -2367,7 +2354,7 @@
     }
     
     @Test public void testCreateInProc() throws Exception{
-        helpResolveException("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table g1(c1 string); end", "Cannot create temporary table \"g1\". A table with the same name already exists.");//$NON-NLS-1$ //$NON-NLS-2$
+        helpResolveException("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table g1(c1 string); end", "Cannot create temporary table \"g1\". An object with the same name already exists.");//$NON-NLS-1$ //$NON-NLS-2$
     }
     
     //this was the old virt.agg procedure.  It was defined in such a way that relied on the scope leak of #temp
@@ -2388,7 +2375,7 @@
             + "        SELECT ID, Name, #temp.BITS AS source_bits FROM #temp;" //$NON-NLS-1$                                          
             + "END"; //$NON-NLS-1$ 
         
-        helpResolveException(proc, FakeMetadataFactory.exampleBitwise(), "Group does not exist: #temp"); //$NON-NLS-1$
+        helpResolveException(proc, RealMetadataFactory.exampleBitwise(), "Group does not exist: #temp"); //$NON-NLS-1$
     }
     
     @Test public void testDrop() {
@@ -2530,21 +2517,17 @@
     }
     
     @Test public void testExecWithDuplicateNames() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        
-        FakeMetadataStore store = metadata.getStore();
-        
-        FakeMetadataObject pm1 = store.findObject("pm1", FakeMetadataObject.MODEL); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("pm1.rs2", pm1, new String[] { "in", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq2 = FakeMetadataFactory.createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
+        MetadataStore metadataStore = new MetadataStore();
 
-        store.addObject(rs2);
-        store.addObject(sq2);
+        Schema pm1 = RealMetadataFactory.createPhysicalModel("pm1", metadataStore);
         
+        ColumnSet<Procedure> rs2 = RealMetadataFactory.createResultSet("rs2", new String[] { "in", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs2p2 = RealMetadataFactory.createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        Procedure sq2 = RealMetadataFactory.createStoredProcedure("sq2", pm1, Arrays.asList(rs2p2));  //$NON-NLS-1$
+        sq2.setResultSet(rs2);
+
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
+
         helpResolveException("select * from pm1.sq2", metadata, "Cannot access procedure pm1.sq2 using table semantics since the parameter and result set column names are not all unique."); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
@@ -2627,6 +2610,11 @@
         helpResolveException(sql, "Cannot convert insert query expression projected symbol '3' of type java.lang.Integer to insert column 'pm1.g1.e3' of type java.lang.Boolean"); //$NON-NLS-1$
     }
     
+    @Test public void testInsertWithQueryImplicitWithColumns() {
+        String sql = "Insert into #X (x) select 1 as x"; //$NON-NLS-1$
+        helpResolve(sql); //$NON-NLS-1$
+    }
+    
     @Test public void testInsertWithQueryImplicitWithoutColumns() {
         String sql = "Insert into #X select 1 as x, 2 as y, 3 as z"; //$NON-NLS-1$
         helpResolve(sql); //$NON-NLS-1$
@@ -2670,11 +2658,11 @@
     @Test public void testCase6319() throws QueryResolverException, TeiidComponentException {
         String sql = "select floatnum from bqt1.smalla group by floatnum having sum(floatnum) between 51.0 and 100.0 "; //$NON-NLS-1$
         Query query = (Query)helpParse(sql);
-        QueryResolver.resolveCommand(query, FakeMetadataFactory.exampleBQTCached());
+        QueryResolver.resolveCommand(query, RealMetadataFactory.exampleBQTCached());
     }
 
     @Test public void testUniqeNamesWithInlineView() {
-        helpResolveException("select * from (select count(intNum) a, count(stringKey) b, bqt1.smalla.intkey as b from bqt1.smalla group by bqt1.smalla.intkey) q1 order by q1.a", FakeMetadataFactory.exampleBQTCached(), "Cannot create group 'q1' with multiple columns named 'b'"); //$NON-NLS-1$ //$NON-NLS-2$
+        helpResolveException("select * from (select count(intNum) a, count(stringKey) b, bqt1.smalla.intkey as b from bqt1.smalla group by bqt1.smalla.intkey) q1 order by q1.a", RealMetadataFactory.exampleBQTCached(), "Cannot create group 'q1' with multiple columns named 'b'"); //$NON-NLS-1$ //$NON-NLS-2$
     }
             
     @Test public void testResolveOldProcRelational() {
@@ -2702,13 +2690,13 @@
 	@Test public void testCallableStatementTooManyParameters() throws Exception {
 		String sql = "{call pm4.spTest9(?, ?)}"; //$NON-NLS-1$
 		
-		TestResolver.helpResolveException(sql, FakeMetadataFactory.exampleBQTCached(), "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm4.spTest9 - expected 1 but got 2"); //$NON-NLS-1$
+		TestResolver.helpResolveException(sql, RealMetadataFactory.exampleBQTCached(), "Error Code:ERR.015.008.0007 Message:Incorrect number of parameters specified on the stored procedure pm4.spTest9 - expected 1 but got 2"); //$NON-NLS-1$
 	}	
 	    
     @Test public void testUpdateSetClauseReferenceType() {
     	String sql = "UPDATE pm1.g1 SET pm1.g1.e1 = 1, pm1.g1.e2 = ?;"; //$NON-NLS-1$
     	
-    	Update update = (Update)helpResolve(sql, FakeMetadataFactory.example1Cached());
+    	Update update = (Update)helpResolve(sql, RealMetadataFactory.example1Cached());
     	
     	Expression ref = update.getChangeList().getClauses().get(1).getValue();
     	assertTrue(ref instanceof Reference);
@@ -2718,26 +2706,26 @@
     @Test public void testNoTypeCriteria() {
     	String sql = "select * from pm1.g1 where ? = ?"; //$NON-NLS-1$
     	
-    	helpResolveException(sql, FakeMetadataFactory.example1Cached(), "Error Code:ERR.015.008.0026 Message:Expression '? = ?' has a parameter with non-determinable type information.  The use of an explicit convert may be necessary."); //$NON-NLS-1$
+    	helpResolveException(sql, RealMetadataFactory.example1Cached(), "Error Code:ERR.015.008.0026 Message:Expression '? = ?' has a parameter with non-determinable type information.  The use of an explicit convert may be necessary."); //$NON-NLS-1$
     }
     
     @Test public void testReferenceInSelect() {
     	String sql = "select ?, e1 from pm1.g1"; //$NON-NLS-1$
-    	Query command = (Query)helpResolve(sql, FakeMetadataFactory.example1Cached());
+    	Query command = (Query)helpResolve(sql, RealMetadataFactory.example1Cached());
     	assertEquals(DataTypeManager.DefaultDataClasses.STRING, command.getProjectedSymbols().get(0).getType());
     }
     
     @Test public void testReferenceInSelect1() {
     	String sql = "select convert(?, integer), e1 from pm1.g1"; //$NON-NLS-1$
     	
-    	Query command = (Query)helpResolve(sql, FakeMetadataFactory.example1Cached());
+    	Query command = (Query)helpResolve(sql, RealMetadataFactory.example1Cached());
     	assertEquals(DataTypeManager.DefaultDataClasses.INTEGER, command.getProjectedSymbols().get(0).getType());
     }
     
     @Test public void testUnionWithObjectTypeConversion() {
     	String sql = "select convert(null, xml) from pm1.g1 union all select 1"; //$NON-NLS-1$
     	
-    	SetQuery query = (SetQuery)helpResolve(sql, FakeMetadataFactory.example1Cached());
+    	SetQuery query = (SetQuery)helpResolve(sql, RealMetadataFactory.example1Cached());
     	assertEquals(DataTypeManager.DefaultDataClasses.OBJECT, ((SingleElementSymbol)query.getProjectedSymbols().get(0)).getType());
     }
     
@@ -2780,7 +2768,7 @@
     }
     
     @Test public void testSPOutParamWithExec() {
-    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm2.spTest8(1)", FakeMetadataFactory.exampleBQTCached());
+    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm2.spTest8(1)", RealMetadataFactory.exampleBQTCached());
     	assertEquals(2, proc.getProjectedSymbols().size());
     }
 
@@ -2789,21 +2777,21 @@
      * That hack is handled by the PreparedStatementRequest
      */
     @Test public void testSPOutParamWithCallableStatement() {
-    	StoredProcedure proc = (StoredProcedure)helpResolve("{call pm2.spTest8(1)}", FakeMetadataFactory.exampleBQTCached());
+    	StoredProcedure proc = (StoredProcedure)helpResolve("{call pm2.spTest8(1)}", RealMetadataFactory.exampleBQTCached());
     	assertEquals(3, proc.getProjectedSymbols().size());
     }
     
     @Test public void testOutWithWrongType() {
-    	helpResolveException("exec pm2.spTest8(inkey=>1, outkey=>{t '12:00:00'})", FakeMetadataFactory.exampleBQTCached());
+    	helpResolveException("exec pm2.spTest8(inkey=>1, outkey=>{t '12:00:00'})", RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testProcRelationalWithOutParam() {
-    	Query proc = (Query)helpResolve("select * from pm2.spTest8 where inkey = 1", FakeMetadataFactory.exampleBQTCached());
+    	Query proc = (Query)helpResolve("select * from pm2.spTest8 where inkey = 1", RealMetadataFactory.exampleBQTCached());
     	assertEquals(3, proc.getProjectedSymbols().size());
     }
     
     @Test public void testSPReturnParamWithNoResultSet() {
-    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm4.spTest9(1)", FakeMetadataFactory.exampleBQTCached());
+    	StoredProcedure proc = (StoredProcedure)helpResolve("exec pm4.spTest9(1)", RealMetadataFactory.exampleBQTCached());
     	assertEquals(1, proc.getProjectedSymbols().size());
     }
     
@@ -2930,7 +2918,7 @@
 			String userUpdateStr) throws QueryParserException,
 			QueryResolverException, TeiidComponentException,
 			QueryMetadataException {
-		FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure);
+		QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(TriggerEvent.UPDATE, procedure);
 
         ProcedureContainer userCommand = (ProcedureContainer)QueryParser.getQueryParser().parseCommand(userUpdateStr);
         QueryResolver.resolveCommand(userCommand, metadata);
@@ -2989,4 +2977,14 @@
 
         helpResolveUpdateProcedure(procedure, userQuery);
 	}
+    
+    @Test public void testTrim() {
+    	Query query = (Query)helpResolve("select trim(e1) from pm1.g1");
+    	assertEquals(DataTypeManager.DefaultDataClasses.STRING, query.getProjectedSymbols().get(0).getType());
+    }
+    
+    @Test public void testTrim1() {
+    	helpResolve("select trim('x' from e1) from pm1.g1");
+    }
+
 }
\ No newline at end of file

Modified: branches/as7/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/resolver/TestXMLResolver.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,8 +22,9 @@
 
 package org.teiid.query.resolver;
 
-import junit.framework.TestCase;
+import static org.junit.Assert.*;
 
+import org.junit.Test;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.util.ResolverUtil;
 import org.teiid.query.sql.lang.Command;
@@ -35,26 +36,26 @@
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
-public class TestXMLResolver extends TestCase {
+public class TestXMLResolver {
     
     public Command helpResolve(String sql) {
-        Command cmd = TestResolver.helpResolve(sql, FakeMetadataFactory.example1Cached());
+        Command cmd = TestResolver.helpResolve(sql, RealMetadataFactory.example1Cached());
         ResolverUtil.fullyQualifyElements(cmd);
         return cmd;
     }
     
     public void helpResolveException(String sql) {
-        TestResolver.helpResolveException(sql, FakeMetadataFactory.example1Cached());
+        TestResolver.helpResolveException(sql, RealMetadataFactory.example1Cached());
     }
     
     public void helpResolveException(String sql, String expectedMessage) {
-        TestResolver.helpResolveException(sql, FakeMetadataFactory.example1Cached(), expectedMessage);
+        TestResolver.helpResolveException(sql, RealMetadataFactory.example1Cached(), expectedMessage);
     }
 
-    public void testXMLCriteriaShortElement() {
+    @Test public void testXMLCriteriaShortElement() {
         CompareCriteria expected = new CompareCriteria();
         GroupSymbol gs = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es = new ElementSymbol("root.node1", null, gs); //$NON-NLS-1$
@@ -67,7 +68,7 @@
         assertEquals("Did not match expected criteria", expected, actual);     //$NON-NLS-1$
     }   
 
-    public void testXMLCriteriaLongElement1() {
+    @Test public void testXMLCriteriaLongElement1() {
         CompareCriteria expected = new CompareCriteria();
         GroupSymbol gs = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es = new ElementSymbol("root.node1", null, gs); //$NON-NLS-1$
@@ -81,7 +82,7 @@
         assertEquals("Did not match expected criteria", expected, actual);     //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElement2() {
+    @Test public void testXMLCriteriaLongElement2() {
         CompareCriteria expected1 = new CompareCriteria();
         GroupSymbol gs = new GroupSymbol("xmltest.doc4"); //$NON-NLS-1$
         ElementSymbol es1 = new ElementSymbol("root.node1", null, gs); //$NON-NLS-1$
@@ -94,7 +95,7 @@
         assertEquals("Did not match expected criteria", expected1, actual); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElement3() {
+    @Test public void testXMLCriteriaLongElement3() {
         GroupSymbol gs = new GroupSymbol("xmltest.doc4"); //$NON-NLS-1$
         CompareCriteria expected2 = new CompareCriteria();
         ElementSymbol es2 = new ElementSymbol("root.node1. at node2", null, gs); //$NON-NLS-1$
@@ -108,7 +109,7 @@
         assertEquals("Did not match expected criteria", expected2, actual); //$NON-NLS-1$
     }
         
-    public void testXMLCriteriaLongElement4() {
+    @Test public void testXMLCriteriaLongElement4() {
         GroupSymbol gs = new GroupSymbol("xmltest.doc4"); //$NON-NLS-1$
         CompareCriteria expected3 = new CompareCriteria();
         ElementSymbol es3 = new ElementSymbol("root.node3", null, gs); //$NON-NLS-1$
@@ -121,76 +122,76 @@
         assertEquals("Did not match expected criteria", expected3, actual);                 //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElement5() {
+    @Test public void testXMLCriteriaLongElement5() {
         helpResolve("select * from xmltest.doc4 where root.node1 = 'yyz'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElement6() {
+    @Test public void testXMLCriteriaLongElement6() {
         helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'yyz'"); //$NON-NLS-1$
     } 
 
-    public void testXMLCriteriaLongElement7() {    
+    @Test public void testXMLCriteriaLongElement7() {    
         helpResolve("select * from xmltest.doc4 where root.node3 = 'yyz'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElement8() {    
+    @Test public void testXMLCriteriaLongElement8() {    
         helpResolve("select * from xmltest.doc4 where node3 = 'yyz'");         //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElementFail1() {    
+    @Test public void testXMLCriteriaLongElementFail1() {    
         helpResolveException("select * from xmltest.doc4 where node3.node1.node2 = 'xyz'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElementFail2() {    
+    @Test public void testXMLCriteriaLongElementFail2() {    
         helpResolveException("select * from xmltest.doc4 where root.node1.node2.node3 = 'xyz'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElementFail3() {    
+    @Test public void testXMLCriteriaLongElementFail3() {    
         helpResolveException("select * from xmltest.doc4 where root.node1.node3 = 'xyz'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElementFail4() {    
+    @Test public void testXMLCriteriaLongElementFail4() {    
         helpResolveException("select * from xmltest.doc4 where node2.node1.node2 = 'xyz'");                              //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaTempElement1() {
+    @Test public void testXMLCriteriaTempElement1() {
         helpResolve("select * from xmltest.doc4 where tm1.g1.e1 = 'x'"); //$NON-NLS-1$
     } 
     
-    public void testXMLCriteriaTempElement2() {
+    @Test public void testXMLCriteriaTempElement2() {
         helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'yyz' and tm1.g1.e2 = 'y'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaTempElement3() {
+    @Test public void testXMLCriteriaTempElement3() {
         helpResolve("select * from xmltest.doc4 where tm1.g1.e1 = 'x' and tm1.g1.e2 = 'y'"); //$NON-NLS-1$
     }
 
-    public void testXMLCriteriaTempElementFail1() {    
+    @Test public void testXMLCriteriaTempElementFail1() {    
         helpResolveException("select * from xmltest.doc4 where tm1.g2.e1 = 'xyz'"); //$NON-NLS-1$
     } 
     
-    public void testXMLCriteriaTempElementFail2() {
+    @Test public void testXMLCriteriaTempElementFail2() {
         helpResolveException("select * from xmltest.doc4 where root.node1.node2.node3 = 'xyz' and e1 = 'x'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaTempElementFail3() {
+    @Test public void testXMLCriteriaTempElementFail3() {
         helpResolveException("select * from xmltest.doc4 where e3 = 'xyz' and tm1.g2.e4='m'"); //$NON-NLS-1$
     }
 
     //tests ambiguously-named elements in both root temp group and document
-    public void testXMLAmbiguousName1() {
+    @Test public void testXMLAmbiguousName1() {
         helpResolve("select * from xmltest.doc4 where root.node1 is null"); //$NON-NLS-1$
     }
     
-    public void testXMLAmbiguousName2() {
+    @Test public void testXMLAmbiguousName2() {
         helpResolve("select * from xmltest.doc4 where tm1.g1.node1 = 'yyz'"); //$NON-NLS-1$
     }
     
-    public void testXMLAmbiguousName3() {
+    @Test public void testXMLAmbiguousName3() {
         helpResolveException("select * from xmltest.doc4 where node1 = 'yyz'"); //$NON-NLS-1$
     }    
 
-    public void testXMLCriteriaLongElementInAnonymous() {                  
+    @Test public void testXMLCriteriaLongElementInAnonymous() {                  
         CompareCriteria expected = new CompareCriteria();
         GroupSymbol gs = new GroupSymbol("xmltest.doc2"); //$NON-NLS-1$
         ElementSymbol es = new ElementSymbol("root.node1.node3", null, gs); //$NON-NLS-1$
@@ -203,7 +204,7 @@
         assertEquals("Did not match expected criteria", expected, actual);     //$NON-NLS-1$
     }    
 
-    public void testXMLAmbiguousShortName() {                  
+    @Test public void testXMLAmbiguousShortName() {                  
         CompareCriteria expected = new CompareCriteria();
         ElementSymbol es = new ElementSymbol("node2"); //$NON-NLS-1$
         GroupSymbol gs = new GroupSymbol("doc3"); //$NON-NLS-1$
@@ -218,95 +219,95 @@
     /**
      * defect 9745
      */
-    public void testXMLAttributeInCriteria() {
+    @Test public void testXMLAttributeInCriteria() {
         helpResolve("select * from xmltest.doc4 where root.node1. at node2 = 'x'"); //$NON-NLS-1$
     }
 
     /**
      * defect 9745
      */
-    public void testXMLAttributeInCriteria2() {
+    @Test public void testXMLAttributeInCriteria2() {
         helpResolve("select * from xmltest.doc4 where root.node1.node2 = 'x'"); //$NON-NLS-1$
     }
 
     /**
      * defect 9745
      */
-    public void testXMLAttributeInCriteria3() {
+    @Test public void testXMLAttributeInCriteria3() {
         helpResolve("select * from xmltest.doc4 where node2 = 'x'"); //$NON-NLS-1$
     }
 
-    public void testXMLAttributeElementAmbiguity1() {
+    @Test public void testXMLAttributeElementAmbiguity1() {
         helpResolve("select * from xmltest.doc4 where root.node3.node4 = 'x'"); //$NON-NLS-1$
     }
     
-    public void testXMLAttributeElementAmbiguity2() {        
+    @Test public void testXMLAttributeElementAmbiguity2() {        
         helpResolve("select * from xmltest.doc4 where root.node3. at node4 = 'x'"); //$NON-NLS-1$
     }
     
-    public void testXMLAttributeElementAmbiguity3() {
+    @Test public void testXMLAttributeElementAmbiguity3() {
         helpResolve("select * from xmltest.doc4 where root.node3.node4 = 'x' and root.node3. at node4='y'"); //$NON-NLS-1$
     }       
 
     /*
      * This should resolve to the XML element root.node3.root.node6
      */
-    public void testXMLAttributeElementAmbiguity4() {
+    @Test public void testXMLAttributeElementAmbiguity4() {
         helpResolve("select * from xmltest.doc4 where root.node6 = 'x'"); //$NON-NLS-1$
     }       
 
     /*
      * This should resolve to the XML attribute root. at node6
      */
-    public void testXMLAttributeElementAmbiguity5() {
+    @Test public void testXMLAttributeElementAmbiguity5() {
         helpResolve("select * from xmltest.doc4 where root. at node6 = 'x'"); //$NON-NLS-1$
     }       
 
-    public void testXMLAttributeFullPath() {
+    @Test public void testXMLAttributeFullPath() {
         helpResolve("select * from xmltest.doc4 where xmltest.doc4.root. at node6 = 'x'"); //$NON-NLS-1$
     }       
     
-    public void testXMLCriteriaLongElementWithGroup1() {
+    @Test public void testXMLCriteriaLongElementWithGroup1() {
         helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node1 = 'yyz'"); //$NON-NLS-1$
     }
     
-    public void testXMLCriteriaLongElementWithGroup2() {
+    @Test public void testXMLCriteriaLongElementWithGroup2() {
         helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node1. at node2 = 'yyz'"); //$NON-NLS-1$
     } 
 
-    public void testXMLCriteriaLongElementWithGroup3() {    
+    @Test public void testXMLCriteriaLongElementWithGroup3() {    
         helpResolve("select * from xmltest.doc4 where xmltest.doc4.root.node3 = 'yyz'"); //$NON-NLS-1$
     }
 
-    /*public void testXMLElementPotentialAmbiguous() {    
+    /*@Test public void testXMLElementPotentialAmbiguous() {    
         helpResolve("select * from xmltest.doc6 where node = 'yyz'");
     }*/
 
-    public void testXMLSelect() {        
+    @Test public void testXMLSelect() {        
         helpResolve("select root.node3. at node4 from xmltest.doc4"); //$NON-NLS-1$
     }        
 
-    public void testXMLSelect2() {        
+    @Test public void testXMLSelect2() {        
         helpResolve("select root.node3.node4 from xmltest.doc4"); //$NON-NLS-1$
     }        
 
-    public void testXMLSelect3() {        
+    @Test public void testXMLSelect3() {        
         helpResolve("select root. at node6 from xmltest.doc4"); //$NON-NLS-1$
     }    
 
-    public void testXMLSelect4() {        
+    @Test public void testXMLSelect4() {        
         helpResolve("select root.node6 from xmltest.doc4"); //$NON-NLS-1$
     }    
 
-    public void testXMLSelect5() {        
+    @Test public void testXMLSelect5() {        
         helpResolve("select node2 from xmltest.doc4"); //$NON-NLS-1$
     }
     
-    public void testDEFECT_19771() {
+    @Test public void testDEFECT_19771() {
         helpResolveException("select node2 AS NODE2 from xmltest.doc4"); //$NON-NLS-1$
     }
         
-    public void testContext() {                  
+    @Test public void testContext() {                  
         GroupSymbol gs1 = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es1 = new ElementSymbol("root.node1.node2.node3", null, gs1); //$NON-NLS-1$
         ElementSymbol es2 = new ElementSymbol("root.node1", null, gs1); //$NON-NLS-1$
@@ -324,7 +325,7 @@
         assertEquals("Did not match expected criteria", expected, actual);         //$NON-NLS-1$
     }    
 
-    public void testRowLimit() {                  
+    @Test public void testRowLimit() {                  
     	GroupSymbol gs1 = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es1 = new ElementSymbol("root.node1.node2.node3", null, gs1); //$NON-NLS-1$
         es1.setGroupSymbol(gs1);
@@ -342,7 +343,7 @@
         assertEquals("Did not match expected criteria", expected, actual);         //$NON-NLS-1$
     }    
 
-    public void testRowLimitException() {                  
+    @Test public void testRowLimitException() {                  
     	GroupSymbol gs1 = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es1 = new ElementSymbol("root.node1.node2.node3", null, gs1); //$NON-NLS-1$
         Expression[] exprs = new Expression[]{es1};
@@ -359,23 +360,23 @@
         assertEquals("Did not match expected criteria", expected, actual);         //$NON-NLS-1$
     }     
     
-    public void testXMLQueryFail1() {
+    @Test public void testXMLQueryFail1() {
         helpResolveException("SELECT DISTINCT * FROM vm1.doc1"); //$NON-NLS-1$
     }
 
-    public void testXMLQueryFail2() {
+    @Test public void testXMLQueryFail2() {
         helpResolveException("SELECT a2 FROM vm1.doc1"); //$NON-NLS-1$
     }
 
-    public void testXMLQueryFail3() {
+    @Test public void testXMLQueryFail3() {
         helpResolveException("SELECT * FROM vm1.doc1, vm1.doc2"); //$NON-NLS-1$
     }
     
-    public void testXMLWithOrderBy1() {
+    @Test public void testXMLWithOrderBy1() {
         helpResolveException("select * from xmltest.doc4 order by node1");             //$NON-NLS-1$
     }
     
-    public void testConversionInXML() {
+    @Test public void testConversionInXML() {
         // Expected left expression
     	GroupSymbol gs1 = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es1 = new ElementSymbol("root.node1", null, gs1); //$NON-NLS-1$
@@ -397,7 +398,7 @@
         assertNotNull("Failed to resolve function", actualRightExpr.getFunctionDescriptor()); //$NON-NLS-1$
     }
 
-    public void testXMLWithSelect1() throws Exception {
+    @Test public void testXMLWithSelect1() throws Exception {
         CompareCriteria expected = new CompareCriteria();
         GroupSymbol gs = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es = new ElementSymbol("root.node1", null, gs); //$NON-NLS-1$
@@ -405,16 +406,16 @@
         expected.setOperator(CompareCriteria.EQ);
         expected.setRightExpression(new Constant("yyz")); //$NON-NLS-1$
     
-        Query query = (Query) TestResolver.helpResolve(QueryParser.getQueryParser().parseCommand("select \"xml\" from xmltest.doc1 where node1 = 'yyz'"), FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        Query query = (Query) TestResolver.helpResolve(QueryParser.getQueryParser().parseCommand("select \"xml\" from xmltest.doc1 where node1 = 'yyz'"), RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         Criteria actual = query.getCriteria();
         assertEquals("Did not match expected criteria", expected, actual);     //$NON-NLS-1$
     } 
     
-    public void testXMLWithSelect1a() {
+    @Test public void testXMLWithSelect1a() {
         helpResolveException("select 'a' from xmltest.doc1 where node1 = 'yyz'", "Expressions cannot be selected by XML Queries"); //$NON-NLS-1$ //$NON-NLS-2$
     } 
 
-    public void testXMLWithSelect2() {
+    @Test public void testXMLWithSelect2() {
         CompareCriteria expected = new CompareCriteria();
         GroupSymbol gs = new GroupSymbol("xmltest.doc1"); //$NON-NLS-1$
         ElementSymbol es = new ElementSymbol("root.node1", null, gs); //$NON-NLS-1$

Modified: branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestOrderByRewrite.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,9 +32,9 @@
 import org.junit.Test;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.core.TeiidProcessingException;
+import org.teiid.metadata.Column;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
-import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.lang.Command;
 import org.teiid.query.sql.lang.OrderBy;
 import org.teiid.query.sql.lang.Query;
@@ -42,8 +42,7 @@
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 
 /**
@@ -54,36 +53,36 @@
     private static Command getCommand(String sql) throws TeiidComponentException, TeiidProcessingException {
         Command command = QueryParser.getQueryParser().parseCommand(sql);
         
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
         
-        return QueryRewriter.rewrite(command, FakeMetadataFactory.example1Cached(), null);
+        return QueryRewriter.rewrite(command, RealMetadataFactory.example1Cached(), null);
     }
 
     private void helpCheckElements(OrderBy langObj,
                                    String[] elementNames,
                                    String[] elementIDs) {
-        List elements = new ArrayList();
-        for (Iterator i = langObj.getSortKeys().iterator(); i.hasNext();) {
-            ElementCollectorVisitor.getElements((LanguageObject)i.next(), elements);
+        List<ElementSymbol> elements = new ArrayList<ElementSymbol>();
+        for (Iterator<SingleElementSymbol> i = langObj.getSortKeys().iterator(); i.hasNext();) {
+            ElementCollectorVisitor.getElements(i.next(), elements);
         }
 
         assertEquals("Wrong number of elements: ", elementNames.length, elements.size()); //$NON-NLS-1$
 
         for (int i = 0; i < elements.size(); i++) {
-            ElementSymbol symbol = (ElementSymbol)elements.get(i);
+            ElementSymbol symbol = elements.get(i);
             assertEquals("Element name does not match: ", elementNames[i].toUpperCase(), symbol.getName().toUpperCase()); //$NON-NLS-1$
 
-            FakeMetadataObject elementID = (FakeMetadataObject)symbol.getMetadataID();
+            Column elementID = (Column)symbol.getMetadataID();
             assertNotNull("ElementSymbol " + symbol + " was not resolved and has no metadataID", elementID); //$NON-NLS-1$ //$NON-NLS-2$
-            assertEquals("ElementID name does not match: ", elementIDs[i].toUpperCase(), elementID.getName().toUpperCase()); //$NON-NLS-1$
+            assertEquals("ElementID name does not match: ", elementIDs[i].toUpperCase(), elementID.getFullName().toUpperCase()); //$NON-NLS-1$
         }
     }
     
     private void helpCheckExpressionsSymbols(OrderBy langObj,
                                              String[] functionsNames) {
     	int expCount = 0;
-        for (Iterator i = langObj.getSortKeys().iterator(); i.hasNext();) {
-        	SingleElementSymbol ses = (SingleElementSymbol)i.next();
+        for (Iterator<SingleElementSymbol> i = langObj.getSortKeys().iterator(); i.hasNext();) {
+        	SingleElementSymbol ses = i.next();
             if (ses instanceof ExpressionSymbol) {
                 assertEquals("Expression Symbols does not match: ", functionsNames[expCount++], ses.toString()); //$NON-NLS-1$                        		
             }
@@ -306,11 +305,6 @@
             new String[] { "pm1.g1.e1" } ); //$NON-NLS-1$ 
     } 
     
-    @Test public void testOrderByExpression() throws Exception {
-    	Query resolvedQuery = (Query) getCommand("SELECT 0 AS SOMEINT, pm1.g1.e2 as y FROM pm1.g1 ORDER BY e2 || e1, e3"); //$NON-NLS-1$
-        assertEquals("SELECT X.SOMEINT, X.y FROM (SELECT 0 AS SOMEINT, pm1.g1.e2 AS y, (e2 || e1) AS EXPR1, e3 FROM pm1.g1) AS X ORDER BY X.EXPR1, X.e3", resolvedQuery.toString()); //$NON-NLS-1$
-    }
-    
     @Test public void testRewiteOrderBy() {
         helpTestRewriteCommand("SELECT 1+1 as a FROM pm1.g1 order by a", "SELECT 2 AS a FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
     }

Modified: branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/rewriter/TestQueryRewriter.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -48,8 +48,8 @@
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.util.TimestampWithTimezone;
+import org.teiid.metadata.Table;
 import org.teiid.query.eval.Evaluator;
-import org.teiid.query.function.FunctionLibrary;
 import org.teiid.query.function.FunctionTree;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.optimizer.FakeFunctionMetadataSource;
@@ -79,9 +79,7 @@
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.SingleElementSymbol;
 import org.teiid.query.sql.visitor.CorrelatedReferenceCollectorVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
+import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.query.util.CommandContext;
 import org.teiid.query.util.ContextProperties;
 
@@ -116,7 +114,7 @@
     }   
     
     private Criteria helpTestRewriteCriteria(String original, String expected, boolean rewrite) throws QueryMetadataException, TeiidComponentException, TeiidProcessingException {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
         Criteria expectedCrit = parseCriteria(expected, metadata);
         if (rewrite) {
             QueryResolver.resolveCriteria(expectedCrit, metadata);
@@ -126,11 +124,11 @@
     }
     
     private Map<ElementSymbol, Integer> elements;
-    private List<List> tuples;
+    private List<List<? extends Object>> tuples;
     
     @Before public void setUp() {
     	elements = null;
-    	tuples = new ArrayList<List>();
+    	tuples = new ArrayList<List<? extends Object>>();
     }
 
     private Criteria helpTestRewriteCriteria(String original, Criteria expectedCrit, QueryMetadataInterface metadata) {
@@ -140,7 +138,7 @@
         // rewrite
         try { 
         	ArrayList<Boolean> booleanVals = new ArrayList<Boolean>(tuples.size());
-        	for (List<Object> tuple : tuples) {
+        	for (List<?> tuple : tuples) {
             	booleanVals.add(new Evaluator(elements, null, null).evaluate(origCrit, tuple));
 			}
             actual = QueryRewriter.rewriteCriteria(origCrit, null, null, metadata);
@@ -168,8 +166,8 @@
     	return actualExp;
     }
     
-	private String getRewritenProcedure(String procedure, String userUpdateStr, String procedureType) throws TeiidComponentException, TeiidProcessingException {
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+	private String getRewritenProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) throws TeiidComponentException, TeiidProcessingException {
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
 
         return getRewritenProcedure(userUpdateStr, metadata);
 	}
@@ -187,7 +185,7 @@
 	
     static Command helpTestRewriteCommand(String original, String expected) { 
         try {
-            return helpTestRewriteCommand(original, expected, FakeMetadataFactory.example1Cached());
+            return helpTestRewriteCommand(original, expected, RealMetadataFactory.example1Cached());
         } catch(TeiidException e) { 
             throw new TeiidRuntimeException(e);
         }
@@ -438,7 +436,7 @@
     
     @Ignore(value="Should be moved to the validator")
     @Test public void testRewriteCrit_invalidParseDate() {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         Criteria origCrit = parseCriteria("PARSEDATE(pm3.g1.e1, '''') = {d'2003-05-01'}", metadata); //$NON-NLS-1$
         
         try { 
@@ -600,7 +598,7 @@
         String original = "formatBigInteger(convert(pm1.g1.e2, biginteger), '#,##0') = '1,234,567,890'"; //$NON-NLS-1$
         String expected = "pm1.g1.e2 = 1234567890"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
         Criteria origCrit = parseCriteria(original, metadata);
         Criteria expectedCrit = parseCriteria(expected, metadata);
         
@@ -614,7 +612,7 @@
         String original = "formatFloat(convert(pm1.g1.e4, float), '#,##0.###') = '1,234.123'"; //$NON-NLS-1$
         String expected = "pm1.g1.e4 = 1234.123046875"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
         Criteria origCrit = parseCriteria(original, metadata);
         
         // rewrite
@@ -627,7 +625,7 @@
         String original = "formatDouble(convert(pm1.g1.e4, double), '$#,##0.00') = '$1,234.50'"; //$NON-NLS-1$
         String expected = "pm1.g1.e4 = '1234.5'"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
         Criteria origCrit = parseCriteria(original, metadata);
         Criteria expectedCrit = parseCriteria(expected, metadata);
         ((CompareCriteria)expectedCrit).setRightExpression(new Constant(new Double(1234.5)));
@@ -642,7 +640,7 @@
         String original = "formatBigDecimal(convert(pm1.g1.e4, bigdecimal), '#,##0.###') = '1,234.5'"; //$NON-NLS-1$
         String expected = "pm1.g1.e4 = 1234.5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
         Criteria origCrit = parseCriteria(original, metadata);
         Criteria expectedCrit = parseCriteria(expected, metadata);
         
@@ -868,7 +866,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 		
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 				
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -896,7 +894,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 				
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -924,7 +922,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 				
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -947,7 +945,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 		
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 				
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }    
@@ -970,7 +968,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 		
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -992,7 +990,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 		
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }     
@@ -1016,7 +1014,7 @@
 		rewritProc = rewritProc + "END";		 //$NON-NLS-1$
 		
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1040,7 +1038,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 		
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1063,12 +1061,12 @@
 		rewritProc = rewritProc + "DECLARE String var1;\n"; //$NON-NLS-1$
 		rewritProc = rewritProc + "IF(var1 IN ('y', 'x'))\n"; //$NON-NLS-1$
 		rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-		rewritProc = rewritProc + "SELECT pm1.g1.e2, null, FALSE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
+		rewritProc = rewritProc + "SELECT pm1.g1.e2, 123, FALSE, TRUE FROM pm1.g1;\n"; //$NON-NLS-1$
 		rewritProc = rewritProc + "END\n"; //$NON-NLS-1$
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1090,7 +1088,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1112,7 +1110,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1135,7 +1133,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1158,7 +1156,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1180,7 +1178,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1202,7 +1200,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1220,7 +1218,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1237,7 +1235,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1254,7 +1252,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1278,7 +1276,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where e4= 1"; //$NON-NLS-1$
 
 		this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 	
 	// Bug 8212 elements in INPUT and CHANGING special groups are cese sensitive
@@ -1296,7 +1294,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1317,7 +1315,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1338,7 +1336,7 @@
         rewritProc = rewritProc + "UPDATE pm1.g1 SET e3 = TRUE;\n"; //$NON-NLS-1$
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
-		this.getRewritenProcedure(procedure, userQuery, FakeMetadataObject.Props.INSERT_PROCEDURE);
+		this.getRewritenProcedure(procedure, userQuery, Table.TriggerEvent.INSERT);
 	}
     
     @Test public void testRewriteProcedure21a() throws Exception {
@@ -1351,11 +1349,11 @@
 
         String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
         rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = null, e2 = null, e3 = TRUE;\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "UPDATE pm1.g1 SET e1 = '124', e2 = 123, e3 = TRUE;\n"; //$NON-NLS-1$
         rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
         String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                                                        FakeMetadataObject.Props.INSERT_PROCEDURE);
+                                                        Table.TriggerEvent.INSERT);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1374,7 +1372,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1393,7 +1391,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1409,11 +1407,11 @@
 
         String rewritProc = "CREATE PROCEDURE\n"; //$NON-NLS-1$
         rewritProc = rewritProc + "BEGIN\n"; //$NON-NLS-1$
-        rewritProc = rewritProc + "UPDATE pm1.g1 SET e2 = null, e3 = TRUE;\n"; //$NON-NLS-1$
+        rewritProc = rewritProc + "UPDATE pm1.g1 SET e2 = 123, e3 = TRUE;\n"; //$NON-NLS-1$
         rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
         String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.INSERT_PROCEDURE);
+                Table.TriggerEvent.INSERT);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1427,7 +1425,7 @@
         String userQuery = "UPDATE vm1.g1 set E2=1 where e2 = 1 and e1 LIKE 'mnopxyz_'"; //$NON-NLS-1$
 
 		this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
     }
 
 	// INPUT vars in insert statements replaced by default variable when user's inser ignores values
@@ -1445,7 +1443,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.INSERT_PROCEDURE);
+				Table.TriggerEvent.INSERT);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1467,7 +1465,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 
 		assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
 	}
@@ -1482,7 +1480,7 @@
 		String userQuery = "UPDATE vm1.g1 SET e1='x' where e2 LIKE 'xyz'"; //$NON-NLS-1$
         
 		this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 
     /**
@@ -1516,7 +1514,7 @@
         rewritProc = rewritProc + "END"; //$NON-NLS-1$
 
         String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1524,8 +1522,8 @@
     //base test.  no change is expected
     @Test public void testRewriteLookupFunction1() {
         String criteria = "lookup('pm1.g1','e1', 'e2', 1) = 'ab'"; //$NON-NLS-1$
-        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
-        helpTestRewriteCriteria(criteria, expected, FakeMetadataFactory.example1Cached());
+        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, RealMetadataFactory.example1Cached()); 
+        helpTestRewriteCriteria(criteria, expected, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testRewriteLookupFunction1b() {
@@ -1535,8 +1533,8 @@
     /** defect 11630 1 should still get rewritten as '1'*/
     @Test public void testRewriteLookupFunctionCompoundCriteria() {
         String criteria = "LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL AND pm1.g1.e1='1'"; //$NON-NLS-1$
-        CompoundCriteria expected = (CompoundCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
-        helpTestRewriteCriteria("LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL AND pm1.g1.e1=1", expected, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+        CompoundCriteria expected = (CompoundCriteria)parseCriteria(criteria, RealMetadataFactory.example1Cached()); 
+        helpTestRewriteCriteria("LOOKUP('pm1.g1','e1', 'e2', 1) IS NULL AND pm1.g1.e1=1", expected, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ 
     }
 
     @Test public void testSelectWithNoFrom() {
@@ -1550,7 +1548,7 @@
         Command command = parser.parseCommand("exec pm1.sp4(5)");             //$NON-NLS-1$
         
         // resolve
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         QueryResolver.resolveCommand(command, metadata);
         
         // rewrite
@@ -1566,7 +1564,7 @@
     }
     
     @Test public void testRewriteFunctionThrowsEvaluationError() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
         Criteria origCrit = parseCriteria("5 / 0 = 5", metadata); //$NON-NLS-1$
         
         // rewrite
@@ -1580,7 +1578,7 @@
     }
     
     @Test public void testRewriteConvertThrowsEvaluationError() {
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
         Criteria origCrit = parseCriteria("convert('x', integer) = 0", metadata); //$NON-NLS-1$
         
         // rewrite
@@ -1610,7 +1608,7 @@
 		rewritProc = rewritProc + "END"; //$NON-NLS-1$
 		
 		String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.DELETE_PROCEDURE);				
+				Table.TriggerEvent.DELETE);				
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
     
@@ -1623,7 +1621,7 @@
     }
 
     @Test public void testRewriteCase1954b() throws Exception{
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1Cached(); 
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); 
 
         CompareCriteria expected = new CompareCriteria();
         ElementSymbol leftElement = new ElementSymbol("pm1.g1.e4"); //$NON-NLS-1$
@@ -1711,6 +1709,9 @@
         helpTestRewriteCriteria("case when 0 = pm1.g1.e2 then null else null end IS NULL", TRUE_STR); //$NON-NLS-1$ 
     }
     
+    @Test public void testRewriteConstantAgg2() throws Exception {
+    	helpTestRewriteCommand("select count(2) from pm1.g1 group by e1", "SELECT COUNT(2) FROM pm1.g1 GROUP BY e1");
+    }
     
     @Test public void testRewriteCaseExprForCase5413a() {
         helpTestRewriteCriteria("pm1.g2.e1 = case when 0 = pm1.g1.e2 then 2 else 2 end", "pm1.g2.e1 = '2'"); //$NON-NLS-1$ //$NON-NLS-2$
@@ -1736,8 +1737,8 @@
     
     @Test public void testRewriteSearchedCaseExpr4() {
         String criteria = "lookup('pm1.g1', 'e2', 'e1', '2') = 0"; //$NON-NLS-1$
-        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, FakeMetadataFactory.example1Cached()); 
-        helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case 0 when 1 then pm1.g1.e1 else 2 end) = 0", expected, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        CompareCriteria expected = (CompareCriteria)parseCriteria(criteria, RealMetadataFactory.example1Cached()); 
+        helpTestRewriteCriteria("lookup('pm1.g1', 'e2', 'e1', case 0 when 1 then pm1.g1.e1 else 2 end) = 0", expected, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     // First WHEN always false, so remove it
@@ -1788,13 +1789,13 @@
     @Test public void testRewriteExecEnv() throws Exception {
         Command command = QueryParser.getQueryParser().parseCommand("exec pm1.sq2(env('sessionid'))");             //$NON-NLS-1$
         
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.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, FakeMetadataFactory.example1Cached(), context);
+        Command rewriteCommand = QueryRewriter.rewrite(command, RealMetadataFactory.example1Cached(), context);
         
         assertEquals("EXEC pm1.sq2('1')", rewriteCommand.toString()); //$NON-NLS-1$
     }
@@ -1830,7 +1831,7 @@
         String userQuery = "Insert into vm1.g1 (e1, e2) values ('String', 1)"; //$NON-NLS-1$
 
         try {       
-            getRewritenProcedure(procedure, userQuery, FakeMetadataObject.Props.INSERT_PROCEDURE);
+            getRewritenProcedure(procedure, userQuery, Table.TriggerEvent.INSERT);
             fail("exception expected"); //$NON-NLS-1$
         } catch (QueryValidatorException e) {
             assertEquals("Infinite loop detected, procedure will not be executed.", e.getMessage()); //$NON-NLS-1$
@@ -1854,7 +1855,7 @@
         rewritProc = rewritProc + "END"; //$NON-NLS-1$
         
         String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.INSERT_PROCEDURE);
+                Table.TriggerEvent.INSERT);
                 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1877,7 +1878,7 @@
         rewritProc = rewritProc + "END"; //$NON-NLS-1$
         
         String procReturned = this.getRewritenProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.INSERT_PROCEDURE);
+                Table.TriggerEvent.INSERT);
                 
         assertEquals("Rewritten command was not expected", rewritProc, procReturned); //$NON-NLS-1$
     }
@@ -1903,7 +1904,7 @@
 
         String userUpdateStr = "UPDATE vm1.g1 SET e1 = 'x' WHERE e2 = 5"; //$NON-NLS-1$
         
-        FakeMetadataFacade metadata = FakeMetadataFactory.exampleUpdateProc(FakeMetadataObject.Props.UPDATE_PROCEDURE, procedure1, procedure2);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(Table.TriggerEvent.UPDATE, procedure1, procedure2);
         
         String rewriten = getRewritenProcedure(userUpdateStr, metadata);
         
@@ -2013,9 +2014,9 @@
 
     private void verifyProjectedTypesOnUnionBranches(String unionQuery, Class<?>[] types) throws TeiidComponentException, TeiidProcessingException {
         SetQuery union = (SetQuery)QueryParser.getQueryParser().parseCommand(unionQuery);
-        QueryResolver.resolveCommand(union, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCommand(union, RealMetadataFactory.example1Cached());
         
-        union = (SetQuery)QueryRewriter.rewrite(union, FakeMetadataFactory.example1Cached(), null);
+        union = (SetQuery)QueryRewriter.rewrite(union, RealMetadataFactory.example1Cached(), null);
         
         for (QueryCommand query : union.getQueryCommands()) {
             List<SingleElementSymbol> projSymbols = query.getProjectedSymbols();
@@ -2056,7 +2057,7 @@
      */
     @Test public void testVirtualRightOuterJoinSwap() throws Exception {
         String sql = "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (select * from BQT1.smalla) sa RIGHT OUTER JOIN (select BQT1.mediumb.intkey from BQT1.mediumb) mb ON sa.IntKey = mb.IntKey"; //$NON-NLS-1$
-        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN (SELECT * FROM BQT1.smalla) AS sa ON sa.IntKey = mb.IntKey", FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN (SELECT * FROM BQT1.smalla) AS sa ON sa.IntKey = mb.IntKey", RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
     }
     
     /**
@@ -2064,11 +2065,11 @@
      */
     @Test public void testVirtualRightOuterJoinSwap1() throws Exception {
         String sql = "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM ((select * from BQT1.smalla) sa inner join BQT1.smallb on sa.intkey = smallb.intkey) RIGHT OUTER JOIN (select BQT1.mediumb.intkey from BQT1.mediumb) mb ON sa.IntKey = mb.IntKey"; //$NON-NLS-1$
-        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN ((SELECT * FROM BQT1.smalla) AS sa INNER JOIN BQT1.smallb ON sa.intkey = smallb.intkey) ON sa.IntKey = mb.IntKey", FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+        helpTestRewriteCommand(sql, "SELECT sa.IntKey AS sa_IntKey, mb.IntKey AS mb_IntKey FROM (SELECT BQT1.mediumb.intkey FROM BQT1.mediumb) AS mb LEFT OUTER JOIN ((SELECT * FROM BQT1.smalla) AS sa INNER JOIN BQT1.smallb ON sa.intkey = smallb.intkey) ON sa.IntKey = mb.IntKey", RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
     }
     
     @Test public void testRewriteConcat2() {
-        helpTestRewriteCriteria("concat2('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
+        helpTestRewriteCriteria("sys.concat2('a','b') = 'ab'", "1 = 1"); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testRewriteConcat2_1() {
@@ -2087,10 +2088,6 @@
         helpTestRewriteCriteria("concat2('a', pm1.g1.e1) = 'xyz'", "concat('a', ifnull(pm1.g1.e1, '')) = 'xyz'"); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
-    @Test public void testRewiteEvaluatableAggregate() {
-    	helpTestRewriteCommand("select pm1.g1.e1, max(1) from pm1.g1", "SELECT pm1.g1.e1, 1 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-    }
-    
     @Test public void testRewriteFromUnixTime() throws Exception {
     	TimestampWithTimezone.resetCalendar(TimeZone.getTimeZone("GMT-06:00")); //$NON-NLS-1$
     	try {
@@ -2321,7 +2318,7 @@
     @Test public void testRewriteBigDecimal() {
     	String original = "convert(BQT1.SmallA.LongNum, bigdecimal) = '22.0'"; //$NON-NLS-1$
     	CompareCriteria crit = new CompareCriteria(new ElementSymbol("BQT1.SmallA.LongNum"), CompareCriteria.EQ, new Constant(new Long(22))); //$NON-NLS-1$
-    	helpTestRewriteCriteria(original, crit, FakeMetadataFactory.exampleBQTCached()); 
+    	helpTestRewriteCriteria(original, crit, RealMetadataFactory.exampleBQTCached()); 
     }
 
     /**
@@ -2329,54 +2326,54 @@
      */
     @Test public void testRewriteWideningIn() {
     	String original = "convert(BQT1.SmallA.TimestampValue, time) in ({t'10:00:00'}, {t'11:00:00'})"; //$NON-NLS-1$
-    	helpTestRewriteCriteria(original, parseCriteria("convert(BQT1.SmallA.TimestampValue, time) in ({t'10:00:00'}, {t'11:00:00'})", FakeMetadataFactory.exampleBQTCached()), FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$ 
+    	helpTestRewriteCriteria(original, parseCriteria("convert(BQT1.SmallA.TimestampValue, time) in ({t'10:00:00'}, {t'11:00:00'})", RealMetadataFactory.exampleBQTCached()), RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$ 
     }
     
     @Test public void testRewriteParseDate() {
     	String original = "parsedate(BQT1.SmallA.stringkey, 'yymmdd') = {d'1970-01-01'}"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteCriteria(original, parseCriteria("convert(parsetimestamp(BQT1.SmallA.stringkey, 'yymmdd'), date) = {d'1970-01-01'}", metadata), metadata); //$NON-NLS-1$
     }
 
     @Test public void testRewriteFormatTime() {
     	String original = "formattime(BQT1.SmallA.timevalue, 'hh:mm') = '08:02'"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteCriteria(original, parseCriteria("formattimestamp(convert(BQT1.SmallA.timevalue, timestamp), 'hh:mm') = '08:02'", metadata), metadata); //$NON-NLS-1$
     }
     
     @Test public void testRewriteTimestampAdd() {
     	String original = "timestampadd(SQL_TSI_SECOND, 1, BQT1.SmallA.timevalue) = {t'08:02:00'}"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteCriteria(original, parseCriteria("convert(timestampadd(SQL_TSI_SECOND, 1, convert(BQT1.SmallA.timevalue, timestamp)), time) = {t'08:02:00'}", metadata), metadata); //$NON-NLS-1$
     }
     
     @Test public void testRewriteXmlElement() throws Exception {
     	String original = "xmlserialize(document xmlelement(name a, xmlattributes('b' as c)) as string)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteExpression(original, "'<a c=\"b\"></a>'", metadata);
     }
     
     @Test public void testRewriteXmlElement1() throws Exception {
     	String original = "xmlelement(name a, xmlattributes(1+1 as c), BQT1.SmallA.timevalue)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteExpression(original, "XMLELEMENT(NAME a, XMLATTRIBUTES(2 AS c), BQT1.SmallA.timevalue)", metadata);
     }
     
     @Test public void testRewriteXmlSerialize() throws Exception {
     	String original = "xmlserialize(document xmlelement(name a, xmlattributes('b' as c)) as string)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteExpression(original, "'<a c=\"b\"></a>'", metadata);
     }
     
     @Test public void testRewriteXmlTable() throws Exception {
     	String original = "select * from xmltable('/' passing 1 + 1 as a columns x string default curdate()) as x"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteCommand(original, "SELECT * FROM XMLTABLE('/' PASSING 2 AS a COLUMNS x string DEFAULT curdate()) AS x", metadata);
     }
     
     @Test public void testRewriteQueryString() throws Exception {
     	String original = "querystring('path', 'value' as \"&x\", ' & ' as y, null as z)"; //$NON-NLS-1$
-    	QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
     	helpTestRewriteExpression(original, "'path?%26x=value&y=%20%26%20'", metadata);
     }
     
@@ -2446,10 +2443,33 @@
     }
     
 	@Test public void testUDFParse() throws Exception {     
-        FunctionLibrary funcLibrary = new FunctionLibrary(FakeMetadataFactory.SFM.getSystemFunctions(), new FunctionTree("foo", new FakeFunctionMetadataSource()));
-        FakeMetadataFacade metadata = new FakeMetadataFacade(FakeMetadataFactory.example1Cached().getStore(), funcLibrary);
+        QueryMetadataInterface metadata = RealMetadataFactory.createTransformationMetadata(RealMetadataFactory.example1Cached().getMetadataStore(), "example1", new FunctionTree("foo", new FakeFunctionMetadataSource()));
 		String sql = "parsedate_(pm1.g1.e1) = {d'2001-01-01'}";
         helpTestRewriteCriteria(sql, parseCriteria(sql, metadata), metadata);  		
 	} 
+	
+    @Test public void testRewriteNestedConvert() throws Exception {
+        helpTestRewriteExpression("cast(cast(pm1.g1.e3 as integer) as long)", "cast(pm1.g1.e3 as long)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteNestedConvert1() throws Exception {
+        helpTestRewriteExpression("cast(cast(pm1.g1.e3 as integer) as string)", "convert(convert(pm1.g1.e3, integer), string)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
 
+    @Test public void testRewriteNestedConvert2() throws Exception {
+        helpTestRewriteExpression("cast(cast(pm1.g1.e3 as string) as clob)", "convert(convert(pm1.g1.e3, string), clob)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    }
+    
+    @Test public void testRewriteConstantAgg() throws Exception {
+    	helpTestRewriteCommand("select max(1) from pm1.g1 group by e1", "SELECT 1 FROM pm1.g1 GROUP BY e1");
+    }
+    
+    @Test public void testRewriteTrim() throws Exception {
+    	helpTestRewriteExpression("trim(pm1.g1.e1)", "rtrim(ltrim(pm1.g1.e1))", RealMetadataFactory.example1Cached());
+    }
+
+    @Test public void testRewriteTrim1() throws Exception {
+    	helpTestRewriteExpression("trim(leading from pm1.g1.e1)", "ltrim(pm1.g1.e1)", RealMetadataFactory.example1Cached());
+    }
+
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/lang/TestSelect.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/lang/TestSelect.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/lang/TestSelect.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,7 +28,7 @@
 import org.teiid.core.util.UnitTestUtil;
 import org.teiid.query.sql.lang.Select;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.ElementSymbol;
 
 import junit.framework.TestCase;
@@ -50,7 +50,7 @@
 		symbols.add(new ElementSymbol("b")); //$NON-NLS-1$
 
 	    Select select = new Select();
-	    AllSymbol all = new AllSymbol();
+	    MultipleElementSymbol all = new MultipleElementSymbol();
 	    all.setElementSymbols(symbols);
 	    select.addSymbol(all);
 	    return select;	
@@ -69,7 +69,7 @@
 	
 	public void testGetProjectedNoElements() {    
 	    Select select = new Select();
-	    select.addSymbol(new AllSymbol());
+	    select.addSymbol(new MultipleElementSymbol());
 	    
 	    List projectedSymbols = select.getProjectedSymbols();
 	    assertEquals("Did not get empty list for select * with no elements: ", new ArrayList(), projectedSymbols); //$NON-NLS-1$
@@ -81,7 +81,7 @@
 		symbols.add(new ElementSymbol("b")); //$NON-NLS-1$
 
 	    Select select = new Select();
-	    AllSymbol all = new AllSymbol();
+	    MultipleElementSymbol all = new MultipleElementSymbol();
 	    all.setElementSymbols(symbols);
 	    select.addSymbol(all);
 	    

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestBreakStatement.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestBreakStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestBreakStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,12 +24,11 @@
  */
 package org.teiid.query.sql.proc;
 
+import junit.framework.TestCase;
+
 import org.teiid.core.util.UnitTestUtil;
-import org.teiid.query.sql.proc.BreakStatement;
-import org.teiid.query.sql.proc.ContinueStatement;
+import org.teiid.query.sql.proc.BranchingStatement.BranchingMode;
 
-import junit.framework.*;
-
 public class TestBreakStatement  extends TestCase{
 
     /**
@@ -41,32 +40,32 @@
     
     // ################################## TEST HELPERS ################################ 
 
-    public static final BreakStatement sample1() { 
-        return new BreakStatement();
+    public static final BranchingStatement sample1() { 
+        return new BranchingStatement();
     }
     
-    public static final BreakStatement sample2() { 
-        return new BreakStatement();
+    public static final BranchingStatement sample2() { 
+        return new BranchingStatement();
     }
     
     // ################################## ACTUAL TESTS ################################ 
     
     public void testSelfEquivalence(){
-        BreakStatement s1 = sample1();
+        BranchingStatement s1 = sample1();
         int equals = 0;
         UnitTestUtil.helpTestEquivalence(equals, s1, s1);
     }
 
     public void testEquivalence(){
-        BreakStatement s1 = sample1();
-        BreakStatement s1a = sample2();
+        BranchingStatement s1 = sample1();
+        BranchingStatement s1a = sample2();
         int equals = 0;
         UnitTestUtil.helpTestEquivalence(equals, s1, s1a);
     }
     
     public void testNonEquivalence(){
-        BreakStatement s1 = sample1();
+        BranchingStatement s1 = sample1();
         int equals = -1;
-        UnitTestUtil.helpTestEquivalence(equals, s1, new ContinueStatement());
+        UnitTestUtil.helpTestEquivalence(equals, s1, new BranchingStatement(BranchingMode.CONTINUE));
     }
 }

Deleted: branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestContinueStatement.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestContinueStatement.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/proc/TestContinueStatement.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,80 +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 org.teiid.query.sql.proc;
-
-import org.teiid.core.util.UnitTestUtil;
-import org.teiid.query.sql.proc.BreakStatement;
-import org.teiid.query.sql.proc.ContinueStatement;
-
-import junit.framework.TestCase;
-
-
-/**
- * @author LLiang
- *
- * To change the template for this generated type comment go to
- * Window>Preferences>Java>Code Generation>Code and Comments
- */
-public class TestContinueStatement  extends TestCase{
-
-    /**
-     * Constructor for TestAssignmentStatement.
-     */
-    public TestContinueStatement(String name) { 
-        super(name);
-    }
-    
-    // ################################## TEST HELPERS ################################ 
-
-    public static final ContinueStatement sample1() { 
-        return new ContinueStatement();
-    }
-    
-    public static final ContinueStatement sample2() { 
-        return new ContinueStatement();
-    }
-    
-    // ################################## ACTUAL TESTS ################################ 
-    
-    public void testSelfEquivalence(){
-        ContinueStatement s1 = sample1();
-        int equals = 0;
-        UnitTestUtil.helpTestEquivalence(equals, s1, s1);
-    }
-
-    public void testEquivalence(){
-        ContinueStatement s1 = sample1();
-        ContinueStatement s1a = sample2();
-        int equals = 0;
-        UnitTestUtil.helpTestEquivalence(equals, s1, s1a);
-    }
-    
-    public void testNonEquivalence(){
-        ContinueStatement s1 = sample1();
-        int equals = -1;
-        UnitTestUtil.helpTestEquivalence(equals, s1, new BreakStatement());
-    }
-
-}

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/symbol/TestSearchedCaseExpression.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/symbol/TestSearchedCaseExpression.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/symbol/TestSearchedCaseExpression.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,16 +25,11 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import junit.framework.TestCase;
+
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.query.sql.lang.CompareCriteria;
-import org.teiid.query.sql.symbol.Constant;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.Expression;
-import org.teiid.query.sql.symbol.SearchedCaseExpression;
 
-
-import junit.framework.TestCase;
-
 public class TestSearchedCaseExpression extends TestCase {
 
     /**

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/util/TestElementSymbolOptimizer.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -36,7 +36,7 @@
 import org.teiid.query.resolver.util.ResolverUtil;
 import org.teiid.query.resolver.util.ResolverVisitor;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 /**
  */
@@ -65,51 +65,51 @@
     /** Can be optimized */
     @Test public void testOptimize1() throws Exception {
         helpTestOptimize("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT e1, e2 FROM pm1.g1"); //$NON-NLS-1$
     }
 
     /** Can't be optimized */
     @Test public void testOptimize2() throws Exception {
         helpTestOptimize("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1, pm1.g2", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1, pm1.g2"); //$NON-NLS-1$
     }
 
     @Test public void testOptimize3() throws Exception {
         helpTestOptimize("UPDATE pm1.g1 SET pm1.g1.e1 = 'e' WHERE pm1.g1.e2 = 3", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "UPDATE pm1.g1 SET e1 = 'e' WHERE e2 = 3"); //$NON-NLS-1$
     }
 
     @Test public void testOptimize4() throws Exception {
         helpTestOptimize("INSERT INTO pm1.g1 (pm1.g1.e1, pm1.g1.e2) VALUES ('e', 3)", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "INSERT INTO pm1.g1 (e1, e2) VALUES ('e', 3)"); //$NON-NLS-1$
     }
 
     @Test public void testOptimize5() throws Exception {
         helpTestOptimize("DELETE FROM pm1.g1 WHERE pm1.g1.e2 = 3", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "DELETE FROM pm1.g1 WHERE e2 = 3"); //$NON-NLS-1$
     }
     
     @Test public void testOptimize6() throws Exception {
         helpTestOptimize("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1 WHERE e2 > (SELECT AVG(pm1.g2.e2) FROM pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1)", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT e1, e2 FROM pm1.g1 WHERE e2 > (SELECT AVG(e2) FROM pm1.g2 WHERE pm1.g1.e1 = e1)"); //$NON-NLS-1$
     }
 
     /** alias */
     @Test public void testOptimize7() throws Exception {
         helpTestOptimize("SELECT 'text' AS zz, pm1.g1.e2 FROM pm1.g1", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT 'text' AS zz, e2 FROM pm1.g1"); //$NON-NLS-1$
     }
 
     @Test public void testOptimize8() throws Exception {
         helpTestOptimize("SELECT 1, 'xyz'", //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT 1, 'xyz'"); //$NON-NLS-1$
     }
 
@@ -123,37 +123,37 @@
     
     @Test public void testFullyQualify1() throws Exception {
         helpTestFullyQualify("SELECT e1, e2 FROM pm1.g1",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1"); //$NON-NLS-1$
     }
     
     @Test public void testXMLQuery() throws Exception {
         helpTestOptimize("SELECT root.node1.node2.node3 FROM xmltest.doc1",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT root.node1.node2.node3 FROM xmltest.doc1"); //$NON-NLS-1$
     }
     
     @Test public void testVirtualStoredProcedure() throws Exception {
         helpTestOptimize("EXEC pm1.vsp7(5)",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "EXEC pm1.vsp7(5)"); //$NON-NLS-1$
     }
 
     @Test public void testStoredQuerySubquery() throws Exception {
         helpTestOptimize("select x.e1 from (EXEC pm1.sq1()) as x",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT e1 FROM (EXEC pm1.sq1()) AS x"); //$NON-NLS-1$
     }
 
     @Test public void testStoredQuerySubquery2() throws Exception {
         helpTestOptimize("select x.e1 from (EXEC pm1.sq1()) as x WHERE x.e2 = 3",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT e1 FROM (EXEC pm1.sq1()) AS x WHERE e2 = 3"); //$NON-NLS-1$
     }
     
     @Test public void testOptimizeOrderBy() throws Exception {
         helpTestOptimize("SELECT pm1.g1.e1 FROM pm1.g1 order by pm1.g1.e1",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
     }
     
@@ -163,13 +163,13 @@
      */
     @Test public void testOptimizeOrderBy1() throws Exception {
         helpTestFullyQualify("SELECT e1 FROM pm1.g1 order by e1",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT pm1.g1.e1 FROM pm1.g1 ORDER BY e1"); //$NON-NLS-1$
     }
     
     @Test public void testOptimizeOrderByWithoutGroup() throws Exception {
         helpTestOptimize("SELECT pm1.g1.e1, count(*) as x FROM pm1.g1 order by x",  //$NON-NLS-1$
-                            FakeMetadataFactory.example1Cached(), 
+                            RealMetadataFactory.example1Cached(), 
                             "SELECT e1, COUNT(*) AS x FROM pm1.g1 ORDER BY x"); //$NON-NLS-1$
     }
 

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestAggregateSymbolCollectorVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestAggregateSymbolCollectorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestAggregateSymbolCollectorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -25,16 +25,15 @@
 import java.util.ArrayList;
 import java.util.List;
 
+import junit.framework.TestCase;
+
 import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-import org.teiid.query.sql.visitor.AggregateSymbolCollectorVisitor;
+import org.teiid.query.sql.symbol.Expression;
 
-import junit.framework.TestCase;
 
 
-
 public class TestAggregateSymbolCollectorVisitor extends TestCase {
 
     public TestAggregateSymbolCollectorVisitor(String name) {
@@ -46,9 +45,9 @@
         Command command = QueryParser.getQueryParser().parseCommand(sql);
         
         // Find aggregates
-        List<SingleElementSymbol> foundAggs = new ArrayList<SingleElementSymbol>();
-        List<SingleElementSymbol> foundElements = new ArrayList<SingleElementSymbol>();
-        AggregateSymbolCollectorVisitor.getAggregates(command, foundAggs, foundElements);
+        List<Expression> foundAggs = new ArrayList<Expression>();
+        List<Expression> foundElements = new ArrayList<Expression>();
+        AggregateSymbolCollectorVisitor.getAggregates(command, foundAggs, foundElements, null, null, null);
         
         // Compare
         assertEquals("Incorrect number of aggregates: " + foundAggs, aggs.length, foundAggs.size()); //$NON-NLS-1$

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestEvaluatableVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -26,14 +26,14 @@
 import org.teiid.query.resolver.TestResolver;
 import org.teiid.query.sql.lang.Query;
 import org.teiid.query.sql.visitor.EvaluatableVisitor;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
 import static org.junit.Assert.*;
 
 public class TestEvaluatableVisitor {
 
 	@Test public void testNestedNeedsEvaluation() throws Exception {
-		Query command = (Query)TestResolver.helpResolve("select * from pm1.g1 where e1 in (select e1 from pm1.g2 where e2 = ?)", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+		Query command = (Query)TestResolver.helpResolve("select * from pm1.g1 where e1 in (select e1 from pm1.g2 where e2 = ?)", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
 		assertTrue(EvaluatableVisitor.needsProcessingEvaluation(command));
 	}
 	

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestExpressionMappingVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestExpressionMappingVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestExpressionMappingVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -45,7 +45,6 @@
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.TestCaseExpression;
 import org.teiid.query.sql.symbol.TestSearchedCaseExpression;
-import org.teiid.query.sql.visitor.ExpressionMappingVisitor;
 import org.teiid.translator.SourceSystemFunctions;
 
 
@@ -196,13 +195,13 @@
      * a function.
      */
     @Test public void testRecursionDetection() {
-    	ElementSymbol e1 = new ElementSymbol("e1"); //$NON-NLS-1$
+    	ElementSymbol e1 = new ElementSymbol("g1.e1"); //$NON-NLS-1$
     	AggregateSymbol a1 = new AggregateSymbol("x", NonReserved.SUM, false, e1); //$NON-NLS-1$
     	Function f = new Function(SourceSystemFunctions.ADD_OP, new Expression[] {a1, a1});
     	HashMap<AggregateSymbol, AggregateSymbol> map = new HashMap<AggregateSymbol, AggregateSymbol>();
     	map.put(a1, new AggregateSymbol("x", NonReserved.SUM, false, a1)); //$NON-NLS-1$
     	ExpressionMappingVisitor.mapExpressions(f, map);
-        assertEquals("(SUM(SUM(e1)) + SUM(SUM(e1)))", f.toString()); //$NON-NLS-1$
+        assertEquals("(SUM(SUM(g1.e1)) + SUM(SUM(g1.e1)))", f.toString()); //$NON-NLS-1$
     }
     
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestSQLStringVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,13 +22,15 @@
 
 package org.teiid.query.sql.visitor;
 
+import static org.junit.Assert.*;
+
 import java.math.BigDecimal;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
-import junit.framework.TestCase;
-
+import org.junit.Test;
+import org.teiid.api.exception.query.QueryParserException;
 import org.teiid.client.metadata.ParameterInfo;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.language.SQLConstants.NonReserved;
@@ -77,8 +79,6 @@
 import org.teiid.query.sql.proc.RaiseErrorStatement;
 import org.teiid.query.sql.symbol.AggregateSymbol;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.CaseExpression;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
@@ -86,22 +86,17 @@
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Reference;
 import org.teiid.query.sql.symbol.ScalarSubquery;
 import org.teiid.query.sql.symbol.SearchedCaseExpression;
 import org.teiid.query.sql.symbol.TestCaseExpression;
 import org.teiid.query.sql.symbol.TestSearchedCaseExpression;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.query.unittest.RealMetadataFactory;
 
+ at SuppressWarnings("nls")
+public class TestSQLStringVisitor {
 
-public class TestSQLStringVisitor extends TestCase {
-
-	// ################################## FRAMEWORK ################################
-	
-	public TestSQLStringVisitor(String name) { 
-		super(name);
-	}	
-	
 	// ################################## TEST HELPERS ################################	
 		
     private void helpTest(LanguageObject obj, String expectedStr) {
@@ -111,13 +106,13 @@
         
 	// ################################## ACTUAL TESTS ################################
 	
-	public void testNull() {
+	@Test public void testNull() {
         String sql = SQLStringVisitor.getSQLString(null);
         
         assertEquals("Incorrect string for null object", SQLStringVisitor.UNDEFINED, sql); //$NON-NLS-1$
 	}
     
-    public void testBetweenCriteria1() {
+    @Test public void testBetweenCriteria1() {
         BetweenCriteria bc = new BetweenCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             new Constant(new Integer(1000)),
@@ -125,7 +120,7 @@
         helpTest(bc, "m.g.c1 BETWEEN 1000 AND 2000"); //$NON-NLS-1$
     }
     
-    public void testBetweenCriteria2() {
+    @Test public void testBetweenCriteria2() {
         BetweenCriteria bc = new BetweenCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             new Constant(new Integer(1000)),
@@ -134,7 +129,7 @@
         helpTest(bc, "m.g.c1 NOT BETWEEN 1000 AND 2000"); //$NON-NLS-1$
     }
     
-    public void testCompareCriteria1() {	
+    @Test public void testCompareCriteria1() {	
         CompareCriteria cc = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.EQ,
@@ -143,7 +138,7 @@
         helpTest(cc, "m.g.c1 = 'abc'"); //$NON-NLS-1$
     }        
     
-    public void testCompareCriteria2() {	
+    @Test public void testCompareCriteria2() {	
         CompareCriteria cc = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.NE,
@@ -152,7 +147,7 @@
         helpTest(cc, "m.g.c1 <> 'abc'"); //$NON-NLS-1$
     }        
 
-    public void testCompareCriteria3() {	
+    @Test public void testCompareCriteria3() {	
         CompareCriteria cc = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.GT,
@@ -161,7 +156,7 @@
         helpTest(cc, "m.g.c1 > 'abc'"); //$NON-NLS-1$
     }        
 
-    public void testCompareCriteria4() {	
+    @Test public void testCompareCriteria4() {	
         CompareCriteria cc = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.GE,
@@ -170,7 +165,7 @@
         helpTest(cc, "m.g.c1 >= 'abc'"); //$NON-NLS-1$
     }        
 
-    public void testCompareCriteria5() {	
+    @Test public void testCompareCriteria5() {	
         CompareCriteria cc = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.LT,
@@ -179,7 +174,7 @@
         helpTest(cc, "m.g.c1 < 'abc'"); //$NON-NLS-1$
     }        
 
-    public void testCompareCriteria6() {	
+    @Test public void testCompareCriteria6() {	
         CompareCriteria cc = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.LE,
@@ -188,7 +183,7 @@
         helpTest(cc, "m.g.c1 <= 'abc'"); //$NON-NLS-1$
     }        
         
-    public void testCompareCriteria7() {	
+    @Test public void testCompareCriteria7() {	
         CompareCriteria cc = new CompareCriteria(
             null,
             CompareCriteria.EQ,
@@ -197,7 +192,7 @@
         helpTest(cc, "<undefined> = <undefined>"); //$NON-NLS-1$
     }        
 
-    public void testCompoundCriteria1() {	
+    @Test public void testCompoundCriteria1() {	
         CompareCriteria cc = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.EQ,
@@ -209,7 +204,7 @@
         helpTest(comp, "m.g.c1 = 'abc'"); //$NON-NLS-1$
     }        
     
-    public void testCompoundCriteria2() {	
+    @Test public void testCompoundCriteria2() {	
         CompareCriteria cc1 = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.EQ,
@@ -226,7 +221,7 @@
         helpTest(comp, "(m.g.c1 = 'abc') AND (m.g.c2 = 'abc')"); //$NON-NLS-1$
     }        
 
-    public void testCompoundCriteria3() {	
+    @Test public void testCompoundCriteria3() {	
         CompareCriteria cc1 = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.EQ,
@@ -248,7 +243,7 @@
         helpTest(comp, "(m.g.c1 = 'abc') OR (m.g.c2 = 'abc') OR (m.g.c3 = 'abc')"); //$NON-NLS-1$
     }        
 
-    public void testCompoundCriteria4() {	
+    @Test public void testCompoundCriteria4() {	
         CompareCriteria cc1 = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.EQ,
@@ -261,7 +256,7 @@
         helpTest(comp, "(m.g.c1 = 'abc') OR (<undefined>)"); //$NON-NLS-1$
     }        
 
-    public void testCompoundCriteria5() {	
+    @Test public void testCompoundCriteria5() {	
         CompareCriteria cc1 = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.EQ,
@@ -274,7 +269,7 @@
         helpTest(comp, "(<undefined>) OR (m.g.c1 = 'abc')"); //$NON-NLS-1$
     }        
 
-    public void testCompoundCriteria6() {	
+    @Test public void testCompoundCriteria6() {	
         CompareCriteria cc1 = new CompareCriteria(
             new ElementSymbol("m.g.c1"), //$NON-NLS-1$
             CompareCriteria.EQ,
@@ -287,14 +282,14 @@
         helpTest(comp, "(m.g.c1 = 'abc') OR (<undefined>)"); //$NON-NLS-1$
     }        
     
-    public void testDelete1() {
+    @Test public void testDelete1() {
     	Delete delete = new Delete();
     	delete.setGroup(new GroupSymbol("m.g"));     //$NON-NLS-1$
     	
     	helpTest(delete, "DELETE FROM m.g"); //$NON-NLS-1$
     }
 
-    public void testDelete2() {
+    @Test public void testDelete2() {
     	Delete delete = new Delete();
     	delete.setGroup(new GroupSymbol("m.g"));    //$NON-NLS-1$
     	delete.setCriteria(new CompareCriteria(
@@ -306,7 +301,7 @@
     	helpTest(delete, "DELETE FROM m.g WHERE m.g.c1 = 'abc'"); //$NON-NLS-1$
     }
     
-    public void testFrom1() {
+    @Test public void testFrom1() {
     	From from = new From();
     	from.addGroup(new GroupSymbol("m.g1"));    //$NON-NLS-1$
     	from.addGroup(new GroupSymbol("m.g2")); //$NON-NLS-1$
@@ -314,7 +309,7 @@
     	helpTest(from, "FROM m.g1, m.g2");     //$NON-NLS-1$
     }
     
-    public void testFrom2() {
+    @Test public void testFrom2() {
     	From from = new From();
     	from.addClause(new UnaryFromClause(new GroupSymbol("m.g1")));   //$NON-NLS-1$
     	from.addClause(new JoinPredicate(
@@ -325,14 +320,14 @@
     	helpTest(from, "FROM m.g1, m.g2 CROSS JOIN m.g3");     //$NON-NLS-1$
     }
     
-    public void testGroupBy1() {
+    @Test public void testGroupBy1() {
     	GroupBy gb = new GroupBy();
     	gb.addSymbol(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
     	
     	helpTest(gb, "GROUP BY m.g.e1");         //$NON-NLS-1$
     }
 
-    public void testGroupBy2() {
+    @Test public void testGroupBy2() {
     	GroupBy gb = new GroupBy();
     	gb.addSymbol(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
     	gb.addSymbol(new ElementSymbol("m.g.e2")); //$NON-NLS-1$
@@ -341,7 +336,7 @@
     	helpTest(gb, "GROUP BY m.g.e1, m.g.e2, m.g.e3");        //$NON-NLS-1$
     }
     
-    public void testInsert1() {
+    @Test public void testInsert1() {
    		Insert insert = new Insert();
    		insert.setGroup(new GroupSymbol("m.g1"));      //$NON-NLS-1$
    		
@@ -357,33 +352,33 @@
    		helpTest(insert, "INSERT INTO m.g1 (e1, e2) VALUES (5, 'abc')"); //$NON-NLS-1$
     }
   
-  	public void testIsNullCriteria1() {
+  	@Test public void testIsNullCriteria1() {
   		IsNullCriteria inc = new IsNullCriteria();
   		inc.setExpression(new Constant("abc")); //$NON-NLS-1$
   		
   		helpTest(inc, "'abc' IS NULL"); //$NON-NLS-1$
   	}
   	
-  	public void testIsNullCriteria2() {
+  	@Test public void testIsNullCriteria2() {
   		IsNullCriteria inc = new IsNullCriteria();
   		inc.setExpression(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
   		
   		helpTest(inc, "m.g.e1 IS NULL"); //$NON-NLS-1$
   	}
 
-    public void testIsNullCriteria3() {
+    @Test public void testIsNullCriteria3() {
         IsNullCriteria inc = new IsNullCriteria();          
         helpTest(inc, "<undefined> IS NULL"); //$NON-NLS-1$
     }
 
-    public void testIsNullCriteria4() {
+    @Test public void testIsNullCriteria4() {
         IsNullCriteria inc = new IsNullCriteria();
         inc.setExpression(new ElementSymbol("m.g.e1")); //$NON-NLS-1$
         inc.setNegated(true);
         helpTest(inc, "m.g.e1 IS NOT NULL"); //$NON-NLS-1$
     }
 
-	public void testJoinPredicate1() {
+	@Test public void testJoinPredicate1() {
 		JoinPredicate jp = new JoinPredicate(
     		new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
     		new UnaryFromClause(new GroupSymbol("m.g3")),  //$NON-NLS-1$
@@ -392,7 +387,7 @@
     	helpTest(jp, "m.g2 CROSS JOIN m.g3"); //$NON-NLS-1$
 	}
     
-    public void testOptionalJoinPredicate1() {
+    @Test public void testOptionalJoinPredicate1() {
         JoinPredicate jp = new JoinPredicate(
             new UnaryFromClause(new GroupSymbol("m.g2")), //$NON-NLS-1$
             new UnaryFromClause(new GroupSymbol("m.g3")),  //$NON-NLS-1$
@@ -401,7 +396,7 @@
         helpTest(jp, "/*+ optional */ (m.g2 CROSS JOIN m.g3)"); //$NON-NLS-1$
     }
 
-	public void testJoinPredicate2() {
+	@Test public void testJoinPredicate2() {
 	    ArrayList<Criteria> crits = new ArrayList<Criteria>();
 	    crits.add(new CompareCriteria(new ElementSymbol("m.g2.e1"), CompareCriteria.EQ, new ElementSymbol("m.g3.e1"))); //$NON-NLS-1$ //$NON-NLS-2$
 		JoinPredicate jp = new JoinPredicate(
@@ -413,7 +408,7 @@
     	helpTest(jp, "m.g2 INNER JOIN m.g3 ON m.g2.e1 = m.g3.e1"); //$NON-NLS-1$
 	}
 	
-	public void testJoinPredicate3() {
+	@Test public void testJoinPredicate3() {
 	    ArrayList<Criteria> crits = new ArrayList<Criteria>();
 	    crits.add(new CompareCriteria(new ElementSymbol("m.g2.e1"), CompareCriteria.EQ, new ElementSymbol("m.g3.e1"))); //$NON-NLS-1$ //$NON-NLS-2$
 	    crits.add(new CompareCriteria(new ElementSymbol("m.g2.e2"), CompareCriteria.EQ, new ElementSymbol("m.g3.e2"))); //$NON-NLS-1$ //$NON-NLS-2$
@@ -426,7 +421,7 @@
     	helpTest(jp, "m.g2 INNER JOIN m.g3 ON m.g2.e1 = m.g3.e1 AND m.g2.e2 = m.g3.e2"); //$NON-NLS-1$
 	}
 
-	public void testJoinPredicate4() {
+	@Test public void testJoinPredicate4() {
 	    ArrayList<Criteria> crits = new ArrayList<Criteria>();
 	    crits.add(new CompareCriteria(new ElementSymbol("m.g2.e1"), CompareCriteria.EQ, new ElementSymbol("m.g3.e1"))); //$NON-NLS-1$ //$NON-NLS-2$
 		JoinPredicate jp = new JoinPredicate(
@@ -443,7 +438,7 @@
     	helpTest(jp2, "(m.g2 INNER JOIN m.g3 ON m.g2.e1 = m.g3.e1) CROSS JOIN m.g1"); //$NON-NLS-1$
 	}
 
-    public void testJoinPredicate5() {
+    @Test public void testJoinPredicate5() {
         ArrayList<Criteria> crits = new ArrayList<Criteria>();
         crits.add(new NotCriteria(new CompareCriteria(new ElementSymbol("m.g2.e1"), CompareCriteria.EQ, new ElementSymbol("m.g3.e1")))); //$NON-NLS-1$ //$NON-NLS-2$
         JoinPredicate jp = new JoinPredicate(
@@ -455,27 +450,27 @@
         helpTest(jp, "m.g2 INNER JOIN m.g3 ON NOT (m.g2.e1 = m.g3.e1)"); //$NON-NLS-1$
     }
 
-	public void testJoinType1() {
+	@Test public void testJoinType1() {
 		helpTest(JoinType.JOIN_CROSS, "CROSS JOIN");     //$NON-NLS-1$
 	}
 
-	public void testJoinType2() {
+	@Test public void testJoinType2() {
 		helpTest(JoinType.JOIN_INNER, "INNER JOIN");     //$NON-NLS-1$
 	}
 
-	public void testJoinType3() {
+	@Test public void testJoinType3() {
 		helpTest(JoinType.JOIN_RIGHT_OUTER, "RIGHT OUTER JOIN");     //$NON-NLS-1$
 	}
 
-	public void testJoinType4() {
+	@Test public void testJoinType4() {
 		helpTest(JoinType.JOIN_LEFT_OUTER, "LEFT OUTER JOIN");     //$NON-NLS-1$
 	}
 
-	public void testJoinType5() {
+	@Test public void testJoinType5() {
 		helpTest(JoinType.JOIN_FULL_OUTER, "FULL OUTER JOIN");     //$NON-NLS-1$
 	}
 
-	public void testMatchCriteria1() {
+	@Test public void testMatchCriteria1() {
 		MatchCriteria mc = new MatchCriteria();
 		mc.setLeftExpression(new ElementSymbol("m.g.e1"));     //$NON-NLS-1$
 		mc.setRightExpression(new Constant("abc")); //$NON-NLS-1$
@@ -483,7 +478,7 @@
 		helpTest(mc, "m.g.e1 LIKE 'abc'"); //$NON-NLS-1$
 	}
 	
-	public void testMatchCriteria2() {
+	@Test public void testMatchCriteria2() {
 		MatchCriteria mc = new MatchCriteria();
 		mc.setLeftExpression(new ElementSymbol("m.g.e1"));     //$NON-NLS-1$
 		mc.setRightExpression(new Constant("%")); //$NON-NLS-1$
@@ -492,7 +487,7 @@
 		helpTest(mc, "m.g.e1 LIKE '%' ESCAPE '#'"); //$NON-NLS-1$
 	}
 	
-    public void testMatchCriteria3() {
+    @Test public void testMatchCriteria3() {
         MatchCriteria mc = new MatchCriteria();
         mc.setLeftExpression(new ElementSymbol("m.g.e1"));     //$NON-NLS-1$
         mc.setRightExpression(new Constant("abc")); //$NON-NLS-1$
@@ -500,22 +495,22 @@
         helpTest(mc, "m.g.e1 NOT LIKE 'abc'"); //$NON-NLS-1$
     }
     
-	public void testNotCriteria1() {
+	@Test public void testNotCriteria1() {
 		NotCriteria not = new NotCriteria(new IsNullCriteria(new ElementSymbol("m.g.e1"))); //$NON-NLS-1$
 		helpTest(not, "NOT (m.g.e1 IS NULL)"); //$NON-NLS-1$
 	}
 	
-	public void testNotCriteria2() {
+	@Test public void testNotCriteria2() {
 		NotCriteria not = new NotCriteria();
 		helpTest(not, "NOT (<undefined>)"); //$NON-NLS-1$
 	}
 
-	public void testOption1() {
+	@Test public void testOption1() {
 		Option option = new Option();
 		helpTest(option, "OPTION");     //$NON-NLS-1$
 	}
 
-    public void testOption5() {
+    @Test public void testOption5() {
         Option option = new Option();
         option.addDependentGroup("abc"); //$NON-NLS-1$
         option.addDependentGroup("def"); //$NON-NLS-1$
@@ -523,7 +518,7 @@
         helpTest(option, "OPTION MAKEDEP abc, def, xyz");     //$NON-NLS-1$
     }
 
-    public void testOption6() {
+    @Test public void testOption6() {
         Option option = new Option();
         option.addDependentGroup("abc"); //$NON-NLS-1$
         option.addDependentGroup("def"); //$NON-NLS-1$
@@ -531,7 +526,7 @@
         helpTest(option, "OPTION MAKEDEP abc, def, xyz");     //$NON-NLS-1$
     }
 
-    public void testOption8() {
+    @Test public void testOption8() {
         Option option = new Option();
         option.addNoCacheGroup("abc"); //$NON-NLS-1$
         option.addNoCacheGroup("def"); //$NON-NLS-1$
@@ -540,20 +535,20 @@
     }
     
 //  related to defect 14423
-    public void testOption9() {
+    @Test public void testOption9() {
         Option option = new Option();
         option.setNoCache(true);
         helpTest(option, "OPTION NOCACHE");     //$NON-NLS-1$
     }
     
-	public void testOrderBy1() {
+	@Test public void testOrderBy1() {
 		OrderBy ob = new OrderBy();
 		ob.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
 		
 		helpTest(ob, "ORDER BY e1");     //$NON-NLS-1$
 	}
 
-	public void testOrderBy2() {
+	@Test public void testOrderBy2() {
 		OrderBy ob = new OrderBy();
 		ob.addVariable(new ElementSymbol("e1")); //$NON-NLS-1$
 		ob.addVariable(new AliasSymbol("x", new ElementSymbol("e2"))); //$NON-NLS-1$ //$NON-NLS-2$
@@ -561,7 +556,7 @@
 		helpTest(ob, "ORDER BY e1, x");     //$NON-NLS-1$
 	}
 
-	public void testOrderBy3() {
+	@Test public void testOrderBy3() {
 		OrderBy ob = new OrderBy();
 		ob.addVariable(new ElementSymbol("e1"), OrderBy.DESC); //$NON-NLS-1$
 		ob.addVariable(new ElementSymbol("x"), OrderBy.DESC); //$NON-NLS-1$
@@ -569,9 +564,9 @@
 		helpTest(ob, "ORDER BY e1 DESC, x DESC");     //$NON-NLS-1$
 	}
 
-	public void testQuery1() {
+	@Test public void testQuery1() {
 		Select select = new Select();
-		select.addSymbol(new AllSymbol());
+		select.addSymbol(new MultipleElementSymbol());
 		From from = new From();
 		from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
 		Query query = new Query();
@@ -581,9 +576,9 @@
 		helpTest(query, "SELECT * FROM m.g");		     //$NON-NLS-1$
 	}
 
-	public void testQuery2() {
+	@Test public void testQuery2() {
 		Select select = new Select();
-		select.addSymbol(new AllSymbol());
+		select.addSymbol(new MultipleElementSymbol());
 		From from = new From();
 		from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
 		CompareCriteria cc = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(5))); //$NON-NLS-1$
@@ -604,9 +599,9 @@
 		helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0 ORDER BY e1");		     //$NON-NLS-1$
 	}
 
-	public void testQuery3() {
+	@Test public void testQuery3() {
 		Select select = new Select();
-		select.addSymbol(new AllSymbol());
+		select.addSymbol(new MultipleElementSymbol());
 		From from = new From();
 		from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
 		GroupBy groupBy = new GroupBy();
@@ -625,9 +620,9 @@
 		helpTest(query, "SELECT * FROM m.g GROUP BY e1 HAVING e1 > 0 ORDER BY e1");		     //$NON-NLS-1$
 	}
 
-	public void testQuery4() {
+	@Test public void testQuery4() {
 		Select select = new Select();
-		select.addSymbol(new AllSymbol());
+		select.addSymbol(new MultipleElementSymbol());
 		From from = new From();
 		from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
 		CompareCriteria cc = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(5))); //$NON-NLS-1$
@@ -645,9 +640,9 @@
 		helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 HAVING e1 > 0 ORDER BY e1");		     //$NON-NLS-1$
 	}
 
-	public void testQuery5() {
+	@Test public void testQuery5() {
 		Select select = new Select();
-		select.addSymbol(new AllSymbol());
+		select.addSymbol(new MultipleElementSymbol());
 		From from = new From();
 		from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
 		CompareCriteria cc = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(5))); //$NON-NLS-1$
@@ -666,9 +661,9 @@
 		helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 ORDER BY e1");		     //$NON-NLS-1$
 	}
 
-	public void testQuery6() {
+	@Test public void testQuery6() {
 		Select select = new Select();
-		select.addSymbol(new AllSymbol());
+		select.addSymbol(new MultipleElementSymbol());
 		From from = new From();
 		from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
 		CompareCriteria cc = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(5))); //$NON-NLS-1$
@@ -686,9 +681,9 @@
 		helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0");		     //$NON-NLS-1$
 	}
 
-	public void testQuery7() {
+	@Test public void testQuery7() {
 		Select select = new Select();
-		select.addSymbol(new AllSymbol());
+		select.addSymbol(new MultipleElementSymbol());
 		From from = new From();
 		from.addGroup(new GroupSymbol("m.g")); //$NON-NLS-1$
 		CompareCriteria cc = new CompareCriteria(new ElementSymbol("e1"), CompareCriteria.EQ, new Constant(new Integer(5))); //$NON-NLS-1$
@@ -709,14 +704,14 @@
 		helpTest(query, "SELECT * FROM m.g WHERE e1 = 5 GROUP BY e1 HAVING e1 > 0 ORDER BY e1");		     //$NON-NLS-1$
 	}
 	
-	public void testSelect1() {
+	@Test public void testSelect1() {
 		Select select = new Select();
 		select.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
 		
 		helpTest(select, "SELECT e1"); //$NON-NLS-1$
 	}
 
-	public void testSelect2() {
+	@Test public void testSelect2() {
 		Select select = new Select();
 		select.setDistinct(true);
 		select.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
@@ -724,7 +719,7 @@
 		helpTest(select, "SELECT DISTINCT e1"); //$NON-NLS-1$
 	}
 
-	public void testSelect3() {
+	@Test public void testSelect3() {
 		Select select = new Select();
 		select.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
 		select.addSymbol(new ElementSymbol("e2")); //$NON-NLS-1$
@@ -732,7 +727,7 @@
 		helpTest(select, "SELECT e1, e2"); //$NON-NLS-1$
 	}
 
-	public void testSetCriteria1() {
+	@Test public void testSetCriteria1() {
 		SetCriteria sc = new SetCriteria();
 		sc.setExpression(new ElementSymbol("e1"));		 //$NON-NLS-1$
 		sc.setValues(new ArrayList());
@@ -740,7 +735,7 @@
 		helpTest(sc, "e1 IN ()"); //$NON-NLS-1$
 	}
 
-	public void testSetCriteria2() {
+	@Test public void testSetCriteria2() {
 		SetCriteria sc = new SetCriteria();
 		sc.setExpression(new ElementSymbol("e1"));	 //$NON-NLS-1$
 		ArrayList values = new ArrayList();	
@@ -751,7 +746,7 @@
 		helpTest(sc, "e1 IN (e2, 'abc')"); //$NON-NLS-1$
 	}
 
-	public void testSetCriteria3() {
+	@Test public void testSetCriteria3() {
 		SetCriteria sc = new SetCriteria();
 		sc.setExpression(new ElementSymbol("e1"));	 //$NON-NLS-1$
 		ArrayList values = new ArrayList();	
@@ -762,7 +757,7 @@
 		helpTest(sc, "e1 IN (<undefined>, 'b')"); //$NON-NLS-1$
 	}	
     
-    public void testSetCriteria4() {
+    @Test public void testSetCriteria4() {
         SetCriteria sc = new SetCriteria();
         sc.setExpression(new ElementSymbol("e1"));   //$NON-NLS-1$
         ArrayList values = new ArrayList(); 
@@ -773,7 +768,7 @@
         helpTest(sc, "e1 NOT IN (e2, 'abc')"); //$NON-NLS-1$
     }
     
-	public void testSetQuery1() {
+	@Test public void testSetQuery1() {
 		Select s1 = new Select();
 		s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
 		From f1 = new From();
@@ -795,7 +790,7 @@
 		helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2"); //$NON-NLS-1$
 	}
 
-	public void testSetQuery2() {
+	@Test public void testSetQuery2() {
 		Select s1 = new Select();
 		s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
 		From f1 = new From();
@@ -817,7 +812,7 @@
 		helpTest(sq, "SELECT e1 FROM m.g1 UNION ALL SELECT e1 FROM m.g2"); //$NON-NLS-1$
 	}
 
-	public void testSetQuery3() {
+	@Test public void testSetQuery3() {
 		Select s1 = new Select();
 		s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
 		From f1 = new From();
@@ -843,7 +838,7 @@
 		helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2 ORDER BY e1"); //$NON-NLS-1$
 	}
 
-	public void testSetQuery4() {
+	@Test public void testSetQuery4() {
 		Select s1 = new Select();
 		s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
 		From f1 = new From();
@@ -865,7 +860,7 @@
 		helpTest(sq, "SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2"); //$NON-NLS-1$
 	}
 	
-	public void testSetQuery5() {
+	@Test public void testSetQuery5() {
 		Select s1 = new Select();
 		s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
 		From f1 = new From();
@@ -897,7 +892,7 @@
 		helpTest(sq2, "SELECT e3 FROM m.g3 UNION ALL (SELECT e1 FROM m.g1 UNION SELECT e1 FROM m.g2)"); //$NON-NLS-1$
 	}
 	
-    public void testSubqueryFromClause1() {
+    @Test public void testSubqueryFromClause1() {
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
         From f1 = new From();
@@ -910,7 +905,7 @@
         helpTest(sfc, "(SELECT e1 FROM m.g1) AS temp");             //$NON-NLS-1$
     }
     
-    public void testOptionalSubqueryFromClause1() {
+    @Test public void testOptionalSubqueryFromClause1() {
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
         From f1 = new From();
@@ -924,7 +919,7 @@
         helpTest(sfc, "/*+ optional */ (SELECT e1 FROM m.g1) AS temp");             //$NON-NLS-1$
     }
 
-    public void testSubquerySetCriteria1() {
+    @Test public void testSubquerySetCriteria1() {
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
         From f1 = new From();
@@ -939,7 +934,7 @@
         helpTest(ssc, "e2 IN (SELECT e1 FROM m.g1)");             //$NON-NLS-1$
     }
     
-    public void testSubquerySetCriteria2() {
+    @Test public void testSubquerySetCriteria2() {
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
         From f1 = new From();
@@ -955,17 +950,17 @@
         helpTest(ssc, "e2 NOT IN (SELECT e1 FROM m.g1)");             //$NON-NLS-1$
     }
         
-	public void testUnaryFromClause() {
+	@Test public void testUnaryFromClause() {
 		helpTest(new UnaryFromClause(new GroupSymbol("m.g1")), "m.g1");     //$NON-NLS-1$ //$NON-NLS-2$
 	}
     
-    public void testOptionalUnaryFromClause() {
+    @Test public void testOptionalUnaryFromClause() {
         UnaryFromClause unaryFromClause = new UnaryFromClause(new GroupSymbol("m.g1"));//$NON-NLS-1$
         unaryFromClause.setOptional(true);
         helpTest(unaryFromClause, "/*+ optional */ m.g1");     //$NON-NLS-1$ 
     }
 	
-	public void testUpdate1() {
+	@Test public void testUpdate1() {
 		Update update = new Update();
 		update.setGroup(new GroupSymbol("m.g1"));     //$NON-NLS-1$
 		update.addChange(new ElementSymbol("e1"), new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
@@ -973,7 +968,7 @@
 		helpTest(update, "UPDATE m.g1 SET e1 = 'abc'"); //$NON-NLS-1$
 	}
 	
-	public void testUpdate2() {
+	@Test public void testUpdate2() {
 		Update update = new Update();
 		update.setGroup(new GroupSymbol("m.g1"));     //$NON-NLS-1$
 		update.addChange(new ElementSymbol("e1"), new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
@@ -982,7 +977,7 @@
 		helpTest(update, "UPDATE m.g1 SET e1 = 'abc', e2 = 'xyz'"); //$NON-NLS-1$
 	}
 	
-	public void testUpdate3() {
+	@Test public void testUpdate3() {
 		Update update = new Update();
 		update.setGroup(new GroupSymbol("m.g1"));     //$NON-NLS-1$
 		update.addChange(new ElementSymbol("e1"), new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
@@ -995,163 +990,163 @@
 		helpTest(update, "UPDATE m.g1 SET e1 = 'abc' WHERE e2 = 'abc'"); //$NON-NLS-1$
 	}
 	
-	public void testAggregateSymbol1() {
+	@Test public void testAggregateSymbol1() {
 		AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.COUNT, false, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(agg, "COUNT('abc')"); //$NON-NLS-1$
 	}
 	
-	public void testAggregateSymbol2() {
+	@Test public void testAggregateSymbol2() {
 		AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.COUNT, true, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(agg, "COUNT(DISTINCT 'abc')"); //$NON-NLS-1$
 	}
 	
-	public void testAggregateSymbol3() {
+	@Test public void testAggregateSymbol3() {
 		AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.COUNT, false, null); //$NON-NLS-1$
 		helpTest(agg, "COUNT(*)"); //$NON-NLS-1$
 	}
 	
-	public void testAggregateSymbol4() {
+	@Test public void testAggregateSymbol4() {
 		AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.AVG, false, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(agg, "AVG('abc')"); //$NON-NLS-1$
 	}
 	
-	public void testAggregateSymbol5() {
+	@Test public void testAggregateSymbol5() {
 		AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.SUM, false, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(agg, "SUM('abc')"); //$NON-NLS-1$
 	}
 	
-	public void testAggregateSymbol6() {
+	@Test public void testAggregateSymbol6() {
 		AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.MIN, false, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(agg, "MIN('abc')"); //$NON-NLS-1$
 	}
 	
-	public void testAggregateSymbol7() {
+	@Test public void testAggregateSymbol7() {
 		AggregateSymbol agg = new AggregateSymbol("abc", NonReserved.MAX, false, new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(agg, "MAX('abc')"); //$NON-NLS-1$
 	}
 	
-	public void testAliasSymbol1() {
+	@Test public void testAliasSymbol1() {
 	    AliasSymbol as = new AliasSymbol("x", new ElementSymbol("y")); //$NON-NLS-1$ //$NON-NLS-2$
 	    helpTest(as, "y AS x"); //$NON-NLS-1$
 	}
 
 	// Test alias symbol with reserved word 
-	public void testAliasSymbol2() {
+	@Test public void testAliasSymbol2() {
 	    AliasSymbol as = new AliasSymbol("select", new ElementSymbol("y")); //$NON-NLS-1$ //$NON-NLS-2$
 	    helpTest(as, "y AS \"select\""); //$NON-NLS-1$
 	}
 
-	public void testAllSymbol() {
-		helpTest(new AllSymbol(), "*");     //$NON-NLS-1$
+	@Test public void testAllSymbol() {
+		helpTest(new MultipleElementSymbol(), "*");     //$NON-NLS-1$
 	}
 	
-	public void testAllInGroupSymbol() {
-	    helpTest(new AllInGroupSymbol("m.g.*"), "m.g.*"); //$NON-NLS-1$ //$NON-NLS-2$
+	@Test public void testAllInGroupSymbol() {
+	    helpTest(new MultipleElementSymbol("m.g"), "m.g.*"); //$NON-NLS-1$ //$NON-NLS-2$
 	}
 	
-    public void testConstantNull() { 
+    @Test public void testConstantNull() { 
         helpTest(new Constant(null), "null"); //$NON-NLS-1$
     }
 
-    public void testConstantString() { 
+    @Test public void testConstantString() { 
         helpTest(new Constant("abc"), "'abc'"); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testConstantInteger() { 
+    @Test public void testConstantInteger() { 
         helpTest(new Constant(new Integer(5)), "5"); //$NON-NLS-1$
     }
 
-    public void testConstantBigDecimal() { 
+    @Test public void testConstantBigDecimal() { 
         helpTest(new Constant(new BigDecimal("5.4")), "5.4"); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testConstantStringWithTick() { 
+    @Test public void testConstantStringWithTick() { 
         helpTest(new Constant("O'Leary"), "'O''Leary'"); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testConstantStringWithTicks() { 
+    @Test public void testConstantStringWithTicks() { 
         helpTest(new Constant("'abc'"), "'''abc'''"); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testConstantStringWithMoreTicks() { 
+    @Test public void testConstantStringWithMoreTicks() { 
         helpTest(new Constant("a'b'c"), "'a''b''c'"); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
-    public void testConstantStringWithDoubleTick() {
+    @Test public void testConstantStringWithDoubleTick() {
     	helpTest(new Constant("group=\"x\""), "'group=\"x\"'");     //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testConstantBooleanTrue() {
+    @Test public void testConstantBooleanTrue() {
         helpTest(new Constant(Boolean.TRUE), "TRUE");     //$NON-NLS-1$
     }
 
-    public void testConstantBooleanFalse() {
+    @Test public void testConstantBooleanFalse() {
         helpTest(new Constant(Boolean.FALSE), "FALSE");     //$NON-NLS-1$
     }
 
-    public void testConstantDate() {
+    @Test public void testConstantDate() {
         helpTest(new Constant(java.sql.Date.valueOf("2002-10-02")), "{d'2002-10-02'}");     //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testConstantTime() {
+    @Test public void testConstantTime() {
         helpTest(new Constant(java.sql.Time.valueOf("5:00:00")), "{t'05:00:00'}");     //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testConstantTimestamp() {
+    @Test public void testConstantTimestamp() {
         helpTest(new Constant(java.sql.Timestamp.valueOf("2002-10-02 17:10:35.0234")), "{ts'2002-10-02 17:10:35.0234'}");     //$NON-NLS-1$ //$NON-NLS-2$
     }
     
-    public void testElementSymbol1() {
+    @Test public void testElementSymbol1() {
         ElementSymbol es = new ElementSymbol("elem"); //$NON-NLS-1$
         helpTest(es, "elem"); //$NON-NLS-1$
     }
     
-    public void testElementSymbol2() {
+    @Test public void testElementSymbol2() {
         ElementSymbol es = new ElementSymbol("elem", false); //$NON-NLS-1$
         es.setGroupSymbol(new GroupSymbol("m.g")); //$NON-NLS-1$
         helpTest(es, "elem"); //$NON-NLS-1$
     }
 
-    public void testElementSymbol3() {
+    @Test public void testElementSymbol3() {
         ElementSymbol es = new ElementSymbol("m.g.elem", true); //$NON-NLS-1$
         es.setGroupSymbol(new GroupSymbol("m.g")); //$NON-NLS-1$
         helpTest(es, "m.g.elem"); //$NON-NLS-1$
     }
 
-    public void testElementSymbol4() {
+    @Test public void testElementSymbol4() {
         ElementSymbol es = new ElementSymbol("vdb.m.g.elem", true); //$NON-NLS-1$
         helpTest(es, "vdb.m.g.elem"); //$NON-NLS-1$
     }
     
-    public void testElementSymbol5() {
+    @Test public void testElementSymbol5() {
     	ElementSymbol es = new ElementSymbol("m.g.select", false); //$NON-NLS-1$
     	es.setGroupSymbol(new GroupSymbol("m.g")); //$NON-NLS-1$
     	helpTest(es, "\"select\"");     //$NON-NLS-1$
     }
 
-    public void testExpressionSymbol1() {
+    @Test public void testExpressionSymbol1() {
 		ExpressionSymbol expr = new ExpressionSymbol("abc", new Constant("abc")); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(expr, "'abc'"); //$NON-NLS-1$
     }
 
-    public void testFunction1() {
+    @Test public void testFunction1() {
         Function func = new Function("concat", new Expression[] { //$NON-NLS-1$
         	new Constant("a"), null     //$NON-NLS-1$
         });
     	helpTest(func, "concat('a', <undefined>)"); //$NON-NLS-1$
     }
 
-    public void testFunction2() {
+    @Test public void testFunction2() {
         Function func = new Function("now", new Expression[] {}); //$NON-NLS-1$
     	helpTest(func, "now()"); //$NON-NLS-1$
     }
 
-    public void testFunction3() {
+    @Test public void testFunction3() {
         Function func = new Function("concat", new Expression[] {null, null}); //$NON-NLS-1$
     	helpTest(func, "concat(<undefined>, <undefined>)"); //$NON-NLS-1$
     }
 
-    public void testFunction4() {
+    @Test public void testFunction4() {
         Function func1 = new Function("power", new Expression[] { //$NON-NLS-1$
             new Constant(new Integer(5)), 
             new Constant(new Integer(3)) });
@@ -1164,7 +1159,7 @@
     	helpTest(func3, "(1000 + power(power(5, 3), 3))"); //$NON-NLS-1$
     }
 
-    public void testFunction5() {
+    @Test public void testFunction5() {
         Function func1 = new Function("concat", new Expression[] { //$NON-NLS-1$
             new ElementSymbol("elem2"), //$NON-NLS-1$
             null });
@@ -1174,7 +1169,7 @@
         helpTest(func2, "concat(elem1, concat(elem2, <undefined>))"); //$NON-NLS-1$
     }
 
-    public void testConvertFunction1() {
+    @Test public void testConvertFunction1() {
         Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
         	new Constant("5"),  //$NON-NLS-1$
         	new Constant("integer")     //$NON-NLS-1$
@@ -1182,7 +1177,7 @@
     	helpTest(func, "convert('5', integer)"); //$NON-NLS-1$
     }
    
-    public void testConvertFunction2() {
+    @Test public void testConvertFunction2() {
         Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
         	null, 
         	new Constant("integer")     //$NON-NLS-1$
@@ -1190,7 +1185,7 @@
     	helpTest(func, "convert(<undefined>, integer)"); //$NON-NLS-1$
     }
 
-    public void testConvertFunction3() {
+    @Test public void testConvertFunction3() {
         Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
         	new Constant(null), 
         	new Constant("integer")     //$NON-NLS-1$
@@ -1198,7 +1193,7 @@
     	helpTest(func, "convert(null, integer)"); //$NON-NLS-1$
     }
 
-    public void testConvertFunction4() {
+    @Test public void testConvertFunction4() {
         Function func = new Function("convert", new Expression[] { //$NON-NLS-1$
         	new Constant("abc"),  //$NON-NLS-1$
         	null    
@@ -1206,22 +1201,22 @@
     	helpTest(func, "convert('abc', <undefined>)"); //$NON-NLS-1$
     }
 
-    public void testConvertFunction5() {
+    @Test public void testConvertFunction5() {
         Function func = new Function("convert", null); //$NON-NLS-1$
     	helpTest(func, "convert()"); //$NON-NLS-1$
     }
 
-    public void testConvertFunction6() {
+    @Test public void testConvertFunction6() {
         Function func = new Function("convert", new Expression[0]); //$NON-NLS-1$
     	helpTest(func, "convert()"); //$NON-NLS-1$
     }
 
-    public void testConvertFunction7() {
+    @Test public void testConvertFunction7() {
         Function func = new Function("convert", new Expression[] {new Constant("abc")}); //$NON-NLS-1$ //$NON-NLS-2$
     	helpTest(func, "convert('abc', <undefined>)"); //$NON-NLS-1$
     }
 
-    public void testCastFunction1() {
+    @Test public void testCastFunction1() {
         Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
         	new Constant("5"),  //$NON-NLS-1$
         	new Constant("integer")     //$NON-NLS-1$
@@ -1229,7 +1224,7 @@
     	helpTest(func, "cast('5' AS integer)"); //$NON-NLS-1$
     }
    
-    public void testCastFunction2() {
+    @Test public void testCastFunction2() {
         Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
         	null, 
         	new Constant("integer")     //$NON-NLS-1$
@@ -1237,7 +1232,7 @@
     	helpTest(func, "cast(<undefined> AS integer)"); //$NON-NLS-1$
     }
 
-    public void testCastFunction3() {
+    @Test public void testCastFunction3() {
         Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
         	new Constant(null), 
         	new Constant("integer")     //$NON-NLS-1$
@@ -1245,7 +1240,7 @@
     	helpTest(func, "cast(null AS integer)"); //$NON-NLS-1$
     }
 
-    public void testCastFunction4() {
+    @Test public void testCastFunction4() {
         Function func = new Function("cast", new Expression[] { //$NON-NLS-1$
         	new Constant("abc"),  //$NON-NLS-1$
         	null    
@@ -1253,50 +1248,50 @@
     	helpTest(func, "cast('abc' AS <undefined>)"); //$NON-NLS-1$
     }
     
-    public void testArithemeticFunction1() { 
+    @Test public void testArithemeticFunction1() { 
     	Function func = new Function("-", new Expression[] {  //$NON-NLS-1$
     	    new Constant(new Integer(-2)),
     	    new Constant(new Integer(-1))});
     	helpTest(func, "(-2 - -1)");     //$NON-NLS-1$
     }
     
-    public void testGroupSymbol1() {
+    @Test public void testGroupSymbol1() {
 		GroupSymbol gs = new GroupSymbol("g"); //$NON-NLS-1$
 		helpTest(gs, "g"); //$NON-NLS-1$
     }
 
-    public void testGroupSymbol2() {
+    @Test public void testGroupSymbol2() {
 		GroupSymbol gs = new GroupSymbol("x", "g"); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(gs, "g AS x"); //$NON-NLS-1$
     }
 
-    public void testGroupSymbol3() {
+    @Test public void testGroupSymbol3() {
 		GroupSymbol gs = new GroupSymbol("vdb.g"); //$NON-NLS-1$
 		helpTest(gs, "vdb.g"); //$NON-NLS-1$
     }
 
-    public void testGroupSymbol4() {
+    @Test public void testGroupSymbol4() {
 		GroupSymbol gs = new GroupSymbol("x", "vdb.g"); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(gs, "vdb.g AS x"); //$NON-NLS-1$
     }
  
-    public void testGroupSymbol5() {
+    @Test public void testGroupSymbol5() {
 		GroupSymbol gs = new GroupSymbol("from", "m.g"); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(gs, "m.g AS \"from\""); //$NON-NLS-1$
     }
 
-    public void testGroupSymbol6() {
+    @Test public void testGroupSymbol6() {
 		GroupSymbol gs = new GroupSymbol("x", "on.select"); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(gs, "\"on\".\"select\" AS x"); //$NON-NLS-1$
     }
    
-    public void testExecNoParams() {
+    @Test public void testExecNoParams() {
         StoredProcedure proc = new StoredProcedure();
         proc.setProcedureName("myproc"); //$NON-NLS-1$
         helpTest(proc, "EXEC myproc()"); //$NON-NLS-1$
     }
    
-    public void testExecInputParam() {
+    @Test public void testExecInputParam() {
         StoredProcedure proc = new StoredProcedure();
         proc.setProcedureName("myproc"); //$NON-NLS-1$
         SPParameter param = new SPParameter(1, new Reference(0));
@@ -1304,7 +1299,7 @@
         helpTest(proc, "EXEC myproc(?)"); //$NON-NLS-1$
     }
 
-    public void testExecInputOutputParam() {
+    @Test public void testExecInputOutputParam() {
         StoredProcedure proc = new StoredProcedure();
         proc.setProcedureName("myproc"); //$NON-NLS-1$
         SPParameter param1 = new SPParameter(1, new Constant(new Integer(5)));
@@ -1317,7 +1312,7 @@
         helpTest(proc, "EXEC myproc(5)"); //$NON-NLS-1$
     }
 
-    public void testExecOutputInputParam() {
+    @Test public void testExecOutputInputParam() {
         StoredProcedure proc = new StoredProcedure();
         proc.setProcedureName("myproc"); //$NON-NLS-1$
 
@@ -1331,7 +1326,7 @@
         helpTest(proc, "EXEC myproc(5)"); //$NON-NLS-1$
     }
 
-    public void testExecReturnParam() {
+    @Test public void testExecReturnParam() {
         StoredProcedure proc = new StoredProcedure();
         proc.setProcedureName("myproc"); //$NON-NLS-1$
         
@@ -1340,7 +1335,7 @@
         helpTest(proc, "EXEC myproc()"); //$NON-NLS-1$
     }
     
-    public void testExecNamedParam() {
+    @Test public void testExecNamedParam() {
         StoredProcedure proc = new StoredProcedure();
         proc.setDisplayNamedParameters(true);
         proc.setProcedureName("myproc"); //$NON-NLS-1$
@@ -1350,7 +1345,7 @@
         helpTest(proc, "EXEC myproc(p1 => ?)"); //$NON-NLS-1$
     }
 
-    public void testExecNamedParams() {
+    @Test public void testExecNamedParams() {
         StoredProcedure proc = new StoredProcedure();
         proc.setDisplayNamedParameters(true);
         proc.setProcedureName("myproc"); //$NON-NLS-1$
@@ -1370,7 +1365,7 @@
      * 
      * @since 4.3
      */
-    public void testExecNamedParamsReservedWord() {
+    @Test public void testExecNamedParamsReservedWord() {
         StoredProcedure proc = new StoredProcedure();
         proc.setDisplayNamedParameters(true);
         proc.setProcedureName("myproc"); //$NON-NLS-1$
@@ -1385,27 +1380,27 @@
 
     // Test methods for Update Procedure Language Objects
     
-    public void testDeclareStatement() {
+    @Test public void testDeclareStatement() {
 		DeclareStatement dclStmt = new DeclareStatement(new ElementSymbol("a"), "String"); //$NON-NLS-1$ //$NON-NLS-2$
 		helpTest(dclStmt, "DECLARE String a;"); //$NON-NLS-1$
     }
 
-    public void testRaiseErrorStatement() {
+    @Test public void testRaiseErrorStatement() {
     	RaiseErrorStatement errStmt =	new RaiseErrorStatement(new Constant("My Error")); //$NON-NLS-1$
 		helpTest(errStmt, "ERROR 'My Error';"); //$NON-NLS-1$
     }  
     
-    public void testRaiseErrorStatementWithExpression() {
+    @Test public void testRaiseErrorStatementWithExpression() {
         RaiseErrorStatement errStmt =   new RaiseErrorStatement(new ElementSymbol("a")); //$NON-NLS-1$
         helpTest(errStmt, "ERROR a;"); //$NON-NLS-1$
     }
     
-    public void testAssignmentStatement1() {
+    @Test public void testAssignmentStatement1() {
     	AssignmentStatement assigStmt =	new AssignmentStatement(new ElementSymbol("a"), new Constant(new Integer(1))); //$NON-NLS-1$
 		helpTest(assigStmt, "a = 1;"); //$NON-NLS-1$
     }
     
-    public void testAssignmentStatement2() {
+    @Test public void testAssignmentStatement2() {
         Query q1 = new Query();
         Select select = new Select();
         select.addSymbol(new ElementSymbol("x"));        //$NON-NLS-1$
@@ -1418,7 +1413,7 @@
 		helpTest(assigStmt, "a = (SELECT x FROM g);"); //$NON-NLS-1$
     }
     
-    public void testCriteriaSelector1() {
+    @Test public void testCriteriaSelector1() {
 		ElementSymbol sy1 = new ElementSymbol("a"); //$NON-NLS-1$
 		ElementSymbol sy2 = new ElementSymbol("b"); //$NON-NLS-1$
 		ElementSymbol sy3 = new ElementSymbol("c"); //$NON-NLS-1$
@@ -1430,7 +1425,7 @@
 		helpTest(cs, "= CRITERIA ON (a, b, c)"); //$NON-NLS-1$
     }    
     
-    public void testCriteriaSelector2() {
+    @Test public void testCriteriaSelector2() {
         ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
         ElementSymbol sy2 = new ElementSymbol("y"); //$NON-NLS-1$
         ElementSymbol sy3 = new ElementSymbol("z"); //$NON-NLS-1$
@@ -1442,7 +1437,7 @@
         helpTest(cs, "LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
     }
     
-    public void testCriteriaSelector3() {
+    @Test public void testCriteriaSelector3() {
         ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
         ElementSymbol sy2 = new ElementSymbol("y"); //$NON-NLS-1$
         ElementSymbol sy3 = new ElementSymbol("z"); //$NON-NLS-1$
@@ -1454,7 +1449,7 @@
         helpTest(cs, "BETWEEN CRITERIA ON (x, y, z)"); //$NON-NLS-1$
     }
     
-    public void testHasCriteria1() {
+    @Test public void testHasCriteria1() {
 		ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
 		ElementSymbol sy2 = new ElementSymbol("y"); //$NON-NLS-1$
 		ElementSymbol sy3 = new ElementSymbol("z"); //$NON-NLS-1$
@@ -1466,7 +1461,7 @@
 		helpTest(new HasCriteria(cs), "HAS LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
     }
     
-    public void testHasCriteria2() {
+    @Test public void testHasCriteria2() {
         ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
         ElementSymbol sy2 = new ElementSymbol("y"); //$NON-NLS-1$
         ElementSymbol sy3 = new ElementSymbol("z"); //$NON-NLS-1$
@@ -1478,7 +1473,7 @@
         helpTest(new HasCriteria(cs), "HAS LIKE CRITERIA ON (x, y, z)"); //$NON-NLS-1$
     }
     
-    public void testHasCriteria3() {
+    @Test public void testHasCriteria3() {
         ElementSymbol sy1 = new ElementSymbol("x"); //$NON-NLS-1$
         ElementSymbol sy2 = new ElementSymbol("y"); //$NON-NLS-1$
         ElementSymbol sy3 = new ElementSymbol("z"); //$NON-NLS-1$
@@ -1490,7 +1485,7 @@
         helpTest(new HasCriteria(cs), "HAS BETWEEN CRITERIA ON (x, y, z)"); //$NON-NLS-1$
     }
     
-    public void testCommandStatement1() {
+    @Test public void testCommandStatement1() {
         Query q1 = new Query();
         Select select = new Select();
         select.addSymbol(new ElementSymbol("x"));        //$NON-NLS-1$
@@ -1503,14 +1498,14 @@
 		helpTest(cmdStmt, "SELECT x FROM g;"); //$NON-NLS-1$
     }
     
-    public void testCommandStatement2() {
+    @Test public void testCommandStatement2() {
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
     	CommandStatement cmdStmt =	new CommandStatement(d1);
 		helpTest(cmdStmt, "DELETE FROM g;"); //$NON-NLS-1$
     }
     
-    public void testBlock1() {
+    @Test public void testBlock1() {
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
     	CommandStatement cmdStmt =	new CommandStatement(d1);
@@ -1523,7 +1518,7 @@
 		helpTest(b, "BEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
     }
     
-    public void testBlock2() {    	
+    @Test public void testBlock2() {    	
 		// construct If statement
 
         Delete d1 = new Delete();
@@ -1548,7 +1543,7 @@
 		helpTest(b, "BEGIN\nDELETE FROM g;\nIF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\nEND\nERROR 'My Error';\nEND"); //$NON-NLS-1$
     } 
     
-    public void testIfStatement1() {
+    @Test public void testIfStatement1() {
 		// construct If block
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
@@ -1571,7 +1566,7 @@
 		helpTest(ifStmt, "IF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND"); //$NON-NLS-1$
     }
 
-    public void testIfStatement2() {
+    @Test public void testIfStatement2() {
 		// construct If block
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
@@ -1589,7 +1584,7 @@
 		helpTest(ifStmt, "IF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\nEND"); //$NON-NLS-1$
     }
 
-    public void testIfStatement3() {
+    @Test public void testIfStatement3() {
 		// construct If block
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
@@ -1615,7 +1610,7 @@
 		helpTest(ifStmt, "IF(HAS LIKE CRITERIA ON (x))\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND\nELSE\nBEGIN\nDELETE FROM g;\nEND"); //$NON-NLS-1$
     }    
 
-    public void testCreateUpdateProcedure1() {
+    @Test public void testCreateUpdateProcedure1() {
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
     	CommandStatement cmdStmt =	new CommandStatement(d1);
@@ -1629,7 +1624,7 @@
 		helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND");	     //$NON-NLS-1$
     }
     
-    public void testCreateUpdateProcedure2() {
+    @Test public void testCreateUpdateProcedure2() {
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
     	CommandStatement cmdStmt =	new CommandStatement(d1);
@@ -1643,7 +1638,7 @@
 		helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND");	     //$NON-NLS-1$
     }
 
-    public void testCreateUpdateProcedure3() {
+    @Test public void testCreateUpdateProcedure3() {
         Delete d1 = new Delete();
         d1.setGroup(new GroupSymbol("g")); //$NON-NLS-1$
     	CommandStatement cmdStmt =	new CommandStatement(d1);
@@ -1657,7 +1652,7 @@
 		helpTest(cup, "CREATE PROCEDURE\nBEGIN\nDELETE FROM g;\na = 1;\nERROR 'My Error';\nEND");	     //$NON-NLS-1$
     }
 
-    public void testSubqueryCompareCriteria1() {
+    @Test public void testSubqueryCompareCriteria1() {
         
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
@@ -1674,7 +1669,7 @@
         helpTest(scc, "e2 = ANY (SELECT e1 FROM m.g1)");             //$NON-NLS-1$
     }
 
-    public void testSubqueryCompareCriteria2() {
+    @Test public void testSubqueryCompareCriteria2() {
         
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
@@ -1691,7 +1686,7 @@
         helpTest(scc, "e2 <= SOME (SELECT e1 FROM m.g1)");             //$NON-NLS-1$
     }
 
-    public void testExistsCriteria1() {
+    @Test public void testExistsCriteria1() {
         
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
@@ -1706,7 +1701,7 @@
         helpTest(ec, "EXISTS (SELECT e1 FROM m.g1)");             //$NON-NLS-1$
     }
     
-    public void testDynamicCommand() {
+    @Test public void testDynamicCommand() {
 		List symbols = new ArrayList();
 	
 	    ElementSymbol a1 = new ElementSymbol("a1"); //$NON-NLS-1$
@@ -1724,7 +1719,7 @@
 	    helpTest(obj, "EXECUTE 'SELECT a1 FROM g WHERE a2 = 5' AS a1 string INTO #g"); //$NON-NLS-1$
     }
 
-    public void testScalarSubquery() {
+    @Test public void testScalarSubquery() {
         
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
@@ -1739,7 +1734,7 @@
         helpTest(obj, "(SELECT e1 FROM m.g1)");             //$NON-NLS-1$
     }
 
-    public void testNewSubqueryObjects(){
+    @Test public void testNewSubqueryObjects(){
 
         Select s1 = new Select();
         s1.addSymbol(new ElementSymbol("e1")); //$NON-NLS-1$
@@ -1765,35 +1760,35 @@
         helpTest(q2, "SELECT e1, (SELECT e1 FROM m.g1) FROM m.g2 WHERE (e3 >= ANY (SELECT e1 FROM m.g1)) AND (EXISTS (SELECT e1 FROM m.g1))");             //$NON-NLS-1$
     }
     
-    public void testCaseExpression1() {
+    @Test public void testCaseExpression1() {
         helpTest(TestCaseExpression.example(2),
                  "CASE x WHEN 'a' THEN 0 WHEN 'b' THEN 1 ELSE 9999 END"); //$NON-NLS-1$
     }
     
-    public void testCaseExpression2() {
+    @Test public void testCaseExpression2() {
         CaseExpression example = TestCaseExpression.example(2);
         example.setElseExpression(null);
         helpTest(example, "CASE x WHEN 'a' THEN 0 WHEN 'b' THEN 1 END"); //$NON-NLS-1$
     }
     
-    public void testCaseExpression3() {
+    @Test public void testCaseExpression3() {
         CaseExpression example = TestCaseExpression.example(3, 0, true);
         helpTest(example, "CASE x WHEN null THEN 0 WHEN 'b' THEN 1 WHEN 'c' THEN 2 ELSE 9999 END"); //$NON-NLS-1$
     }
     
-    public void testCaseExpression4() {
+    @Test public void testCaseExpression4() {
         CaseExpression example = TestCaseExpression.example(3, 2, true);
         example.setElseExpression(null);
         helpTest(example, "CASE x WHEN 'a' THEN 0 WHEN 'b' THEN 1 WHEN null THEN 2 END"); //$NON-NLS-1$
     }
     
-    public void testSearchedCaseExpression1() {
+    @Test public void testSearchedCaseExpression1() {
         helpTest(TestSearchedCaseExpression.example(2),
                  "CASE WHEN x = 0 THEN 0 WHEN x = 1 THEN 1 ELSE 9999 END"); //$NON-NLS-1$
         
     }
     
-    public void testSearchedCaseExpression2() {
+    @Test public void testSearchedCaseExpression2() {
         SearchedCaseExpression example = TestSearchedCaseExpression.example(2);
         example.setElseExpression(null);
         helpTest(example,
@@ -1805,7 +1800,7 @@
      * For some reason this test was outputting
      * SELECT 'A' AS FOO UNION SELECT 'A' AS FOO
      */
-    public void testSetQueryUnionOfLiteralsCase3102() {
+    @Test public void testSetQueryUnionOfLiteralsCase3102() {
         
         String expected = "SELECT 'A' AS FOO UNION SELECT 'B' AS FOO"; //$NON-NLS-1$
         
@@ -1830,7 +1825,7 @@
      * Same as above except that ExpressionSymbols' internal names (which aren't visible
      * in the query) are different
      */
-    public void testSetQueryUnionOfLiteralsCase3102a() {
+    @Test public void testSetQueryUnionOfLiteralsCase3102a() {
         
         String expected = "SELECT 'A' AS FOO UNION SELECT 'B' AS FOO"; //$NON-NLS-1$
         
@@ -1849,9 +1844,9 @@
         helpTest(sq, expected);        
     } 
 
-    public void testLimit() {
+    @Test public void testLimit() {
         Query query = new Query();
-        Select select = new Select(Arrays.asList(new Object[] {new AllSymbol()}));
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
         From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
         query.setSelect(select);
         query.setFrom(from);
@@ -1859,9 +1854,9 @@
         helpTest(query, "SELECT * FROM a LIMIT 100"); //$NON-NLS-1$
     }
     
-    public void testLimitWithOffset() {
+    @Test public void testLimitWithOffset() {
         Query query = new Query();
-        Select select = new Select(Arrays.asList(new Object[] {new AllSymbol()}));
+        Select select = new Select(Arrays.asList(new MultipleElementSymbol()));
         From from = new From(Arrays.asList(new UnaryFromClause(new GroupSymbol("a")))); //$NON-NLS-1$
         query.setSelect(select);
         query.setFrom(from);
@@ -1869,28 +1864,47 @@
         helpTest(query, "SELECT * FROM a LIMIT 50, 100"); //$NON-NLS-1$ 
     }
     
-    public void testUnionOrderBy() throws Exception {
+    @Test public void testUnionOrderBy() throws Exception {
         Command command = QueryParser.getQueryParser().parseCommand("select pm1.g1.e1 from pm1.g1 union select e2 from pm1.g2 order by e1"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
         helpTest(command, "SELECT pm1.g1.e1 FROM pm1.g1 UNION SELECT e2 FROM pm1.g2 ORDER BY e1"); //$NON-NLS-1$
     }
     
-    public void testUnionBranchOrderBy() throws Exception {
+    @Test public void testUnionBranchOrderBy() throws Exception {
         Command command = QueryParser.getQueryParser().parseCommand("select pm1.g1.e1 from pm1.g1 union (select e2 from pm1.g2 order by e1)"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
         helpTest(command, "SELECT pm1.g1.e1 FROM pm1.g1 UNION (SELECT e2 FROM pm1.g2 ORDER BY e1)"); //$NON-NLS-1$
     }
     
-    public void testAliasedOrderBy() throws Exception {
+    @Test public void testAliasedOrderBy() throws Exception {
         Command command = QueryParser.getQueryParser().parseCommand("select pm1.g1.e1 as a from pm1.g1 order by a"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
         helpTest(command, "SELECT pm1.g1.e1 AS a FROM pm1.g1 ORDER BY a"); //$NON-NLS-1$
     }
     
-    public void testNumberOrderBy() throws Exception {
+    @Test public void testNumberOrderBy() throws Exception {
         Command command = QueryParser.getQueryParser().parseCommand("select pm1.g1.e1 as a from pm1.g1 order by 1"); //$NON-NLS-1$
-        QueryResolver.resolveCommand(command, FakeMetadataFactory.example1Cached());
+        QueryResolver.resolveCommand(command, RealMetadataFactory.example1Cached());
         helpTest(command, "SELECT pm1.g1.e1 AS a FROM pm1.g1 ORDER BY 1"); //$NON-NLS-1$
     }
+    
+    public Expression helpTestExpression(String sql, String expected) throws QueryParserException {
+    	Expression expr = QueryParser.getQueryParser().parseExpression(sql);
+        helpTest(expr, expected);
+        return expr;
+    }
+    
+    @Test public void testLikeRegex() throws Exception {
+    	helpTestExpression("x like_regex 'b'", "x LIKE_REGEX 'b'");
+    }
+    
+    @Test public void testSimilar() throws Exception {
+    	helpTestExpression("x similar to 'b' escape 'c'", "x SIMILAR TO 'b' ESCAPE 'c'");
+    }
+    
+    @Test public void testTextTable() throws Exception {
+    	String sql = "SELECT * from texttable(file columns x string WIDTH 1 NO TRIM NO ROW DELIMITER) as x"; //$NON-NLS-1$
+        helpTest(QueryParser.getQueryParser().parseCommand(sql), "SELECT * FROM TEXTTABLE(file COLUMNS x string WIDTH 1 NO TRIM NO ROW DELIMITER) AS x");
+    }
 
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestStaticSymbolMappingVisitor.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestStaticSymbolMappingVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/sql/visitor/TestStaticSymbolMappingVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,6 +28,8 @@
 import java.util.List;
 import java.util.Map;
 
+import junit.framework.TestCase;
+
 import org.teiid.query.sql.LanguageObject;
 import org.teiid.query.sql.lang.BetweenCriteria;
 import org.teiid.query.sql.lang.CompareCriteria;
@@ -48,23 +50,17 @@
 import org.teiid.query.sql.proc.CriteriaSelector;
 import org.teiid.query.sql.proc.TranslateCriteria;
 import org.teiid.query.sql.symbol.AliasSymbol;
-import org.teiid.query.sql.symbol.AllInGroupSymbol;
-import org.teiid.query.sql.symbol.AllSymbol;
 import org.teiid.query.sql.symbol.Constant;
 import org.teiid.query.sql.symbol.ElementSymbol;
 import org.teiid.query.sql.symbol.Expression;
 import org.teiid.query.sql.symbol.ExpressionSymbol;
 import org.teiid.query.sql.symbol.Function;
 import org.teiid.query.sql.symbol.GroupSymbol;
+import org.teiid.query.sql.symbol.MultipleElementSymbol;
 import org.teiid.query.sql.symbol.Symbol;
-import org.teiid.query.sql.visitor.ElementCollectorVisitor;
-import org.teiid.query.sql.visitor.GroupCollectorVisitor;
-import org.teiid.query.sql.visitor.StaticSymbolMappingVisitor;
 
-import junit.framework.TestCase;
 
 
-
 public class TestStaticSymbolMappingVisitor extends TestCase {
 
 	// ################################## FRAMEWORK ################################
@@ -209,14 +205,14 @@
 
 	public void testVisitSelect2() { 
 		Select select = new Select();
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		select.addSymbol(all);
 		helpTest(select, getSymbolMap());   
 	}
 
 	public void testVisitSelect3() { 
 		Select select = new Select();
-		AllSymbol all = new AllSymbol();
+		MultipleElementSymbol all = new MultipleElementSymbol();
 		all.addElementSymbol(exampleElement(true, 0));
 		select.addSymbol(all);
 		helpTest(select, getSymbolMap());   
@@ -226,7 +222,7 @@
 		Select select = new Select();
 		select.addSymbol( new ExpressionSymbol(
 			"x", new Function("length", new Expression[] {exampleElement(true, 0)})) );    //$NON-NLS-1$ //$NON-NLS-2$
-		select.addSymbol( new AllInGroupSymbol("abc.*") ); //$NON-NLS-1$
+		select.addSymbol( new MultipleElementSymbol("abc.*") ); //$NON-NLS-1$
 		select.addSymbol( exampleElement(true, 1) );
 		helpTest(select,getSymbolMap());
 	}
@@ -266,7 +262,7 @@
 	}
 	
  	public void testVisitAllSymbol() {
- 		AllSymbol as = new AllSymbol();
+ 		MultipleElementSymbol as = new MultipleElementSymbol();
  		ArrayList elements = new ArrayList();
  		elements.add(exampleElement(true, 0));    
  		elements.add(exampleElement(true, 1));     		
@@ -274,8 +270,8 @@
  		helpTest(as, getSymbolMap());
  	}
  	
- 	public void testVisitAllInGroupSymbol() {
- 		AllInGroupSymbol aigs = new AllInGroupSymbol("OLDG0.*"); //$NON-NLS-1$
+ 	public void testVisitMultipleElementSymbol() {
+ 		MultipleElementSymbol aigs = new MultipleElementSymbol("OLDG0.*"); //$NON-NLS-1$
  		ArrayList elements = new ArrayList();
  		elements.add(exampleElement(true, 0));    
  		elements.add(exampleElement(true, 1));     		
@@ -299,9 +295,9 @@
 		helpTest(f2, getSymbolMap()); 	    
  	} 	
 
- 	public void testMapAllInGroupSymbolName() {
- 		AllInGroupSymbol aigs = new AllInGroupSymbol("OLDG0.*"); //$NON-NLS-1$
- 		ArrayList elements = new ArrayList();
+ 	public void testMapMultipleElementSymbolName() {
+ 		MultipleElementSymbol aigs = new MultipleElementSymbol("OLDG0"); //$NON-NLS-1$
+ 		ArrayList<ElementSymbol> elements = new ArrayList<ElementSymbol>();
  		elements.add(exampleElement(true, 0));    
  		elements.add(exampleElement(true, 1));     		
  		aigs.setElementSymbols(elements);
@@ -311,7 +307,7 @@
         DeepPreOrderNavigator.doVisit(aigs, visitor);
 
 		// Check name of all in group symbol
-		assertEquals("AllInGroupSymbol name did not get mapped correctly: ", "NEWG0.*", aigs.getName()); //$NON-NLS-1$ //$NON-NLS-2$
+		assertEquals("MultipleElementSymbol name did not get mapped correctly: ", "NEWG0.*", aigs.toString()); //$NON-NLS-1$ //$NON-NLS-2$
  	}
     
     public void testExecName() {

Deleted: branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFacade.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,774 +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 org.teiid.query.unittest;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.core.util.ArgCheck;
-import org.teiid.core.util.Assertion;
-import org.teiid.query.function.FunctionLibrary;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingBaseNode;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingNode;
-import org.teiid.query.mapping.xml.MappingVisitor;
-import org.teiid.query.mapping.xml.Navigator;
-import org.teiid.query.metadata.BasicQueryMetadata;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.StoredProcedureInfo;
-import org.teiid.query.metadata.SupportConstants;
-import org.teiid.query.sql.lang.SPParameter;
-import org.teiid.query.sql.symbol.ElementSymbol;
-import org.teiid.query.sql.symbol.SingleElementSymbol;
-
-
-public class FakeMetadataFacade extends BasicQueryMetadata {
-
-	private FakeMetadataStore store;
-	private FunctionLibrary functionLibrary;
-
-	public FakeMetadataFacade(FakeMetadataStore store) {
-		this.store = store;
-		this.functionLibrary = FakeMetadataFactory.SFM.getSystemFunctionLibrary();
-	}
-	
-	public FakeMetadataFacade(FakeMetadataStore store, FunctionLibrary funcLibrary) {
-		this.store = store;
-		this.functionLibrary = funcLibrary;
-	}
-
-	public FakeMetadataStore getStore() {
-		return this.store;
-	}
-
-    public Object getElementID(String elementName)
-        throws TeiidComponentException, QueryMetadataException {
-
-        Assertion.isNotNull(elementName);
-
-		Object obj = store.findObject(elementName, FakeMetadataObject.ELEMENT);
-		if(obj == null) {
-			throw new QueryMetadataException("Element '" + elementName + "' not found."); //$NON-NLS-1$ //$NON-NLS-2$
-		}
-		return obj;
-	}
-
-    public Object getGroupID(String groupName)
-        throws TeiidComponentException, QueryMetadataException {
-
-        Assertion.isNotNull(groupName);
-
-        Object result = store.findObject(groupName, FakeMetadataObject.GROUP);
-        if (result == null){
-            throw new QueryMetadataException("Group '" + groupName + "' not found."); //$NON-NLS-1$ //$NON-NLS-2$
-        }
-        return result;
-	}
-
-    public Collection getGroupsForPartialName(String partialGroupName)
-        throws TeiidComponentException, QueryMetadataException {
-
-		if(partialGroupName == null) {
-			throw new QueryMetadataException("Group name cannot be null"); //$NON-NLS-1$
-		}
-        
-        String qualifiedPartialPart = "."+partialGroupName; //$NON-NLS-1$
-        
-		// get all groupNames present in metadata
-        Collection groupNames = store.findObjects(FakeMetadataObject.GROUP, "dummy", null); //$NON-NLS-1$
-
-		// these are the correct group names whose valid partially qualified
-		// part this partial name is part of
-        Collection correctGroups = new ArrayList();
-        Iterator groupIter = groupNames.iterator();
-        while(groupIter.hasNext()) {
-        	String groupName = ((FakeMetadataObject) groupIter.next()).getName();
-        	if(groupName.toLowerCase().endsWith(qualifiedPartialPart.toLowerCase())) {
-        		correctGroups.add(groupName);
-        	}
-        }
-
-        return correctGroups;
-    }
-
-    public Object getModelID(Object groupOrElementID)
-        throws TeiidComponentException, QueryMetadataException {
-
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupOrElementID);
-    	FakeMetadataObject obj = (FakeMetadataObject) groupOrElementID;
-		return obj.getProperty(FakeMetadataObject.Props.MODEL);
-	}
-
-    public String getInsertPlan(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-		FakeMetadataObject obj = (FakeMetadataObject) groupID;
-		return (String) obj.getProperty(FakeMetadataObject.Props.INSERT_PROCEDURE);
-    }
-
-    public String getUpdatePlan(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-		FakeMetadataObject obj = (FakeMetadataObject) groupID;
-		return (String) obj.getProperty(FakeMetadataObject.Props.UPDATE_PROCEDURE);
-    }
-
-    public String getDeletePlan(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-		FakeMetadataObject obj = (FakeMetadataObject) groupID;
-		return (String) obj.getProperty(FakeMetadataObject.Props.DELETE_PROCEDURE);
-    }
-
-    public String getFullName(Object metadataID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, metadataID);
-		return ((FakeMetadataObject)metadataID).getName();
-	}
-    
-    @Override
-    public String getName(Object metadataID) throws TeiidComponentException,
-    		QueryMetadataException {
-    	String name = getFullName(metadataID);
-    	Object groupID = getGroupIDForElementID(metadataID);
-    	boolean isXml = false;
-    	String groupFullName = null;
-    	if (groupID != null) {
-        	isXml = isXMLGroup(groupID);
-        	groupFullName = getFullName(groupID);
-    	}
-    	
-    	if (isXml) {
-    		name = name.substring(groupFullName.length() + 1);
-    	} else {
-    		//the logic about should work in either case, 
-    		//but there is a lot of metadata to correct
-    		name = SingleElementSymbol.getShortName(name);
-    	}
-    	return name;
-    }
-
-    public List getElementIDsInGroupID(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-		List ids = store.findObjects(FakeMetadataObject.ELEMENT, FakeMetadataObject.Props.GROUP, groupID);
-		Collections.sort(ids);
-		return ids;
-	}
-
-    public Object getGroupIDForElementID(Object elementID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-		FakeMetadataObject element = (FakeMetadataObject) elementID;
-		return element.getProperty(FakeMetadataObject.Props.GROUP);
-	}
-
-	public String getElementType(Object elementID)
-		throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element = (FakeMetadataObject) elementID;
-		return (String) element.getProperty(FakeMetadataObject.Props.TYPE);
-	}
-
-	public Object getDefaultValue(Object elementID)
-		throws TeiidComponentException, QueryMetadataException {
-		ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-		return ((FakeMetadataObject)elementID).getDefaultValue();
-	}
-
-    public boolean isVirtualGroup(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-    	FakeMetadataObject group = (FakeMetadataObject) groupID;
-		return Boolean.TRUE.equals(group.getProperty(FakeMetadataObject.Props.IS_VIRTUAL));
-	}
-
-    public boolean isVirtualModel(Object modelID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, modelID);
-    	FakeMetadataObject model = (FakeMetadataObject) modelID;
-        return ((Boolean)model.getProperty(FakeMetadataObject.Props.IS_VIRTUAL)).booleanValue();
-
-    }
-
-    public QueryNode getVirtualPlan(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-    	FakeMetadataObject group = (FakeMetadataObject) groupID;
-		QueryNode queryNode = (QueryNode) group.getProperty(FakeMetadataObject.Props.PLAN);
-		if (queryNode.getQuery() == null) {
-		    throw new QueryMetadataException("no query");//$NON-NLS-1$
-		}
-		return queryNode;
-	}
-
-	public boolean modelSupports(Object modelID, int supportConstant)
-        throws TeiidComponentException, QueryMetadataException {
-		ArgCheck.isInstanceOf(FakeMetadataObject.class, modelID);
-		switch(supportConstant) {
-			default:
-				throw new QueryMetadataException("Unknown model support constant: " + supportConstant); //$NON-NLS-1$
-		}
-	}
-
-    public boolean groupSupports(Object groupID, int groupConstant)
-        throws TeiidComponentException,QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-    	FakeMetadataObject group = (FakeMetadataObject) groupID;
-		Boolean supports = null;
-		switch(groupConstant) {
-			case SupportConstants.Group.UPDATE:
-				supports = (Boolean) group.getProperty(FakeMetadataObject.Props.UPDATE);
-				break;
-			default:
-				throw new QueryMetadataException("Unknown group support constant: " + groupConstant); //$NON-NLS-1$
-		}
-		return supports.booleanValue();
-	}
-
-    public boolean elementSupports(Object elementID, int elementConstant)
-        throws TeiidComponentException,QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-    	FakeMetadataObject element = (FakeMetadataObject) elementID;
-		Boolean supports = null;
-		switch(elementConstant) {
-			case SupportConstants.Element.NULL:
-				supports = (Boolean) element.getProperty(FakeMetadataObject.Props.NULL);
-				break;
-            case SupportConstants.Element.NULL_UNKNOWN:
-                supports = Boolean.FALSE;
-                break;
-			case SupportConstants.Element.SEARCHABLE_COMPARE:
-				supports = (Boolean) element.getProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE);
-				break;
-			case SupportConstants.Element.SEARCHABLE_LIKE:
-				supports = (Boolean) element.getProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE);
-				break;
-			case SupportConstants.Element.SELECT:
-				supports = (Boolean) element.getProperty(FakeMetadataObject.Props.SELECT);
-				break;
-			case SupportConstants.Element.UPDATE:
-				supports = (Boolean) element.getProperty(FakeMetadataObject.Props.UPDATE);
-				break;
-			case SupportConstants.Element.DEFAULT_VALUE:
-                Object defaultValue = element.getProperty(FakeMetadataObject.Props.DEFAULT_VALUE);
-                if(defaultValue == null) {
-                    supports = Boolean.FALSE;
-                } else if(defaultValue instanceof Boolean) {
-                    supports = (Boolean) defaultValue;
-                } else {
-                    supports = Boolean.TRUE;
-                }
-				break;
-			case SupportConstants.Element.AUTO_INCREMENT:
-				supports = (Boolean) element.getProperty(FakeMetadataObject.Props.AUTO_INCREMENT);
-				break;
-            case SupportConstants.Element.CASE_SENSITIVE:
-                supports = (Boolean) element.getProperty(FakeMetadataObject.Props.CASE_SENSITIVE);
-                break;
-            case SupportConstants.Element.SIGNED:
-                supports = (Boolean) element.getProperty(FakeMetadataObject.Props.SIGNED);
-                break;
-			default:
-				throw new QueryMetadataException("Unknown element support constant: " + elementConstant); //$NON-NLS-1$
-		}
-        if(supports != null) {
-    		return supports.booleanValue();
-        }
-        return false;
-	}
-
-    public int getMaxSetSize(Object modelID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, modelID);
-    	FakeMetadataObject model = (FakeMetadataObject) modelID;
-        Integer maxSetSize = (Integer) model.getProperty(FakeMetadataObject.Props.MAX_SET_SIZE);
-        if(maxSetSize == null) {
-            return 100;
-        }
-        return maxSetSize.intValue();
-    }
-
-    public StoredProcedureInfo getStoredProcedureInfoForProcedure(String fullyQualifiedProcedureName)
-        throws TeiidComponentException, QueryMetadataException {
-
-        Assertion.isNotNull(fullyQualifiedProcedureName);
-
-        FakeMetadataObject procedureID = store.findObject(fullyQualifiedProcedureName, FakeMetadataObject.PROCEDURE);
-        if(procedureID == null) {
-            throw new QueryMetadataException("Unknown stored procedure: " + fullyQualifiedProcedureName); //$NON-NLS-1$
-        }
-
-        StoredProcedureInfo procInfo = new StoredProcedureInfo();
-        procInfo.setProcedureID(procedureID);
-        procInfo.setModelID(procedureID.getProperty(FakeMetadataObject.Props.MODEL));
-        procInfo.setQueryPlan((QueryNode)procedureID.getProperty(FakeMetadataObject.Props.PLAN));
-        procInfo.setProcedureCallableName(fullyQualifiedProcedureName);
-        procInfo.setUpdateCount(((Integer)procedureID.getProperty(FakeMetadataObject.Props.UPDATE_COUNT, new Integer(-1))).intValue());
-
-        // Read params
-        List params = (List) procedureID.getProperty(FakeMetadataObject.Props.PARAMS);
-        List paramInfos = new ArrayList(params.size());
-        Iterator iter = params.iterator();
-        while(iter.hasNext()) {
-            FakeMetadataObject param = (FakeMetadataObject) iter.next();
-            
-            String name = param.getName();
-            if(name.indexOf(".") < 0) { //$NON-NLS-1$
-                name = procedureID.getName() + "." + name; //$NON-NLS-1$
-            }            
-            
-            int index = ( (Integer) param.getProperty(FakeMetadataObject.Props.INDEX) ).intValue();
-            int direction = ( (Integer) param.getProperty(FakeMetadataObject.Props.DIRECTION) ).intValue();
-            String dataTypeName = (String) param.getProperty(FakeMetadataObject.Props.TYPE);
-            Class dataTypeClass = DataTypeManager.getDataTypeClass(dataTypeName);
-            
-            SPParameter paramInfo = new SPParameter(index, direction, name);
-            paramInfo.setParameterType(direction);
-            paramInfo.setMetadataID(param);
-            if(direction == ParameterInfo.RESULT_SET) {
-                paramInfo.setClassType(java.sql.ResultSet.class);
-            } else {
-                paramInfo.setClassType(dataTypeClass);
-            }
-            
-            FakeMetadataObject resultSet = (FakeMetadataObject)param.getProperty(FakeMetadataObject.Props.RESULT_SET);
-            if(resultSet != null){
-            	Iterator iter2 = ((List)resultSet.getProperty(FakeMetadataObject.Props.COLUMNS)).iterator();
-            	while(iter2.hasNext()){
-                    ElementSymbol col = (ElementSymbol) iter2.next();
-            		paramInfo.addResultSetColumn(col.getName(), col.getType(), col.getMetadataID());
-            	}
-            }
-            paramInfos.add(paramInfo);
-        }
-
-        procInfo.setParameters(paramInfos);
-
-        return procInfo;
-	}
-
-    /**
-     * @see org.teiid.query.metadata.QueryMetadataInterface#getIndexesInGroup(java.lang.Object)
-     */
-    public Collection getIndexesInGroup(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-        return getTypeOfKeysInGroup(groupID, FakeMetadataObject.TYPE_INDEX);
-    }
-
-    public Collection getUniqueKeysInGroup(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	return getTypeOfKeysInGroup(groupID, FakeMetadataObject.TYPE_PRIMARY_KEY);
-    }
-
-    /**
-     * @see org.teiid.query.metadata.QueryMetadataInterface#getForeignKeysInGroup(java.lang.Object)
-     */
-    public Collection getForeignKeysInGroup(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	return getTypeOfKeysInGroup(groupID, FakeMetadataObject.TYPE_FOREIGN_KEY);
-    }
-
-    /**
-     * @see org.teiid.query.metadata.QueryMetadataInterface#getPrimaryKeyIDForForeignKeyID(java.lang.Object)
-     */
-    public Object getPrimaryKeyIDForForeignKeyID(Object foreignKeyID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, foreignKeyID);
-    	FakeMetadataObject keyObj = (FakeMetadataObject) foreignKeyID;
-        return keyObj.getProperty(FakeMetadataObject.Props.REFERENCED_KEY);
-    }
-
-    /**
-     * @see org.teiid.query.metadata.QueryMetadataInterface#getElementIDsInIndex(java.lang.Object)
-     */
-    public List getElementIDsInIndex(Object index)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, index);
-        FakeMetadataObject keyObj = (FakeMetadataObject) index;
-        return (List)keyObj.getProperty(FakeMetadataObject.Props.KEY_ELEMENTS);
-    }
-
-    public List getElementIDsInKey(Object keyID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, keyID);
-		FakeMetadataObject keyObj = (FakeMetadataObject) keyID;
-		return (List)keyObj.getProperty(FakeMetadataObject.Props.KEY_ELEMENTS);
-    }
-
-    /**
-     * @see org.teiid.query.metadata.QueryMetadataInterface#getAccessPatternsInGroup(Object)
-     */
-    public Collection getAccessPatternsInGroup(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	return getTypeOfKeysInGroup(groupID, FakeMetadataObject.TYPE_ACCESS_PATTERN);
-    }
-
-	//Used to get either keys or access patterns
-	private Collection getTypeOfKeysInGroup(Object groupID,
-                                        final Integer KEY_TYPE) {
-		ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-		FakeMetadataObject group = (FakeMetadataObject)groupID;
-
-		Collection keys = (Collection)group.getProperty(FakeMetadataObject.Props.KEYS);
-		if (keys == null){
-			return Collections.EMPTY_LIST;
-		}
-
-		Collection keysOfType = new ArrayList(keys.size());
-		Iterator keyIter = keys.iterator();
-		while (keyIter.hasNext()) {
-			FakeMetadataObject key = (FakeMetadataObject) keyIter.next();
-			if (KEY_TYPE.equals(key.getProperty(FakeMetadataObject.Props.KEY_TYPE))){
-				keysOfType.add(key);
-			}
-		}
-
-		return keysOfType;
-	}
-
-    /**
-     * @see org.teiid.query.metadata.QueryMetadataInterface#getElementIDsInAccessPattern(Object)
-     */
-    public List getElementIDsInAccessPattern(Object accessPattern)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, accessPattern);
-    	FakeMetadataObject accessPatternObj = (FakeMetadataObject) accessPattern;
-        return (List)accessPatternObj.getProperty(FakeMetadataObject.Props.KEY_ELEMENTS);
-    }
-
-    public MappingNode getMappingNode(Object groupID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-    	FakeMetadataObject group = (FakeMetadataObject) groupID;
-        MappingDocument doc = (MappingDocument)group.getProperty(FakeMetadataObject.Props.PLAN);
-        doc.setName(getFullName(groupID));
-        return doc;
-    }
-
-    public boolean isXMLGroup(Object groupID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-    	FakeMetadataObject group = (FakeMetadataObject) groupID;
-        Object plan = group.getProperty(FakeMetadataObject.Props.PLAN);
-        if(plan == null) {
-        	return false;
-        }
-      	return (plan instanceof MappingNode);
-    }
-
-    public String getVirtualDatabaseName() throws TeiidComponentException, QueryMetadataException {
-        return "myvdb"; //$NON-NLS-1$
-    }
-    
-    public boolean isTemporaryTable(Object groupID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-    	FakeMetadataObject group = (FakeMetadataObject) groupID;
-        Boolean isTemp = (Boolean)group.getProperty(FakeMetadataObject.Props.TEMP);
-        if(isTemp != null && isTemp.equals(Boolean.TRUE)) {
-            return true;
-        }
-        return false;
-    }    
-
-	public Collection getXMLTempGroups(Object groupID)
-        throws TeiidComponentException, QueryMetadataException{
-
-		ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-		MappingDocument mappingDoc = (MappingDocument)((FakeMetadataObject)groupID).getProperty(FakeMetadataObject.Props.PLAN);
-        List tempGroups = resolveGroups(getStagingTables(mappingDoc));
-        return tempGroups;
-    }
-    
-    List getStagingTables(MappingDocument doc) {
-        final List tables = new ArrayList();
-        
-        // visitor to extract all the explicit staging tables.
-        MappingVisitor visitor = new MappingVisitor() {
-            public void visit(MappingBaseNode baseNode) {
-                if (baseNode.getStagingTables() != null) {
-                    tables.addAll(baseNode.getStagingTables());
-                }
-            }
-        };
-        doc.acceptVisitor(new Navigator(true, visitor));
-        return tables;
-    }
-    
-
-    private List resolveGroups(List groupNames)
-        throws QueryMetadataException, TeiidComponentException {
-        
-        if(groupNames != null && !groupNames.isEmpty()) {
-            ArrayList tempGroups = new ArrayList();
-            for(int i = 0; i < groupNames.size(); i++) {           
-                tempGroups.add(this.getGroupID((String)groupNames.get(i)));
-            }
-            return tempGroups;
-        }
-        return Collections.EMPTY_LIST;
-    }
-
-	/**
-	 * @see org.teiid.query.metadata.QueryMetadataInterface#getCardinality(java.lang.Object)
-	 */
-	public int getCardinality(Object groupID)
-		throws TeiidComponentException, QueryMetadataException {
-		ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-		Integer cardinality = (Integer)((FakeMetadataObject)groupID).getProperty(FakeMetadataObject.Props.CARDINALITY);
-		if (cardinality != null){
-			return cardinality.intValue();
-		}
-		return QueryMetadataInterface.UNKNOWN_CARDINALITY;
-	}
-
-    public String getNameInSource(Object metadataID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, metadataID);
-        return (String)((FakeMetadataObject)metadataID).getProperty(FakeMetadataObject.Props.NAME_IN_SOURCE);
-    }
-
-    public Properties getExtensionProperties(Object metadataID)
-        throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, metadataID);
-        return ((FakeMetadataObject)metadataID).getExtensionProps();
-    }
-
-    public int getElementLength(Object elementID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element = (FakeMetadataObject) elementID;
-	    return Integer.parseInt((String) element.getProperty(FakeMetadataObject.Props.LENGTH));
-    }
-
-    /**
-     * Return position of element in group or result set.  Position returned is 1-based!
-     */
-    public int getPosition(Object elementID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-	    FakeMetadataObject element = (FakeMetadataObject) elementID;
-        return ((Integer) element.getProperty(FakeMetadataObject.Props.INDEX)).intValue() + 1;
-    }
-
-    public int getPrecision(Object elementID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element = (FakeMetadataObject) elementID;
-        String precision = (String) element.getProperty(FakeMetadataObject.Props.PRECISION);
-        if (precision == null) {
-            return 0;
-        }
-        return Integer.parseInt(precision);
-    }
-
-    public int getRadix(Object elementID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element = (FakeMetadataObject) elementID;
-        String radix = (String) element.getProperty(FakeMetadataObject.Props.RADIX);
-        if (radix == null) {
-            return 0;
-        }
-        return Integer.parseInt(radix);
-    }
-
-    public int getScale(Object elementID) throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element = (FakeMetadataObject) elementID;
-        String scale = (String) element.getProperty(FakeMetadataObject.Props.SCALE);
-        if (scale == null) {
-            return 0;
-        }
-        return Integer.parseInt(scale);
-    }
-
-    
-    public String getNativeType(Object elementID) throws TeiidComponentException,
-                                                 QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element =  (FakeMetadataObject) elementID;
-        String nativeType = (String) element.getProperty(FakeMetadataObject.Props.NATIVE_TYPE);
-        if(nativeType == null) {
-            return "";                 //$NON-NLS-1$
-        }
-        return nativeType;
-    }
-    
-    public boolean hasMaterialization(Object groupID) throws TeiidComponentException,
-                                                     QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-        FakeMetadataObject group = (FakeMetadataObject)groupID;
-        return group.getProperty(FakeMetadataObject.Props.MAT_GROUP) != null;
-    }
-
-    public Object getMaterialization(Object groupID) throws TeiidComponentException,
-                                                    QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-        FakeMetadataObject group =  (FakeMetadataObject) groupID;
-        return group.getProperty(FakeMetadataObject.Props.MAT_GROUP);
-    }
-    
-    public Object getMaterializationStage(Object groupID) throws TeiidComponentException,
-                                                         QueryMetadataException {
-        
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-        FakeMetadataObject group =  (FakeMetadataObject) groupID;
-        return group.getProperty(FakeMetadataObject.Props.MAT_STAGE);
-    }
-    
-    public Object getMaximumValue(Object elementID) throws TeiidComponentException,
-                                                   QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element =  (FakeMetadataObject) elementID;
-        return element.getProperty(FakeMetadataObject.Props.MAX_VALUE);
-    }
-    
-    public Object getMinimumValue(Object elementID) throws TeiidComponentException,
-                                                   QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element =  (FakeMetadataObject) elementID;
-        return element.getProperty(FakeMetadataObject.Props.MIN_VALUE);
-    }
-
-    public int getDistinctValues(Object elementID) throws TeiidComponentException,
-                                                   QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element = (FakeMetadataObject)elementID;
-        Integer val = (Integer) element.getProperty(FakeMetadataObject.Props.DISTINCT_VALUES);
-        if(val != null) {
-            return val.intValue();
-        }
-        return -1;
-    }
-
-    public int getNullValues(Object elementID) throws TeiidComponentException,
-                                                   QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element = (FakeMetadataObject)elementID;
-        Integer val = (Integer) element.getProperty(FakeMetadataObject.Props.NULL_VALUES);
-        if(val != null) {
-            return val.intValue();
-        }
-        return -1;
-    }
-
-    public List getXMLSchemas(Object groupID) throws TeiidComponentException,
-                                             QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, groupID);
-        FakeMetadataObject group =  (FakeMetadataObject) groupID;
-        return (List) group.getProperty(FakeMetadataObject.Props.XML_SCHEMAS);
-    }
-    
-	public boolean isProcedure(Object elementID) {
-		ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element =  (FakeMetadataObject) elementID;
-        return FakeMetadataObject.PROCEDURE.equals(element.getType());
-	}
-    
-    public byte[] getBinaryVDBResource(String resourcePath) throws TeiidComponentException, QueryMetadataException {
-        return "ResourceContents".getBytes(); //$NON-NLS-1$
-    }
-
-    public String getCharacterVDBResource(String resourcePath) throws TeiidComponentException, QueryMetadataException {
-        return "ResourceContents"; //$NON-NLS-1$
-    }
-
-    public String[] getVDBResourcePaths() throws TeiidComponentException, QueryMetadataException {
-        return new String[] {"my/resource/path"}; //$NON-NLS-1$
-    }
-    
-    /** 
-     * @see org.teiid.query.metadata.BasicQueryMetadata#getModeledType(java.lang.Object)
-     * @since 5.0
-     */
-    public String getModeledType(Object elementID) throws TeiidComponentException,
-                                                  QueryMetadataException {
-        
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element =  (FakeMetadataObject) elementID;
-        return (String) element.getProperty(FakeMetadataObject.Props.MODELED_TYPE);
-    }
-    
-    /** 
-     * @see org.teiid.query.metadata.BasicQueryMetadata#getModeledBaseType(java.lang.Object)
-     * @since 5.0
-     */
-    public String getModeledBaseType(Object elementID) throws TeiidComponentException,
-                                                      QueryMetadataException {
-        
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-    	FakeMetadataObject element =  (FakeMetadataObject) elementID;
-        return (String) element.getProperty(FakeMetadataObject.Props.MODELED_BASE_TYPE);
-    }
-    
-    /** 
-     * @see org.teiid.query.metadata.BasicQueryMetadata#getModeledPrimitiveType(java.lang.Object)
-     * @since 5.0
-     */
-    public String getModeledPrimitiveType(Object elementID) throws TeiidComponentException,
-                                                           QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, elementID);
-        FakeMetadataObject element =  (FakeMetadataObject) elementID;
-        return (String) element.getProperty(FakeMetadataObject.Props.MODELED_PRIMITIVE_TYPE);
-    }
-    
-    @Override
-    public Object addToMetadataCache(Object metadataID, String key, Object value)
-    		throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, metadataID);
-    	FakeMetadataObject object = (FakeMetadataObject) metadataID;
-    	synchronized (object) {
-        	Object result = object.getProperty(key);
-        	object.putProperty(key, value);
-        	return result;
-		}
-    }
-    
-    @Override
-    public Object getFromMetadataCache(Object metadataID, String key)
-    		throws TeiidComponentException, QueryMetadataException {
-    	ArgCheck.isInstanceOf(FakeMetadataObject.class, metadataID);
-    	FakeMetadataObject object =  (FakeMetadataObject) metadataID;
-    	synchronized (object) {
-        	return object.getProperty(key);
-		}
-    }
-    
-    @Override
-    public FunctionLibrary getFunctionLibrary() {
-    	return this.functionLibrary;
-    }
-    
-    @Override
-    public Object getPrimaryKey(Object metadataID) {
-    	Collection keys = getTypeOfKeysInGroup(metadataID, FakeMetadataObject.TYPE_PRIMARY_KEY);
-    	if (!keys.isEmpty()) {
-    		return keys.iterator().next();
-    	}
-    	return null;
-    }
-}

Deleted: branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3039 +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 org.teiid.query.unittest;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-
-import org.teiid.adminapi.Model;
-import org.teiid.adminapi.impl.ModelMetaData;
-import org.teiid.adminapi.impl.SessionMetadata;
-import org.teiid.adminapi.impl.VDBMetaData;
-import org.teiid.api.exception.query.QueryMetadataException;
-import org.teiid.client.metadata.ParameterInfo;
-import org.teiid.core.TeiidComponentException;
-import org.teiid.core.types.DataTypeManager;
-import org.teiid.dqp.internal.process.DQPWorkContext;
-import org.teiid.metadata.Table;
-import org.teiid.query.function.SystemFunctionManager;
-import org.teiid.query.mapping.relational.QueryNode;
-import org.teiid.query.mapping.xml.MappingAttribute;
-import org.teiid.query.mapping.xml.MappingDocument;
-import org.teiid.query.mapping.xml.MappingElement;
-import org.teiid.query.mapping.xml.MappingSequenceNode;
-import org.teiid.query.metadata.QueryMetadataInterface;
-import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.sql.symbol.ElementSymbol;
-
- at SuppressWarnings("nls")
-public class FakeMetadataFactory {
-
-	public static SystemFunctionManager SFM = new SystemFunctionManager();
-    private static FakeMetadataFacade CACHED_EXAMPLE1 = example1();
-    private static FakeMetadataFacade CACHED_AGGREGATES = exampleAggregates();
-        
-	private FakeMetadataFactory() { }
-	
-    public static FakeMetadataFacade example1Cached() {
-        return CACHED_EXAMPLE1;
-    }
-
-    public static TransformationMetadata exampleBQTCached() {
-        return RealMetadataFactory.exampleBQTCached();
-    }
-    
-    public static void setCardinality(String group, int cardinality, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
-    	if (metadata instanceof TransformationMetadata) {
-    		Table t = (Table)metadata.getGroupID(group);
-    		t.setCardinality(cardinality);
-    	} else if (metadata instanceof FakeMetadataFacade) {
-    		FakeMetadataObject fmo = (FakeMetadataObject)metadata.getGroupID(group);
-    		fmo.putProperty(FakeMetadataObject.Props.CARDINALITY, cardinality);
-    	} else {
-    		throw new RuntimeException("unknown metadata"); //$NON-NLS-1$
-    	}
-    	
-    }
-    
-    public static FakeMetadataFacade exampleAggregatesCached() {
-        return CACHED_AGGREGATES;
-    }       
-    
-    public static DQPWorkContext buildWorkContext(TransformationMetadata metadata) {
-    	return buildWorkContext(metadata, metadata.getVdbMetaData());
-    }
-    
-	public static DQPWorkContext buildWorkContext(QueryMetadataInterface metadata, VDBMetaData vdb) {
-		DQPWorkContext workContext = new DQPWorkContext();
-		SessionMetadata session = new SessionMetadata();
-		workContext.setSession(session);
-		session.setVDBName(vdb.getName()); 
-		session.setVDBVersion(vdb.getVersion()); 
-		session.setSessionId(String.valueOf(1));
-		session.setUserName("foo"); //$NON-NLS-1$
-		session.setVdb(vdb);
-        workContext.getVDB().addAttchment(QueryMetadataInterface.class, metadata);
-        if (metadata instanceof TransformationMetadata) {
-        	workContext.getVDB().addAttchment(TransformationMetadata.class, (TransformationMetadata)metadata);
-        }
-        DQPWorkContext.setWorkContext(workContext);
-		return workContext;
-	}
-    
-    public static FakeMetadataFacade exampleBitwise() { 
-        FakeMetadataObject phys = createPhysicalModel("phys"); //$NON-NLS-1$
-        FakeMetadataObject t = createPhysicalGroup("phys.t", phys); //$NON-NLS-1$
-        List tElem = createElements(t, 
-                                    new String[] { "ID", "Name", "source_bits" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-                                    new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-
-        FakeMetadataObject virt = createVirtualModel("virt"); //$NON-NLS-1$
-        FakeMetadataObject rs = createResultSet("rs", virt, new String[] { "ID", "Name", "source_bits" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        FakeMetadataObject paramRS = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs);  //$NON-NLS-1$
-        QueryNode qn = new QueryNode("CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
-		  + "BEGIN " //$NON-NLS-1$
-		  + "        DECLARE integer VARIABLES.BITS;" //$NON-NLS-1$
-		  + "        create local temporary table #temp (id integer, name string, bits integer);" //$NON-NLS-1$
-		  + "        LOOP ON (SELECT DISTINCT phys.t.ID, phys.t.Name FROM phys.t) AS idCursor" //$NON-NLS-1$
-		  + "        BEGIN" //$NON-NLS-1$
-		  + "                VARIABLES.BITS = 0;" //$NON-NLS-1$
-		  + "                LOOP ON (SELECT phys.t.source_bits FROM phys.t WHERE phys.t.ID = idCursor.id) AS bitsCursor" //$NON-NLS-1$
-		  + "                BEGIN" //$NON-NLS-1$
-		  + "                        VARIABLES.BITS = bitor(VARIABLES.BITS, bitsCursor.source_bits);" //$NON-NLS-1$
-		  + "                END" //$NON-NLS-1$
-		  + "                SELECT idCursor.id, idCursor.name, VARIABLES.BITS INTO #temp;" //$NON-NLS-1$
-		  + "        END" //$NON-NLS-1$
-		  + "        SELECT ID, Name, #temp.BITS AS source_bits FROM #temp;" //$NON-NLS-1$                                          
-		  + "END"); //$NON-NLS-1$ 
-        FakeMetadataObject proc = createVirtualProcedure("virt.agg", virt, Arrays.asList(new FakeMetadataObject[] { paramRS }), qn); //$NON-NLS-1$
-
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(phys);
-        store.addObject(t);
-        store.addObjects(tElem);
-        store.addObject(virt);
-        store.addObject(proc);
-        
-        return new FakeMetadataFacade(store);
-        
-    }
-    
-    public static VDBMetaData example1VDB() {
-    	VDBMetaData vdb = new VDBMetaData();
-    	vdb.setName("example1");
-    	vdb.setVersion(1);
-    	vdb.addModel(createModel("pm1", true));
-    	vdb.addModel(createModel("pm2", true));
-    	vdb.addModel(createModel("pm3", true));
-    	vdb.addModel(createModel("pm4", true));
-    	vdb.addModel(createModel("pm5", true));
-    	vdb.addModel(createModel("pm6", true));
-    	vdb.addModel(createModel("vm1", false));
-    	vdb.addModel(createModel("vm2", false));
-    	vdb.addModel(createModel("tm1", false));
-    	
-    	return vdb;
-    }
-    
-    public static ModelMetaData createModel(String name, boolean source) {
-    	ModelMetaData model = new ModelMetaData();
-    	model.setName(name);
-    	if (source) {
-    		model.setModelType(Model.Type.PHYSICAL);
-    	}
-    	else {
-    		model.setModelType(Model.Type.VIRTUAL);
-    	}
-    	model.setVisible(true);
-    	model.setSupportsMultiSourceBindings(false);
-    	model.addSourceMapping(name, name, null);
-    	
-    	return model;
-    }
-    
-	public static FakeMetadataFacade example1() { 
-		// Create models
-		FakeMetadataObject pm1 = createPhysicalModel("pm1"); //$NON-NLS-1$
-		FakeMetadataObject pm2 = createPhysicalModel("pm2"); //$NON-NLS-1$
-        FakeMetadataObject pm3 = createPhysicalModel("pm3"); //allows push of SELECT DISTINCT //$NON-NLS-1$
-        FakeMetadataObject pm4 = createPhysicalModel("pm4"); //all groups w/ access pattern(s) //$NON-NLS-1$
-		FakeMetadataObject pm5 = createPhysicalModel("pm5"); //all groups w/ access pattern(s); model supports join //$NON-NLS-1$
-        FakeMetadataObject pm6 = createPhysicalModel("pm6"); //model does not support where all //$NON-NLS-1$
-		FakeMetadataObject vm1 = createVirtualModel("vm1");	 //$NON-NLS-1$
-		FakeMetadataObject vm2 = createVirtualModel("vm2");	 //$NON-NLS-1$
-        FakeMetadataObject tm1 = createVirtualModel("tm1"); //$NON-NLS-1$
-
-		// Create physical groups
-		FakeMetadataObject pm1g1 = createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g2 = createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g3 = createPhysicalGroup("pm1.g3", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g4 = createPhysicalGroup("pm1.g4", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g5 = createPhysicalGroup("pm1.g5", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g6 = createPhysicalGroup("pm1.g6", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1table = createPhysicalGroup("pm1.table1", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm2g1 = createPhysicalGroup("pm2.g1", pm2); //$NON-NLS-1$
-		FakeMetadataObject pm2g2 = createPhysicalGroup("pm2.g2", pm2); //$NON-NLS-1$
-		FakeMetadataObject pm2g3 = createPhysicalGroup("pm2.g3", pm2); //$NON-NLS-1$
-        FakeMetadataObject pm3g1 = createPhysicalGroup("pm3.g1", pm3); //$NON-NLS-1$
-        FakeMetadataObject pm3g2 = createPhysicalGroup("pm3.g2", pm3); //$NON-NLS-1$
-        FakeMetadataObject pm4g1 = createPhysicalGroup("pm4.g1", pm4); //$NON-NLS-1$
-        FakeMetadataObject pm4g2 = createPhysicalGroup("pm4.g2", pm4); //$NON-NLS-1$
-		FakeMetadataObject pm5g1 = createPhysicalGroup("pm5.g1", pm5); //$NON-NLS-1$
-		FakeMetadataObject pm5g2 = createPhysicalGroup("pm5.g2", pm5); //$NON-NLS-1$
-		FakeMetadataObject pm5g3 = createPhysicalGroup("pm5.g3", pm5); //$NON-NLS-1$
-        FakeMetadataObject pm6g1 = createPhysicalGroup("pm6.g1", pm6); //$NON-NLS-1$
-        
-				
-		// Create physical elements
-		List pm1g1e = createElements(pm1g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g2e = createElements(pm1g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g3e = createElements(pm1g3, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g4e = createElements(pm1g4,
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        ((FakeMetadataObject)pm1g4e.get(1)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        ((FakeMetadataObject)pm1g4e.get(3)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        List pm1g5e = createElements(pm1g5,
-            new String[] { "e1" }, //$NON-NLS-1$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        ((FakeMetadataObject)pm1g5e.get(0)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        List pm1g6e = createElements(pm1g6,
-            new String[] { "in", "in3" }, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List pm1tablee = createElements(pm1table, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g1e = createElements(pm2g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g2e = createElements(pm2g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g3e = createElements(pm2g3, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm3g1e = createElements(pm3g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
-		List pm3g2e = createElements(pm3g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
-        List pm4g1e = createElements(pm4g1, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm4g2e = createElements(pm4g2, 
-            new String[] { "e1", "e2", "e3", "e4", "e5", "e6" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-		List pm5g1e = createElements(pm5g1,
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm5g2e = createElements(pm5g2,
-			new String[] { "e1", "e2", "e3", "e4", "e5", "e6" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-		List pm5g3e = createElements(pm5g3,
-	        new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.SHORT });
-        List pm6g1e = createElements(pm6g1,
-            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        
-
-        // Create access patterns - pm4
-        List elements = new ArrayList(1);
-        elements.add(pm4g1e.iterator().next());       
-        FakeMetadataObject pm4g1ap1 = createAccessPattern("pm4.g1.ap1", pm4g1, elements); //e1 //$NON-NLS-1$
-        elements = new ArrayList(2);
-        Iterator iter = pm4g2e.iterator();
-        elements.add(iter.next());       
-        elements.add(iter.next());       
-        FakeMetadataObject pm4g2ap1 = createAccessPattern("pm4.g2.ap1", pm4g2, elements); //e1,e2 //$NON-NLS-1$
-		elements = new ArrayList(1);
-		elements.add(pm4g2e.get(4)); //"e5"
-		FakeMetadataObject pm4g2ap2 =createAccessPattern("pm4.g2.ap2", pm4g2, elements); //e5 //$NON-NLS-1$
-		// Create access patterns - pm5
-		elements = new ArrayList(1);
-		elements.add(pm5g1e.iterator().next());
-		FakeMetadataObject pm5g1ap1 = createAccessPattern("pm5.g1.ap1", pm5g1, elements); //e1 //$NON-NLS-1$
-		elements = new ArrayList(2);
-		iter = pm5g2e.iterator();
-		elements.add(iter.next());
-		elements.add(iter.next());
-		FakeMetadataObject pm5g2ap1 = createAccessPattern("pm5.g2.ap1", pm5g2, elements); //e1,e2 //$NON-NLS-1$
-		elements = new ArrayList(1);
-		elements.add(pm5g2e.get(4)); //"e5"
-		FakeMetadataObject pm5g2ap2 = createAccessPattern("pm5.g2.ap2", pm5g2, elements); //e5 //$NON-NLS-1$
-
-        // Create temp groups
-        FakeMetadataObject tm1g1 = createTempGroup("tm1.g1", tm1, null); //$NON-NLS-1$
-
-        // Create temp elements - the element "node1" is purposely named to be ambiguous with a document node named "node1"
-        List tm1g1e = createElements(tm1g1, 
-            new String[] { "e1", "e2", "e3", "e4", "node1"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING });
-            
-        // Create temp groups
-        FakeMetadataObject tm1g2 = createTempGroup("tm1.g1", tm1, null); //$NON-NLS-1$
-
-        // Create temp elements
-        List tm1g2e = createElements(tm1g2, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });            
-
-		// Create virtual groups
-		QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g1 = createUpdatableVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
-
-		QueryNode vm2g1n1 = new QueryNode("SELECT pm1.g1.* FROM pm1.g1, pm1.g2 where pm1.g1.e2 = pm1.g2.e2"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm2g1 = FakeMetadataFactory.createUpdatableVirtualGroup("vm2.g1", vm2, vm2g1n1); //$NON-NLS-1$		
-		
-        QueryNode vm1g1n1_defect10711 = new QueryNode("SELECT * FROM vm1.g1 as X"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g1_defect10711 = createVirtualGroup("vm1.g1a", vm1, vm1g1n1_defect10711); //$NON-NLS-1$
-
-        QueryNode vm1g1n1_defect12081 = new QueryNode("SELECT e1, upper(e1) as e1Upper FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g1_defect12081 = createVirtualGroup("vm1.g1b", vm1, vm1g1n1_defect12081); //$NON-NLS-1$
-
-        QueryNode vm1g1n1c = new QueryNode("SELECT PARSETIMESTAMP(pm1.g1.e1, 'MMM dd yyyy hh:mm:ss') as e5, e2, e3, e4 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g1c = createVirtualGroup("vm1.g1c", vm1, vm1g1n1c); //$NON-NLS-1$
-        
-        QueryNode vm1g2an1 = new QueryNode("SELECT * FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g2a = createVirtualGroup("vm1.g2a", vm1, vm1g2an1); //$NON-NLS-1$
-
-		QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1=pm1.g2.e1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g2 = createVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
-
-        QueryNode vm1g4n1 = new QueryNode("SELECT e1 FROM pm1.g1 UNION ALL SELECT convert(e2, string) as x FROM pm1.g2 ORDER BY e1");         //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g4 = createVirtualGroup("vm1.g4", vm1, vm1g4n1); //$NON-NLS-1$
-	
-        QueryNode vm1g5n1 = new QueryNode("SELECT concat(e1, 'val'), e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g5 = createVirtualGroup("vm1.g5", vm1, vm1g5n1); //$NON-NLS-1$
-
-        QueryNode vm1g6n1 = new QueryNode("SELECT concat(e1, 'val') AS e, e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g6 = createVirtualGroup("vm1.g6", vm1, vm1g6n1); //$NON-NLS-1$
-
-        QueryNode vm1g7n1 = new QueryNode("SELECT concat(e1, e2) AS e, e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g7 = createVirtualGroup("vm1.g7", vm1, vm1g7n1); //$NON-NLS-1$
-
-        QueryNode vm1g8n1 = new QueryNode("SELECT concat(e1, 'val') AS e, e2 FROM pm1.g1 ORDER BY e"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g8 = createVirtualGroup("vm1.g8", vm1, vm1g8n1); //$NON-NLS-1$
-
-        QueryNode vm1g9n1 = new QueryNode("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1, pm4.g1 WHERE pm1.g1.e1 = pm4.g1.e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g9 = createVirtualGroup("vm1.g9", vm1, vm1g9n1); //$NON-NLS-1$
-
-        QueryNode vm1g10n1 = new QueryNode("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1, pm4.g2 WHERE pm1.g1.e1 = pm4.g2.e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g10 = createVirtualGroup("vm1.g10", vm1, vm1g10n1); //$NON-NLS-1$
-
-        QueryNode vm1g11n1 = new QueryNode("SELECT * FROM pm4.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g11 = createVirtualGroup("vm1.g11", vm1, vm1g11n1); //$NON-NLS-1$
-
-        QueryNode vm1g12n1 = new QueryNode("SELECT DISTINCT * FROM pm3.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g12 = createVirtualGroup("vm1.g12", vm1, vm1g12n1); //$NON-NLS-1$
-
-        QueryNode vm1g13n1 = new QueryNode("SELECT DISTINCT * FROM pm3.g1 ORDER BY e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g13 = createVirtualGroup("vm1.g13", vm1, vm1g13n1); //$NON-NLS-1$
-
-        QueryNode vm1g14n1 = new QueryNode("SELECT * FROM pm3.g1 ORDER BY e1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g14 = createVirtualGroup("vm1.g14", vm1, vm1g14n1); //$NON-NLS-1$
-   
-        QueryNode vm1g15n1 = new QueryNode("SELECT e1, concat(e1, convert(e2, string)) AS x FROM pm3.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g15 = createVirtualGroup("vm1.g15", vm1, vm1g15n1); //$NON-NLS-1$
-
-        QueryNode vm1g16n1 = new QueryNode("SELECT concat(e1, 'val') AS e, e2 FROM pm3.g1 ORDER BY e"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g16 = createVirtualGroup("vm1.g16", vm1, vm1g16n1); //$NON-NLS-1$
-
-        QueryNode vm1g17n1 = new QueryNode("SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1 UNION ALL SELECT pm3.g2.e1, pm3.g2.e2 FROM pm3.g2 ORDER BY e2");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g17 = createVirtualGroup("vm1.g17", vm1, vm1g17n1); //$NON-NLS-1$
-
-        QueryNode vm1g18n1 = new QueryNode("SELECT (e4 * 100.0) as x FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g18 = createVirtualGroup("vm1.g18", vm1, vm1g18n1); //$NON-NLS-1$
-
-        // Transformations with subqueries and correlated subqueries
-        QueryNode vm1g19n1 = new QueryNode("Select * from vm1.g4 where not (e1 in (select e1 FROM vm1.g1 WHERE vm1.g4.e1 = e1))");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g19 = createVirtualGroup("vm1.g19", vm1, vm1g19n1); //$NON-NLS-1$
-
-        QueryNode vm1g20n1 = new QueryNode("Select * from vm1.g1 where exists (select e1 FROM vm1.g2 WHERE vm1.g1.e1 = e1)");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g20 = createVirtualGroup("vm1.g20", vm1, vm1g20n1); //$NON-NLS-1$
-
-        QueryNode vm1g21n1 = new QueryNode("Select * from pm1.g1 where exists (select e1 FROM pm2.g1 WHERE pm1.g1.e1 = e1)");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g21 = createVirtualGroup("vm1.g21", vm1, vm1g21n1); //$NON-NLS-1$
-
-        QueryNode vm1g22n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM vm1.g21 WHERE vm1.g20.e4 = e4 and e4 = 7.0) as E5 from vm1.g20");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g22 = createVirtualGroup("vm1.g22", vm1, vm1g22n1); //$NON-NLS-1$
-
-        QueryNode vm1g23n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM vm1.g21 WHERE vm1.g20.e4 = 7.0 and e4 = 7.0) as E5 from vm1.g20");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g23 = createVirtualGroup("vm1.g23", vm1, vm1g23n1); //$NON-NLS-1$
-
-        QueryNode vm1g24n1 = new QueryNode("Select * from vm1.g20 where exists (select * FROM vm1.g21 WHERE vm1.g20.e4 = E4)");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g24 = createVirtualGroup("vm1.g24", vm1, vm1g24n1); //$NON-NLS-1$
-
-        QueryNode vm1g25n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM pm1.g2 WHERE e1 = 'b') as E5 from pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g25 = createVirtualGroup("vm1.g25", vm1, vm1g25n1); //$NON-NLS-1$
-
-        QueryNode vm1g26n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM pm1.g2 WHERE e4 = pm1.g1.e4 and e1 = 'b') as E5 from pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g26 = createVirtualGroup("vm1.g26", vm1, vm1g26n1); //$NON-NLS-1$
-
-        //defect 10976
-//        QueryNode vm1g27n1 = new QueryNode("vm1.g27", "SELECT DISTINCT x as a, lower(e1) as x FROM vm1.g28");         //$NON-NLS-1$ //$NON-NLS-2$
-        QueryNode vm1g27n1 = new QueryNode("SELECT upper(e1) as x, e1 FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g27 = createVirtualGroup("vm1.g27", vm1, vm1g27n1); //$NON-NLS-1$
-
-        QueryNode vm1g28n1 = new QueryNode("SELECT DISTINCT x as a, lower(e1) as x FROM vm1.g27");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g28 = createVirtualGroup("vm1.g28", vm1, vm1g28n1); //$NON-NLS-1$
-
-        QueryNode vm1g29n1 = new QueryNode("SELECT DISTINCT x, lower(e1) FROM vm1.g27");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g29 = createVirtualGroup("vm1.g29", vm1, vm1g29n1); //$NON-NLS-1$
-
-        QueryNode vm1g30n1 = new QueryNode("SELECT DISTINCT e1 as x, e1 as y FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g30 = createVirtualGroup("vm1.g30", vm1, vm1g30n1); //$NON-NLS-1$
-
-        QueryNode vm1g31n1 = new QueryNode("SELECT e1 as x, e1 as y FROM pm1.g1 ORDER BY x");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g31 = createVirtualGroup("vm1.g31", vm1, vm1g31n1); //$NON-NLS-1$
-
-        QueryNode vm1g32n1 = new QueryNode("SELECT DISTINCT e1 as x, e1 as y FROM pm1.g1 ORDER BY x");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g32 = createVirtualGroup("vm1.g32", vm1, vm1g32n1); //$NON-NLS-1$
-
-        QueryNode vm1g33n1 = new QueryNode("SELECT e2 FROM pm1.g1 WHERE 2 = e2");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g33 = createVirtualGroup("vm1.g33", vm1, vm1g33n1); //$NON-NLS-1$
-
-        QueryNode vm1g34n1 = new QueryNode("SELECT e1 as e1_, e2 as e2_ FROM pm1.g1 UNION ALL SELECT e1 as e1_, e2 as e2_ FROM pm2.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g34 = createVirtualGroup("vm1.g34", vm1, vm1g34n1); //$NON-NLS-1$
-
-        QueryNode vm1g36n1 = new QueryNode("SELECT pm1.g1.e1 as ve1, pm1.g2.e1 as ve2 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g36 = createVirtualGroup("vm1.g36", vm1, vm1g36n1); //$NON-NLS-1$
-
-        QueryNode vm1g37n1 = new QueryNode("SELECT * from pm4.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g37 = createVirtualGroup("vm1.g37", vm1, vm1g37n1); //$NON-NLS-1$
-        vm1g37.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.TRUE);
-
-        QueryNode vm1g38n1 = new QueryNode("SELECT a.e1, b.e2 from pm1.g1 as a, pm6.g1 as b where a.e1=b.e1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g38 = createVirtualGroup("vm1.g38", vm1, vm1g38n1); //$NON-NLS-1$
-        
-		// Create virtual groups
-		QueryNode vm1g39n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g39 = createUpdatableVirtualGroup("vm1.g39", vm1, vm1g39n1, "CREATE PROCEDURE BEGIN LOOP ON (SELECT pm1.g1.e2 FROM pm1.g1 where pm1.g1.e2=3) AS mycursor begin update pm1.g1 set pm1.g1.e1 = input.e1 where pm1.g1.e1 = input.e1; ROWS_UPDATED = ROWS_UPDATED + ROWCOUNT;\nupdate pm1.g1 set pm1.g1.e2 = input.e2 where pm1.g1.e2 = input.e2; END END"); //$NON-NLS-1$ //$NON-NLS-2$
-        
-		// Create virtual elements
-		List vm1g39e = createElements(vm1g39, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1g1e = createElements(vm1g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm2g1e = FakeMetadataFactory.createElements(vm2g1, 
-    		new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g1e_defect10711 = createElements(vm1g1_defect10711, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g1e_defect12081 = createElements(vm1g1_defect12081, 
-            new String[] { "e1", "e1Upper" }, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g1ce = createElements(vm1g1c, 
-            new String[] { "e5", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g2ae = createElements(vm1g2a, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1g2e = createElements(vm1g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1g4e = createElements(vm1g4,
-			new String[] { "e1" }, //$NON-NLS-1$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g5e = createElements(vm1g5,
-            new String[] { "expr", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g6e = createElements(vm1g6,
-            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g7e = createElements(vm1g7,
-            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g8e = createElements(vm1g8,
-            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g9e = createElements(vm1g9,
-            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g10e = createElements(vm1g10,
-            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g11e = createElements(vm1g11,
-            new String[] { "e1", "e2", "e3", "e4", "e5", "e6"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g12e = createElements(vm1g12,
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
-        List vm1g13e = createElements(vm1g13,
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
-        List vm1g14e = createElements(vm1g14,
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
-        List vm1g15e = createElements(vm1g15,
-            new String[] { "e1", "x" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g16e = createElements(vm1g16,
-            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE });
-        List vm1g17e = createElements(vm1g17,
-            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE });
-        List vm1g18e = createElements(vm1g18,
-            new String[] { "x" }, //$NON-NLS-1$
-            new String[] { DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g19e = createElements(vm1g19,
-            new String[] { "e1" }, //$NON-NLS-1$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g20e = createElements(vm1g20,
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g21e = createElements(vm1g21,
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g22e = createElements(vm1g22,
-            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g23e = createElements(vm1g23,
-            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g24e = createElements(vm1g24,
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g25e = createElements(vm1g25,
-            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g26e = createElements(vm1g26,
-            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g27e = createElements(vm1g27,
-            new String[] { "x", "e1"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g28e = createElements(vm1g28,
-            new String[] { "a", "x"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g29e = createElements(vm1g29,
-            new String[] { "x", "expr"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g30e = createElements(vm1g30,
-            new String[] { "x", "y"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g31e = createElements(vm1g31,
-            new String[] { "x", "y"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g32e = createElements(vm1g32,
-            new String[] { "x", "y"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g33e = createElements(vm1g33,
-            new String[] { "e2"}, //$NON-NLS-1$  
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g34e = createElements(vm1g34,
-            new String[] { "e1_", "e2_"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-        List vm1g36e = createElements(vm1g36,
-             new String[] { "ve1", "ve2" }, //$NON-NLS-1$ //$NON-NLS-2$
-             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        List vm1g37e = createElements(vm1g37,
-              new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
-              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List vm1g38e = createElements(vm1g38,
-              new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
-              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-
-        //Create access patterns on vm1.g37
-        elements = new ArrayList(1);
-        elements.add(vm1g37e.iterator().next());       
-        FakeMetadataObject vm1g37ap1 = createAccessPattern("vm1.g37.ap1", vm1g37, elements); //e1 //$NON-NLS-1$
-        
-        //XML STUFF =============================================
-        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("xmltest.doc1", vm1, exampleDoc1()); //$NON-NLS-1$
-        FakeMetadataObject doc2 = FakeMetadataFactory.createVirtualGroup("xmltest.doc2", vm1, exampleDoc2()); //$NON-NLS-1$
-        FakeMetadataObject doc3 = FakeMetadataFactory.createVirtualGroup("xmltest.doc3", vm1, exampleDoc3()); //$NON-NLS-1$
-        FakeMetadataObject doc4 = FakeMetadataFactory.createVirtualGroup("xmltest.doc4", vm1, exampleDoc4());         //$NON-NLS-1$
-        FakeMetadataObject doc5 = FakeMetadataFactory.createVirtualGroup("xmltest.doc5", vm1, exampleDoc5()); //$NON-NLS-1$
-        FakeMetadataObject doc6 = FakeMetadataFactory.createVirtualGroup("xmltest.doc6", vm1, exampleDoc6()); //$NON-NLS-1$
-
-        // Defect 11479 - test ambiguous doc short names
-        FakeMetadataObject docAmbiguous1 = FakeMetadataFactory.createVirtualGroup("xmltest2.docA", vm1, exampleDoc1()); //$NON-NLS-1$
-        FakeMetadataObject docAmbiguous2 = FakeMetadataFactory.createVirtualGroup("xmltest3.docA", vm1, exampleDoc2()); //$NON-NLS-1$
-
-		List docE1 = createElements(doc1, new String[] { "root", "root.node1", "root.node1.node2", "root.node1.node2.node3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-		List docE2 = createElements(doc2, new String[] { "root", "root.node1", "root.node1.node3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-		List docE3 = createElements(doc3, new String[] { "root", "root.node1.node2", "root.node2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-		List docE4 = createElements(doc4, new String[] { "root", "root. at node6", "root.node1", "root.node1. at node2", "root.node3", "root.node3. at node4", "root.node3.node4", "root.node3.root.node6" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-		Collection tempGroups = new HashSet();
-		tempGroups.add(tm1g1);
-		doc4.putProperty("TEMP_GROUPS", tempGroups); //$NON-NLS-1$
-        List docE5 = createElements(doc5, new String[] { "root", "root.node1", "root.node1.node2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-            
-        // Create mapping classes for xmltest.doc5
-        QueryNode mc1n1 = new QueryNode("SELECT e1 FROM pm1.g1 UNION ALL SELECT e1 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1mc1 = createVirtualGroup("xmltest.mc1", vm1, mc1n1); //$NON-NLS-1$
-        List vm1mc1e = createElements(vm1mc1,
-            new String[] { "e1" }, //$NON-NLS-1$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING });
-
-        List docE6 = createElements(doc6, new String[] { "root", "root.node", "root.thenode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-            
-        //XML STUFF =============================================
-
-        // Procedures and stored queries
-        FakeMetadataObject rs1 = createResultSet("pm1.rs1", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs1p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs1);  //$NON-NLS-1$
-        QueryNode sq1n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq1 = createVirtualProcedure("pm1.sq1", pm1, Arrays.asList(new FakeMetadataObject[] { rs1p1 }), sq1n1); //$NON-NLS-1$
-        
-        FakeMetadataObject rs2 = createResultSet("pm1.rs2", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq2 = createVirtualProcedure("pm1.sq2", pm1, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        FakeMetadataObject rs5 = createResultSet("pm1.r5", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs5p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs5);  //$NON-NLS-1$
-        FakeMetadataObject rs5p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs5p3 = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        QueryNode sq3n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq3.in UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sq3.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq3 = createVirtualProcedure("pm1.sq3", pm1, Arrays.asList(new FakeMetadataObject[] { rs5p1, rs5p2, rs5p3 }), sq3n1);  //$NON-NLS-1$
-
-        //For defect 8211 - this stored query has two input params, no return param, and
-        //the input params are PURPOSELY numbered with indices "1" and "3" - see defect 8211
-        FakeMetadataObject rs5a = createResultSet("pm1.r5a", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs5p1a = createParameter("in", 1, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs5p2a = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        QueryNode sq3n1a = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq3a.in UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sq3a.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq3a = createVirtualProcedure("pm1.sq3a", pm1, Arrays.asList(new FakeMetadataObject[] { rs5p1a, rs5p2a }), sq3n1a);  //$NON-NLS-1$
-
-        //Case 3281 - create procedures with optional parameter(s)
-        
-        //make "in2" parameter optional, make "in3" required but with a default value
-        FakeMetadataObject rs5b = createResultSet("pm1.r5b", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs5p1b = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs5b);  //$NON-NLS-1$
-        FakeMetadataObject rs5p2b = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs5p3b = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        FakeMetadataObject rs5p4b = createParameter("in3", 4, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        rs5p3b.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rs5p4b.setDefaultValue("YYZ"); //$NON-NLS-1$
-        QueryNode sq3n1b = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq3b.in UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sq3b.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq3b = createVirtualProcedure("pm1.sq3b", pm1, Arrays.asList(new FakeMetadataObject[] { rs5p1b, rs5p2b, rs5p3b, rs5p4b }), sq3n1b);  //$NON-NLS-1$
-        
-        //Make parameters of all different types, all with appropriate default values
-        //Make some parameters required, some optional
-        //Also, fully-qualify the param names
-        FakeMetadataObject rsDefaults = createResultSet("pm1.rDefaults", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rsDefaultsParameterReturn = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rsDefaults);  //$NON-NLS-1$
-        FakeMetadataObject rsDefaultsParameterString = createParameter("inString", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        //rsDefaultsParameterString.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsDefaultsParameterString.setDefaultValue(new String("x")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterBigDecimal = createParameter("inBigDecimal", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, null);  //$NON-NLS-1$
-        rsParameterBigDecimal.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterBigDecimal.setDefaultValue(new String("13.0")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterBigInteger = createParameter("inBigInteger", 4, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BIG_INTEGER, null);  //$NON-NLS-1$
-        rsParameterBigInteger.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterBigInteger.setDefaultValue(new String("13")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterBoolean = createParameter("inBoolean", 5, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BOOLEAN, null);  //$NON-NLS-1$
-        rsParameterBoolean.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterBoolean.setDefaultValue(new String("True")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterByte = createParameter("inByte", 6, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BYTE, null);  //$NON-NLS-1$
-        rsParameterByte.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterByte.setDefaultValue(new String("1")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterChar = createParameter("inChar", 7, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.CHAR, null);  //$NON-NLS-1$
-        rsParameterChar.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterChar.setDefaultValue(new String("q")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterDate = createParameter("inDate", 8, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.DATE, null);  //$NON-NLS-1$
-        rsParameterDate.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterDate.setDefaultValue(new String("2003-03-20")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterDouble = createParameter("inDouble", 9, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.DOUBLE, null);  //$NON-NLS-1$
-        rsParameterDouble.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterDouble.setDefaultValue(new String("13.0")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterFloat = createParameter("inFloat", 10, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.FLOAT, null);  //$NON-NLS-1$
-        rsParameterFloat.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterFloat.setDefaultValue(new String("13")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterInteger = createParameter("inInteger", 11, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        rsParameterInteger.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterInteger.setDefaultValue(new String("13")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterLong = createParameter("inLong", 12, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.LONG, null);  //$NON-NLS-1$
-        rsParameterLong.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterLong.setDefaultValue(new String("13")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterShort = createParameter("inShort", 13, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.SHORT, null);  //$NON-NLS-1$
-        rsParameterShort.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterShort.setDefaultValue(new String("13")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterTimestamp = createParameter("inTimestamp", 14, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.TIMESTAMP, null);  //$NON-NLS-1$
-        rsParameterTimestamp.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterTimestamp.setDefaultValue(new String("2003-03-20 21:26:00.000000")); //$NON-NLS-1$
-        FakeMetadataObject rsParameterTime = createParameter("inTime", 15, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.TIME, null);  //$NON-NLS-1$
-        rsParameterTime.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        rsParameterTime.setDefaultValue(new String("21:26:00")); //$NON-NLS-1$
-        QueryNode sqDefaultsNode = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sqDefaults.inString UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sqDefaults.inInteger; END"); //$NON-NLS-1$ //$NON-NLS-2$
-
-        FakeMetadataObject sqDefaults = createVirtualProcedure("pm1.sqDefaults", pm1, //$NON-NLS-1$
-                                                          Arrays.asList(new FakeMetadataObject[] { 
-                                                              rsDefaultsParameterReturn, 
-                                                              rsDefaultsParameterString, 
-                                                              rsParameterBigDecimal, 
-                                                              rsParameterBigInteger, 
-                                                              rsParameterBoolean, 
-                                                              rsParameterByte, 
-                                                              rsParameterChar, 
-                                                              rsParameterDate, 
-                                                              rsParameterDouble, 
-                                                              rsParameterFloat, 
-                                                              rsParameterInteger, 
-                                                              rsParameterLong, 
-                                                              rsParameterShort, 
-                                                              rsParameterTimestamp, 
-                                                              rsParameterTime, 
-                                                          }), sqDefaultsNode);  
-        
-        
-        FakeMetadataObject rsBadDefault = createResultSet("pm1.rBadDefault", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject paramBadDefaultRet = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rsBadDefault);  //$NON-NLS-1$
-        FakeMetadataObject paramBadDefaultIn = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        paramBadDefaultIn.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        paramBadDefaultIn.setDefaultValue("Clearly Not An Integer"); //$NON-NLS-1$
-        QueryNode sqnBadDefault = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sqBadDefault.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sqBadDefault = createVirtualProcedure("pm1.sqBadDefault", pm1, Arrays.asList(new FakeMetadataObject[] { paramBadDefaultRet, paramBadDefaultIn }), sqnBadDefault);  //$NON-NLS-1$
-        
-        //end case 3281
-        
-		FakeMetadataObject rs3 = createResultSet("pm1.rs3", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs3p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs3);  //$NON-NLS-1$
-        FakeMetadataObject sp1 = createStoredProcedure("pm1.sp1", pm1, Arrays.asList(new FakeMetadataObject[] { rs3p1 }));  //$NON-NLS-1$ //$NON-NLS-2$
-
-		FakeMetadataObject rs4 = createResultSet("pm1.rs4", pm1, new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs4p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs4);  //$NON-NLS-1$
-        QueryNode sqsp1n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sp1()) as x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sqsp1 = createVirtualProcedure("pm1.sqsp1", pm1, Arrays.asList(new FakeMetadataObject[] { rs4p1 }), sqsp1n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs6 = createResultSet("pm1.rs6", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs6p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs6);  //$NON-NLS-1$
-        QueryNode sq4n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sq1(); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq4 = createVirtualProcedure("pm1.sq4", pm1, Arrays.asList(new FakeMetadataObject[] { rs6p1}), sq4n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs7 = createResultSet("pm1.rs7", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs7p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs7);  //$NON-NLS-1$
-        FakeMetadataObject rs7p2 = createParameter("in1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq5n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sq2(pm1.sq5.in1); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq5 = createVirtualProcedure("pm1.sq5", pm1, Arrays.asList(new FakeMetadataObject[] { rs7p1, rs7p2 }), sq5n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs8 = createResultSet("pm1.rs8", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs8p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs8);  //$NON-NLS-1$
-        QueryNode sq6n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sq2(\'1\'); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq6 = createVirtualProcedure("pm1.sq6", pm1, Arrays.asList(new FakeMetadataObject[] { rs8p1 }), sq6n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs9 = createResultSet("pm1.rs9", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs9p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs9);  //$NON-NLS-1$
-        QueryNode sq7n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq1()) as x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq7 = createVirtualProcedure("pm1.sq7", pm1, Arrays.asList(new FakeMetadataObject[] { rs9p1 }), sq7n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs10 = createResultSet("pm1.rs10", pm1, new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs10p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs10);  //$NON-NLS-1$
-        FakeMetadataObject rs10p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq8n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq1()) as x WHERE x.e1=pm1.sq8.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq8 = createVirtualProcedure("pm1.sq8", pm1, Arrays.asList(new FakeMetadataObject[] { rs10p1, rs10p2 }), sq8n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs11 = createResultSet("pm1.rs11", pm1, new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs11p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs11);  //$NON-NLS-1$
-        FakeMetadataObject rs11p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq9n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq2(pm1.sq9.in)) as x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq9 = createVirtualProcedure("pm1.sq9", pm1, Arrays.asList(new FakeMetadataObject[] { rs11p1, rs11p2 }), sq9n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs12 = createResultSet("pm1.rs12", pm1, new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs12p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs12);  //$NON-NLS-1$
-        FakeMetadataObject rs12p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs12p3 = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        QueryNode sq10n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq2(pm1.sq10.in)) as x where e2=pm1.sq10.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq10 = createVirtualProcedure("pm1.sq10", pm1, Arrays.asList(new FakeMetadataObject[] { rs12p1, rs12p2,  rs12p3}), sq10n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs13 = createResultSet("pm1.rs13", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs13p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs13);  //$NON-NLS-1$
-        FakeMetadataObject rs13p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        FakeMetadataObject sp2 = createStoredProcedure("pm1.sp2", pm1, Arrays.asList(new FakeMetadataObject[] { rs13p1, rs13p2 }));  //$NON-NLS-1$ //$NON-NLS-2$
-
-		FakeMetadataObject rs14 = createResultSet("pm1.rs14", pm1, new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs14p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs14);  //$NON-NLS-1$
-        FakeMetadataObject rs14p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs14p3 = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        QueryNode sq11n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sp2(?)) as x where e2=pm1.sq11.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq11 = createVirtualProcedure("pm1.sq11", pm1, Arrays.asList(new FakeMetadataObject[] { rs14p1, rs14p2,  rs14p3}), sq11n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs15 = createResultSet("pm1.rs15", pm1, new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs15p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs15);  //$NON-NLS-1$
-        FakeMetadataObject rs15p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs15p3 = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        QueryNode sq12n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN INSERT INTO pm1.g1 ( e1, e2 ) VALUES( pm1.sq12.in, pm1.sq12.in2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq12 = createVirtualProcedure("pm1.sq12", pm1, Arrays.asList(new FakeMetadataObject[] { rs15p1, rs15p2, rs15p3 }), sq12n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs16 = createResultSet("pm1.rs16", pm1, new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs16p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs16);  //$NON-NLS-1$
-        FakeMetadataObject rs16p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode sq13n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN INSERT INTO pm1.g1 ( e1, e2 ) VALUES( pm1.sq13.in, 2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq13 = createVirtualProcedure("pm1.sq13", pm1, Arrays.asList(new FakeMetadataObject[] { rs16p1, rs16p2 }), sq13n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs17 = createResultSet("pm1.rs17", pm1, new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs17p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs17);  //$NON-NLS-1$
-        FakeMetadataObject rs17p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs17p3 = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        QueryNode sq14n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN UPDATE pm1.g1 SET e1 = pm1.sq14.in WHERE e2 = pm1.sq14.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq14 = createVirtualProcedure("pm1.sq14", pm1, Arrays.asList(new FakeMetadataObject[] { rs17p1, rs17p2, rs17p3 }), sq14n1);  //$NON-NLS-1$
-
-		FakeMetadataObject rs18 = createResultSet("pm1.rs17", pm1, new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rs18p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs18);  //$NON-NLS-1$
-        FakeMetadataObject rs18p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs18p3 = createParameter("in2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null);  //$NON-NLS-1$
-        QueryNode sq15n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DELETE FROM pm1.g1 WHERE e1 = pm1.sq15.in AND e2 = pm1.sq15.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq15 = createVirtualProcedure("pm1.sq15", pm1, Arrays.asList(new FakeMetadataObject[] { rs18p1, rs18p2, rs18p3 }), sq15n1);  //$NON-NLS-1$
-
-		QueryNode sq16n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN INSERT INTO pm1.g1 ( e1, e2 ) VALUES( 1, 2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq16 = createVirtualProcedure("pm1.sq16", pm1, new ArrayList(), sq16n1);  //$NON-NLS-1$
-
-        FakeMetadataObject rs19 = createResultSet("pm1.rs19", pm1, new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq17p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs19);  //$NON-NLS-1$
-        QueryNode sq17n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM xmltest.doc1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq17 = createVirtualProcedure("pm1.sq17", pm1, Arrays.asList(new FakeMetadataObject[] { sq17p1 }), sq17n1);  //$NON-NLS-1$
-
-		FakeMetadataObject sp3 = createStoredProcedure("pm1.sp3", pm1, new ArrayList());  //$NON-NLS-1$ //$NON-NLS-2$
-
-        FakeMetadataObject rs20 = createResultSet("pm1.rs20", pm1, new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq18p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs20); //$NON-NLS-1$
-        QueryNode sq18n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM xmltest.doc1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq18 = createVirtualProcedure("pm1.sq18", pm1, Arrays.asList(new FakeMetadataObject[] { sq18p1 }), sq18n1); //$NON-NLS-1$
-
-        FakeMetadataObject rs21 = createResultSet("pm1.rs21", pm1, new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq19p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs21); //$NON-NLS-1$
-        FakeMetadataObject sq19p2 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null); //$NON-NLS-1$
-        QueryNode sq19n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM xmltest.doc4 WHERE root.node1 = param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject sq19 = createVirtualProcedure("pm1.sq19", pm1, Arrays.asList(new FakeMetadataObject[] { sq19p1, sq19p2 }), sq19n1); //$NON-NLS-1$
-
-        FakeMetadataObject rs22p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BIG_INTEGER, null);  //$NON-NLS-1$
-        FakeMetadataObject sp4 = createStoredProcedure("pm1.sp4", pm1, Arrays.asList(new FakeMetadataObject[] { rs13p1, rs22p2 }));  //$NON-NLS-1$ //$NON-NLS-2$
-
-        // no params or result set at all
-        FakeMetadataObject sp5 = createStoredProcedure("pm1.sp5", pm1, Arrays.asList(new FakeMetadataObject[] {}));  //$NON-NLS-1$ //$NON-NLS-2$
-
-        //virtual stored procedures
-        FakeMetadataObject vsprs1 = createResultSet("pm1.vsprs1", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vspp1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsprs1); //$NON-NLS-1$
-//        QueryNode vspqn1 = new QueryNode("vsp1", "CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; LOOP ON (SELECT e1 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e1; IF(x > 5) BEGIN CONTINUE; END END SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        QueryNode vspqn1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e2; IF(x = 15) BEGIN BREAK; END END SELECT e1 FROM pm1.g1 where pm1.g1.e2 = x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp1 = createVirtualProcedure("pm1.vsp1", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn1); //$NON-NLS-1$
-
-        QueryNode vspqn2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e2; END SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp2 = createVirtualProcedure("pm1.vsp2", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn2); //$NON-NLS-1$
-
-        QueryNode vspqn3 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp3 = createVirtualProcedure("pm1.vsp3", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn3); //$NON-NLS-1$
-
-        QueryNode vspqn4 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN IF(mycursor.e2 > 10) BEGIN BREAK; END x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp4 = createVirtualProcedure("pm1.vsp4", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn4); //$NON-NLS-1$
-        
-        QueryNode vspqn5 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN IF(mycursor.e2 > 10) BEGIN CONTINUE; END x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp5 = createVirtualProcedure("pm1.vsp5", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn5); //$NON-NLS-1$
-
-        QueryNode vspqn6 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < 15) BEGIN x=x+1; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp6 = createVirtualProcedure("pm1.vsp6", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn6); //$NON-NLS-1$
-
-        FakeMetadataObject vspp2 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn7 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < 12) BEGIN x=x+pm1.vsp7.param1; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp7 = createVirtualProcedure("pm1.vsp7", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1, vspp2 }), vspqn7); //$NON-NLS-1$
-
-        FakeMetadataObject vspp8 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn8 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < 12) BEGIN x=x+pm1.vsp8.param1; END SELECT e1 FROM pm1.g1 WHERE e2 >= param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp8 = createVirtualProcedure("pm1.vsp8", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1, vspp8 }), vspqn8); //$NON-NLS-1$
-
-        FakeMetadataObject vspp9 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn9 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < param1) BEGIN x=x+pm1.vsp9.param1; END SELECT e1 FROM pm1.g1 WHERE e2 >= param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp9 = createVirtualProcedure("pm1.vsp9", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1, vspp9 }), vspqn9); //$NON-NLS-1$
-
-        FakeMetadataObject vspp3 = createParameter("param1", 1, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn10 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1 WHERE e2=param1) AS mycursor BEGIN x=mycursor.e2; END END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp10 = createVirtualProcedure("pm1.vsp10", pm1, Arrays.asList(new FakeMetadataObject[] { vspp3 }), vspqn10); //$NON-NLS-1$
-
-        //invalid
-        QueryNode vspqn11 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN LOOP ON (SELECT e1 FROM pm1.g1) AS mycursor BEGIN END END SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp11 = createVirtualProcedure("pm1.vsp11", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn11); //$NON-NLS-1$
-
-        //invalid
-        QueryNode vspqn12 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN END x=mycursor.e2; SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp12 = createVirtualProcedure("pm1.vsp12", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn12); //$NON-NLS-1$
-
-        FakeMetadataObject vsprs2 = createResultSet("pm1.vsprs2", pm1, new String[] { "e1", "const" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject vspp4 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsprs2); //$NON-NLS-1$
-        QueryNode vspqn13 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; LOOP ON (SELECT e1 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e1; END SELECT x, 5; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp13 = createVirtualProcedure("pm1.vsp13", pm1, Arrays.asList(new FakeMetadataObject[] { vspp4 }), vspqn13); //$NON-NLS-1$
-
-        QueryNode vspqn14 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1; SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp14 = createVirtualProcedure("pm1.vsp14", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn14); //$NON-NLS-1$
-
-        QueryNode vspqn15 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable, pm1.g2 WHERE #temptable.e2 = pm1.g2.e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp15 = createVirtualProcedure("pm1.vsp15", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn15); //$NON-NLS-1$
-        
-        QueryNode vspqn16 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT a.e1 FROM (SELECT pm1.g2.e1 FROM #temptable, pm1.g2 WHERE #temptable.e2 = pm1.g2.e2) AS a; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        //QueryNode vspqn16 = new QueryNode("vsp16", "CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT e1 FROM #temptable where e1 in (SELECT pm1.g2.e1 FROM  #temptable, pm1.g2 WHERE #temptable.e2 = pm1.g2.e2); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp16 = createVirtualProcedure("pm1.vsp16", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn16); //$NON-NLS-1$
-
-        QueryNode vspqn17 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; SELECT e1, e2 INTO #temptable FROM pm1.g1; LOOP ON (SELECT e1, e2 FROM #temptable) AS mycursor BEGIN x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp17 = createVirtualProcedure("pm1.vsp17", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn17); //$NON-NLS-1$
-
-        //invalid
-         QueryNode vspqn18 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO temptable FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-         FakeMetadataObject vsp18 = createVirtualProcedure("pm1.vsp18", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn18); //$NON-NLS-1$
-
-        QueryNode vspqn19 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1; SELECT e1 INTO #temptable FROM pm1.g1; SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp19 = createVirtualProcedure("pm1.vsp19", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn19); //$NON-NLS-1$
-
-        QueryNode vspqn20 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1; INSERT INTO #temptable(e1) VALUES( 'Fourth'); SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp20 = createVirtualProcedure("pm1.vsp20", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn20); //$NON-NLS-1$
-
-        FakeMetadataObject vspp21 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn21 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; INSERT INTO #temptable(#temptable.e1, e2) VALUES( 'Fourth', param1); SELECT e1, e2 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp21 = createVirtualProcedure("pm1.vsp21", pm1, Arrays.asList(new FakeMetadataObject[] { vspp4, vspp21 }), vspqn21); //$NON-NLS-1$
-
-        FakeMetadataObject vspp22 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn22 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1 where e2 > param1; SELECT e1, e2 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp22 = createVirtualProcedure("pm1.vsp22", pm1, Arrays.asList(new FakeMetadataObject[] { vspp4, vspp22 }), vspqn22); //$NON-NLS-1$
-
-        FakeMetadataObject vspp23 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn23 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; SELECT e1, e2 INTO #temptable FROM pm1.g1 where e2 > param1; x = SELECT e1 FROM #temptable WHERE e2=15; SELECT x, 15; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp23 = createVirtualProcedure("pm1.vsp23", pm1, Arrays.asList(new FakeMetadataObject[] { vspp4, vspp23 }), vspqn23); //$NON-NLS-1$
- 
-        QueryNode vspqn24 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable WHERE #temptable.e2=15; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp24 = createVirtualProcedure("pm1.vsp24", pm1, Arrays.asList(new FakeMetadataObject[] { vspp4 }), vspqn24); //$NON-NLS-1$
- 
-        QueryNode vspqn25 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1 WHERE e1 ='no match'; SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp25 = createVirtualProcedure("pm1.vsp25", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn25); //$NON-NLS-1$
-
-        QueryNode vspqn27 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 from (exec pm1.vsp25())as c; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp27 = createVirtualProcedure("pm1.vsp27", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn27); //$NON-NLS-1$
-
-        QueryNode vspqn28 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT 0 AS e1 ORDER BY e1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp28 = createVirtualProcedure("pm1.vsp28", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn28); //$NON-NLS-1$
-
-        QueryNode vspqn29 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1 ORDER BY e1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp29 = createVirtualProcedure("pm1.vsp29", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn29); //$NON-NLS-1$
-
-        FakeMetadataObject vsprs30 = createResultSet("pm1.vsprs30", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp30p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, null, vsprs30); //$NON-NLS-1$
-        QueryNode vspqn30 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp30 = createVirtualProcedure("pm1.vsp30", pm1, Arrays.asList(new FakeMetadataObject[] {vsp30p1}), vspqn30); //$NON-NLS-1$        
-
-        FakeMetadataObject vsprs31 = createResultSet("pm1.vsprs31", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp31p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, null, vsprs31); //$NON-NLS-1$
-        FakeMetadataObject vsp31p2 = createParameter("p1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn31 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1 WHERE e2 = pm1.vsp31.p1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp31 = createVirtualProcedure("pm1.vsp31", pm1, Arrays.asList(new FakeMetadataObject[] {vsp31p1, vsp31p2}), vspqn31); //$NON-NLS-1$        
-
-        QueryNode vspqn38 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer VARIABLES.y; VARIABLES.y=5; EXEC pm1.vsp7(VARIABLES.y); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp38 = createVirtualProcedure("pm1.vsp38", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn38); //$NON-NLS-1$
-  
-        QueryNode vspqn39 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer VARIABLES.x; VARIABLES.x=5; EXEC pm1.vsp7(VARIABLES.x); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp39 = createVirtualProcedure("pm1.vsp39", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn39); //$NON-NLS-1$
-
-        QueryNode vspqn40 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN EXEC pm1.vsp41(); END END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp40 = createVirtualProcedure("pm1.vsp40", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn40); //$NON-NLS-1$
-
-        QueryNode vspqn41 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1 where e2=15; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp41 = createVirtualProcedure("pm1.vsp41", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn41); //$NON-NLS-1$
-
-        vm1g1.putProperty(FakeMetadataObject.Props.INSERT_PROCEDURE, "CREATE PROCEDURE BEGIN ROWS_UPDATED = INSERT INTO pm1.g1(e1, e2, e3, e4) values(INPUT.e1, INPUT.e2, INPUT.e3, INPUT.e4); END"); //$NON-NLS-1$
-        vm1g1.putProperty(FakeMetadataObject.Props.UPDATE_PROCEDURE, "CREATE PROCEDURE BEGIN ROWS_UPDATED = UPDATE pm1.g1 SET e1 = INPUT.e1, e2 = INPUT.e2, e3 = INPUT.e3, e4=INPUT.e4 WHERE TRANSLATE CRITERIA; END"); //$NON-NLS-1$       
-        vm1g1.putProperty(FakeMetadataObject.Props.DELETE_PROCEDURE, "CREATE PROCEDURE BEGIN ROWS_UPDATED = DELETE FROM pm1.g1 WHERE TRANSLATE CRITERIA; END"); //$NON-NLS-1$       
-
-        vm1g37.putProperty(FakeMetadataObject.Props.INSERT_PROCEDURE, "CREATE PROCEDURE BEGIN ROWS_UPDATED = INSERT INTO pm4.g1(e1, e2, e3, e4) values(INPUT.e1, INPUT.e2, INPUT.e3, INPUT.e4); END"); //$NON-NLS-1$
-        vm1g37.putProperty(FakeMetadataObject.Props.DELETE_PROCEDURE, "CREATE PROCEDURE BEGIN ROWS_UPDATED = DELETE FROM pm4.g1 where translate criteria; END"); //$NON-NLS-1$
-        QueryNode vspqn37 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; VARIABLES.x=5; INSERT INTO vm1.g1(e2) values(VARIABLES.x); SELECT ROWCOUNT; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp37 = createVirtualProcedure("pm1.vsp37", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn37); //$NON-NLS-1$
-
-        QueryNode vspqn33 = new QueryNode(new StringBuffer("CREATE VIRTUAL PROCEDURE")  //$NON-NLS-1$//$NON-NLS-2$
-                                                            .append(" BEGIN") //$NON-NLS-1$
-                                                            .append(" SELECT 3 AS temp1 INTO #myTempTable;") //$NON-NLS-1$
-                                                            .append(" SELECT 2 AS temp1 INTO #myTempTable;") //$NON-NLS-1$
-                                                            .append(" SELECT 1 AS temp1 INTO #myTempTable;") //$NON-NLS-1$
-                                                            .append(" SELECT temp1 AS e1 FROM #myTempTable ORDER BY e1;") //$NON-NLS-1$
-                                                            .append(" END").toString() //$NON-NLS-1$
-                                         );
-        FakeMetadataObject vsp33 = createVirtualProcedure("pm1.vsp33", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn33); //$NON-NLS-1$
-
-        QueryNode vspqn35 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer VARIABLES.ID; VARIABLES.ID = pm1.vsp35.p1; SELECT e1 FROM pm1.g1 WHERE e2 = VARIABLES.ID; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp35 = createVirtualProcedure("pm1.vsp35", pm1, Arrays.asList(new FakeMetadataObject[] {vsp31p1, vsp31p2}), vspqn35); //$NON-NLS-1$        
-
-        QueryNode vspqn34 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, 0 AS const FROM pm1.g1 ORDER BY const; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp34 = createVirtualProcedure("pm1.vsp34", pm1, Arrays.asList(new FakeMetadataObject[] { vspp4 }), vspqn34); //$NON-NLS-1$
-
-        QueryNode vspqn45 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable where #temptable.e1 in (SELECT pm1.g2.e1 FROM pm1.g2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp45 = createVirtualProcedure("pm1.vsp45", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn45); //$NON-NLS-1$
-        
-        // Virtual group w/ procedure in transformation, optional params, named parameter syntax
-        QueryNode vspqn47 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp47.param1 IS NOT NULL) BEGIN SELECT 'FOO' as e1, pm1.vsp47.param1 as e2; END ELSE BEGIN SELECT pm1.vsp47.param2 as e1, 2112 as e2; END END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsprs47 = createResultSet("pm1.vsprs47", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject vspp47_1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsprs47); //$NON-NLS-1$
-        FakeMetadataObject vspp47_2 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        vspp47_2.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        FakeMetadataObject vspp47_3 = createParameter("param2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null); //$NON-NLS-1$
-        vspp47_3.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        FakeMetadataObject vsp47 = createVirtualProcedure("pm1.vsp47", pm1, Arrays.asList(new FakeMetadataObject[] { vspp47_1, vspp47_2, vspp47_3 }), vspqn47); //$NON-NLS-1$
-        QueryNode vgvpn7 = new QueryNode("SELECT P.e2 as ve3, P.e1 as ve4 FROM (EXEC pm1.vsp47(param1=vm1.vgvp7.ve1, param2=vm1.vgvp7.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
-//        QueryNode vgvpn7 = new QueryNode("vm1.vgvp7", "SELECT P.e2 as ve1, P.e1 as ve2 FROM (EXEC pm1.vsp47(vm1.vgvp7.ve1, vm1.vgvp7.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vgvp7 = createVirtualGroup("vm1.vgvp7", vm1, vgvpn7); //$NON-NLS-1$
-        FakeMetadataObject vgvp7e1 = FakeMetadataFactory.createElement("vm1.vgvp7.ve1", vgvp7, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        vgvp7e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp7e2 = FakeMetadataFactory.createElement("vm1.vgvp7.ve2", vgvp7, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vgvp7e2.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp7e3 = FakeMetadataFactory.createElement("vm1.vgvp7.ve3", vgvp7, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        FakeMetadataObject vgvp7e4 = FakeMetadataFactory.createElement("vm1.vgvp7.ve4", vgvp7, DataTypeManager.DefaultDataTypes.STRING, 3); //$NON-NLS-1$
-        
-        
-        //invalid
-        QueryNode vspqn32 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS #mycursor BEGIN IF(#mycursor.e2 > 10) BEGIN CONTINUE; END x=#mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp32 = createVirtualProcedure("pm1.vsp32", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn32); //$NON-NLS-1$
-
-        //virtual group with procedure in transformation
-        QueryNode vspqn26 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e2 >= pm1.vsp26.param1 and e1 = pm1.vsp26.param2; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vspp26_1 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        FakeMetadataObject vspp26_2 = createParameter("param2", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null); //$NON-NLS-1$
-        FakeMetadataObject vsprs3 = createResultSet("pm1.vsprs3", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject vspp6 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsprs3); //$NON-NLS-1$
-        FakeMetadataObject vsp26 = createVirtualProcedure("pm1.vsp26", pm1, Arrays.asList(new FakeMetadataObject[] { vspp6, vspp26_1, vspp26_2 }), vspqn26); //$NON-NLS-1$
-		QueryNode vgvpn1 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp1.ve1, vm1.vgvp1.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vgvp1 = createVirtualGroup("vm1.vgvp1", vm1, vgvpn1); //$NON-NLS-1$
-        FakeMetadataObject vgvp1e1 = FakeMetadataFactory.createElement("vm1.vgvp1.ve1", vgvp1, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        vgvp1e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp1e2 = FakeMetadataFactory.createElement("vm1.vgvp1.ve2", vgvp1, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vgvp1e2.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp1e3 = FakeMetadataFactory.createElement("vm1.vgvp1.ve3", vgvp1, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-      
-		QueryNode vgvpn2 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp2.ve1, vm1.vgvp2.ve2)) as P where P.e1='a'"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vgvp2 = createVirtualGroup("vm1.vgvp2", vm1, vgvpn2); //$NON-NLS-1$
-        FakeMetadataObject vgvp2e1 = FakeMetadataFactory.createElement("vm1.vgvp2.ve1", vgvp2, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        vgvp2e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp2e2 = FakeMetadataFactory.createElement("vm1.vgvp2.ve2", vgvp2, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vgvp2e2.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp2e3 = FakeMetadataFactory.createElement("vm1.vgvp2.ve3", vgvp2, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-   
-		QueryNode vgvpn3 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp3.ve1, vm1.vgvp3.ve2)) as P, pm1.g2 where P.e1=g2.e1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vgvp3 = createVirtualGroup("vm1.vgvp3", vm1, vgvpn3); //$NON-NLS-1$
-        FakeMetadataObject vgvp3e1 = FakeMetadataFactory.createElement("vm1.vgvp3.ve1", vgvp3, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        vgvp3e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp3e2 = FakeMetadataFactory.createElement("vm1.vgvp3.ve2", vgvp3, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vgvp3e2.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp3e3 = FakeMetadataFactory.createElement("vm1.vgvp3.ve3", vgvp3, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-
-		QueryNode vgvpn4 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp4.ve1, vm1.vgvp4.ve2)) as P, vm1.g1 where P.e1=g1.e1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vgvp4 = createVirtualGroup("vm1.vgvp4", vm1, vgvpn4); //$NON-NLS-1$
-        FakeMetadataObject vgvp4e1 = FakeMetadataFactory.createElement("vm1.vgvp4.ve1", vgvp4, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        vgvp4e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp4e2 = FakeMetadataFactory.createElement("vm1.vgvp4.ve2", vgvp4, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vgvp4e2.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp4e3 = FakeMetadataFactory.createElement("vm1.vgvp4.ve3", vgvp4, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        
-		QueryNode vgvpn5 = new QueryNode("SELECT * FROM vm1.vgvp4 where vm1.vgvp4.ve1=vm1.vgvp5.ve1 and  vm1.vgvp4.ve2=vm1.vgvp5.ve2"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vgvp5 = createVirtualGroup("vm1.vgvp5", vm1, vgvpn5); //$NON-NLS-1$
-        FakeMetadataObject vgvp5e1 = FakeMetadataFactory.createElement("vm1.vgvp5.ve1", vgvp5, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        vgvp5e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp5e2 = FakeMetadataFactory.createElement("vm1.vgvp5.ve2", vgvp5, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vgvp5e2.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp5e3 = FakeMetadataFactory.createElement("vm1.vgvp5.ve3", vgvp5, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-
-		QueryNode vgvpn6 = new QueryNode("SELECT P.e1 as ve3, P.e2 as ve4 FROM (EXEC pm1.vsp26(vm1.vgvp6.ve1, vm1.vgvp6.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vgvp6 = createVirtualGroup("vm1.vgvp6", vm1, vgvpn6); //$NON-NLS-1$
-        FakeMetadataObject vgvp6e1 = FakeMetadataFactory.createElement("vm1.vgvp6.ve1", vgvp6, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        vgvp6e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp6e2 = FakeMetadataFactory.createElement("vm1.vgvp6.ve2", vgvp6, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vgvp6e2.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vgvp6e3 = FakeMetadataFactory.createElement("vm1.vgvp6.ve3", vgvp6, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        FakeMetadataObject vgvp6e4 = FakeMetadataFactory.createElement("vm1.vgvp6.ve4", vgvp6, DataTypeManager.DefaultDataTypes.INTEGER, 3); //$NON-NLS-1$
-
-        //virtual group with two elements. One selectable, one not.
-        QueryNode vm1g35n1 = new QueryNode("SELECT e1, e2 FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g35 = createVirtualGroup("vm1.g35", vm1, vm1g35n1); //$NON-NLS-1$
-        FakeMetadataObject vm1g35e1 = FakeMetadataFactory.createElement("vm1.g35.e1", vm1g35, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        vm1g35e1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject vm1g35e2 = FakeMetadataFactory.createElement("vm1.g35.e2", vm1g35, DataTypeManager.DefaultDataTypes.INTEGER, 2); //$NON-NLS-1$
-		
-        FakeMetadataObject vsprs36 = createResultSet("pm1.vsprs36", pm1, new String[] { "x" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp36p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, null, vsprs36); //$NON-NLS-1$
-        FakeMetadataObject vsp36p2 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn36 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x = pm1.vsp36.param1 * 2; SELECT x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp36 = createVirtualProcedure("pm1.vsp36", pm1, Arrays.asList(new FakeMetadataObject[] { vsp36p1, vsp36p2 }), vspqn36); //$NON-NLS-1$
-
-        FakeMetadataObject vsprs42 = createResultSet("pm1.vsprs42", pm1, new String[] { "x" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp42p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, null, vsprs42); //$NON-NLS-1$
-        FakeMetadataObject vsp42p2 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn42 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp42 = createVirtualProcedure("pm1.vsp42", pm1, Arrays.asList(new FakeMetadataObject[] { vsp42p1, vsp42p2 }), vspqn42); //$NON-NLS-1$
-
-        FakeMetadataObject vspp44 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn44 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT pm1.vsp44.param1 INTO #temptable; SELECT e1 from pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$    
-        FakeMetadataObject vsp44 = createVirtualProcedure("pm1.vsp44", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1, vspp44 }), vspqn44); //$NON-NLS-1$
-
-        FakeMetadataObject vspp43 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn43 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN exec pm1.vsp44(pm1.vsp43.param1); END"); //$NON-NLS-1$ //$NON-NLS-2$    
-        FakeMetadataObject vsp43 = createVirtualProcedure("pm1.vsp43", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1, vspp43 }), vspqn43); //$NON-NLS-1$
-        
-        QueryNode vspqn46 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table #temptable (e1 string, e2 string); LOOP ON (SELECT e1 FROM pm1.g1) AS mycursor BEGIN select mycursor.e1, a.e1 as e2 into #temptable from (SELECT pm1.g1.e1 FROM pm1.g1 where pm1.g1.e1 = mycursor.e1) a; END SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp46 = createVirtualProcedure("pm1.vsp46", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn46); //$NON-NLS-1$
-        
-        FakeMetadataObject vsp48rs = createResultSet("pm1vsp48.rs", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vsp48p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsp48rs);  //$NON-NLS-1$
-        FakeMetadataObject vsp48p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode vspqn48 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; SELECT e1 FROM (EXEC pm1.sq2(pm1.vsp48.in)) as e; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp48 = createVirtualProcedure("pm1.vsp48", pm1, Arrays.asList(new FakeMetadataObject[] { vsp48p1, vsp48p2 }), vspqn48); //$NON-NLS-1$
-        
-        FakeMetadataObject vsp49rs = createResultSet("pm1vsp49.rs", pm1, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-        FakeMetadataObject vsp49p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsp49rs);  //$NON-NLS-1$
-        QueryNode vspqn49 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; EXEC pm1.sq2(x); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp49 = createVirtualProcedure("pm1.vsp49", pm1, Arrays.asList(new FakeMetadataObject[] { vsp49p1 }), vspqn49); //$NON-NLS-1$
-
-        FakeMetadataObject vsp50rs = createResultSet("pm1vsp50.rs", pm1, new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vsp50p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsp50rs);  //$NON-NLS-1$
-        QueryNode vspqn50 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; SELECT e1 FROM (EXEC pm1.sq2(x)) as e; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp50 = createVirtualProcedure("pm1.vsp50", pm1, Arrays.asList(new FakeMetadataObject[] { vsp50p1 }), vspqn50); //$NON-NLS-1$
-
-        FakeMetadataObject vsp51rs = createResultSet("pm1vsp51.rs", pm1, new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vsp51p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsp51rs);  //$NON-NLS-1$
-        QueryNode vspqn51 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; LOOP ON (SELECT e1 FROM (EXEC pm1.sq2(x)) as e) AS c BEGIN x = x || 'b'; END SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp51 = createVirtualProcedure("pm1.vsp51", pm1, Arrays.asList(new FakeMetadataObject[] { vsp51p1 }), vspqn51); //$NON-NLS-1$
-
-        FakeMetadataObject vsp52rs = createResultSet("pm1vsp52.rs", pm1, new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vsp52p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsp52rs);  //$NON-NLS-1$
-        QueryNode vspqn52 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'c'; x = SELECT e1 FROM (EXEC pm1.sq2(x)) as e; SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp52 = createVirtualProcedure("pm1.vsp52", pm1, Arrays.asList(new FakeMetadataObject[] { vsp52p1 }), vspqn52); //$NON-NLS-1$
-
-        FakeMetadataObject vsp53rs = createResultSet("pm1vsp53.rs", pm1, new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vsp53p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsp53rs);  //$NON-NLS-1$
-        FakeMetadataObject vsp53p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode vspqn53 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; LOOP ON (SELECT e1 FROM (EXEC pm1.sq2(pm1.vsp53.in)) as e) AS c BEGIN x = x || 'b'; END SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp53 = createVirtualProcedure("pm1.vsp53", pm1, Arrays.asList(new FakeMetadataObject[] { vsp53p1, vsp53p2 }), vspqn53); //$NON-NLS-1$
-
-        FakeMetadataObject vsp54rs = createResultSet("pm1vsp54.rs", pm1, new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vsp54p1 = createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, vsp54rs);  //$NON-NLS-1$
-        FakeMetadataObject vsp54p2 = createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        QueryNode vspqn54 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'c'; x = SELECT e1 FROM (EXEC pm1.sq2(pm1.vsp54.in)) as e; SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp54 = createVirtualProcedure("pm1.vsp54", pm1, Arrays.asList(new FakeMetadataObject[] { vsp54p1, vsp54p2 }), vspqn54); //$NON-NLS-1$
-        
-        FakeMetadataObject vspp55 = createParameter("param1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn55 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN select e1, param1 as a from vm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp55 = createVirtualProcedure("pm1.vsp55", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1, vspp55 }), vspqn55); //$NON-NLS-1$
-
-        QueryNode vspqn56 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp56 = createVirtualProcedure("pm1.vsp56", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn56); //$NON-NLS-1$
-
-        QueryNode vspqn57 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable order by #temptable.e1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp57 = createVirtualProcedure("pm1.vsp57", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn57); //$NON-NLS-1$
-
-        FakeMetadataObject vspp58 = createParameter("inp", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER, null); //$NON-NLS-1$
-        QueryNode vspqn58 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT vsp58.inp; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp58 = createVirtualProcedure("pm1.vsp58", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1, vspp58 }), vspqn58); //$NON-NLS-1$
-        
-        QueryNode vspqn59 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temp FROM pm5.g3;INSERT INTO #temp (e1, e2) VALUES('integer',1); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp59 = createVirtualProcedure("pm5.vsp59", pm6, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn59); //$NON-NLS-1$
-        
-        QueryNode vspqn60 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table temp_table (column1 string);insert into temp_table (column1) values ('First');insert into temp_table (column1) values ('Second');insert into temp_table (column1) values ('Third');select * from temp_table; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp60 = createVirtualProcedure("pm1.vsp60", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn60); //$NON-NLS-1$
-
-        QueryNode vspqn61 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table temp_table (column1 string);insert into temp_table (column1) values ('First');drop table temp_table;create local temporary table temp_table (column1 string);insert into temp_table (column1) values ('First');insert into temp_table (column1) values ('Second');insert into temp_table (column1) values ('Third');select * from temp_table; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp61 = createVirtualProcedure("pm1.vsp61", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn61); //$NON-NLS-1$
-
-        QueryNode vspqn62 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table temp_table (column1 string); select e1 as column1 into temp_table from pm1.g1;select * from temp_table; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp62 = createVirtualProcedure("pm1.vsp62", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn62); //$NON-NLS-1$
-
-        QueryNode vspqn63 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string o; if(1>0) begin declare string a; a='b'; o=a; end if(1>0) begin declare string a; a='c'; o=a; end  select o; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vsp63 = createVirtualProcedure("pm1.vsp63", pm1, Arrays.asList(new FakeMetadataObject[] { vspp1 }), vspqn63); //$NON-NLS-1$
-
-        // Add all objects to the store
-		FakeMetadataStore store = new FakeMetadataStore();
-		store.addObject(vsp63);
-		store.addObject(pm1);
-		store.addObject(pm1g1);		
-		store.addObjects(pm1g1e);
-		store.addObject(pm1g2);		
-		store.addObjects(pm1g2e);
-		store.addObject(pm1g3);	
-		store.addObjects(pm1g3e);
-        store.addObject(pm1g4);
-        store.addObjects(pm1g4e);
-        store.addObject(pm1g5);
-        store.addObjects(pm1g5e);
-        store.addObject(pm1g6);
-        store.addObjects(pm1g6e);
-        store.addObject(pm1table);
-        store.addObjects(pm1tablee);
-        
-		store.addObject(pm2);
-		store.addObject(pm2g1);		
-		store.addObjects(pm2g1e);
-		store.addObject(pm2g2);		
-		store.addObjects(pm2g2e);
-		store.addObject(pm2g3);		
-		store.addObjects(pm2g3e);
-
-		store.addObject(pm3);
-        store.addObject(pm3g1);
-        store.addObjects(pm3g1e);
-        store.addObject(pm3g2);
-        store.addObjects(pm3g2e);
-
-        store.addObject(pm4);
-        store.addObject(pm4g1);
-        store.addObjects(pm4g1e);
-        store.addObject(pm4g2);
-        store.addObjects(pm4g2e);
-        store.addObject(pm4g1ap1);
-        store.addObject(pm4g2ap1);
-		store.addObject(pm4g2ap2);
-
-		store.addObject(pm5);
-		store.addObject(pm5g1);
-		store.addObjects(pm5g1e);
-		store.addObject(pm5g2);
-		store.addObjects(pm5g2e);
-		store.addObject(pm5g3);
-		store.addObjects(pm5g3e);
-		store.addObject(pm5g1ap1);
-		store.addObject(pm5g2ap1);
-		store.addObject(pm5g2ap2);
-
-        store.addObject(pm6);
-        store.addObject(pm6g1);
-        store.addObjects(pm6g1e);
-
-        store.addObject(tm1);
-        store.addObject(tm1g1);
-        store.addObjects(tm1g1e);
-        store.addObject(tm1g2);
-        store.addObjects(tm1g2e);        
-
-		store.addObject(vm1);
-		store.addObject(vm1g1);
-		store.addObjects(vm1g1e);
-        store.addObject(vm1g1_defect10711);
-        store.addObjects(vm1g1e_defect10711);
-        store.addObject(vm1g1_defect12081);
-        store.addObjects(vm1g1e_defect12081);
-        store.addObject(vm1g1c);
-        store.addObjects(vm1g1ce);
-        store.addObject(vm1g2a);
-        store.addObjects(vm1g2ae);
-		store.addObject(vm1g2);
-		store.addObjects(vm1g2e);
-		store.addObject(vm1g4);
-		store.addObjects(vm1g4e);
-        store.addObject(vm1g5);
-        store.addObjects(vm1g5e);
-        store.addObject(vm1g6);
-        store.addObjects(vm1g6e);
-        store.addObject(vm1g7);
-        store.addObjects(vm1g7e);
-        store.addObject(vm1g8);
-        store.addObjects(vm1g8e);
-        store.addObject(vm1g9);
-        store.addObjects(vm1g9e);
-        store.addObject(vm1g10);
-        store.addObjects(vm1g10e);
-        store.addObject(vm1g11);
-        store.addObjects(vm1g11e);
-        store.addObject(vm1g12);
-        store.addObjects(vm1g12e);
-        store.addObject(vm1g13);
-        store.addObjects(vm1g13e);
-        store.addObject(vm1g14);
-        store.addObjects(vm1g14e);
-        store.addObject(vm1g15);
-        store.addObjects(vm1g15e);
-        store.addObject(vm1g16);
-        store.addObjects(vm1g16e);
-        store.addObject(vm1g17);
-        store.addObjects(vm1g17e);
-        store.addObject(vm1g18);
-        store.addObjects(vm1g18e);
-        store.addObject(vm1g19);
-        store.addObjects(vm1g19e);
-        store.addObject(vm1g20);
-        store.addObjects(vm1g20e);
-        store.addObject(vm1g21);
-        store.addObjects(vm1g21e);
-        store.addObject(vm1g22);
-        store.addObjects(vm1g22e);
-        store.addObject(vm1g23);
-        store.addObjects(vm1g23e);
-        store.addObject(vm1g24);
-        store.addObjects(vm1g24e);
-        store.addObject(vm1g25);
-        store.addObjects(vm1g25e);
-        store.addObject(vm1g26);
-        store.addObjects(vm1g26e);
-        store.addObject(vm1g27);
-        store.addObjects(vm1g27e);
-        store.addObject(vm1g28);
-        store.addObjects(vm1g28e);
-        store.addObject(vm1g29);
-        store.addObjects(vm1g29e);
-        store.addObject(vm1g30);
-        store.addObjects(vm1g30e);
-        store.addObject(vm1g31);
-        store.addObjects(vm1g31e);
-        store.addObject(vm1g32);
-        store.addObjects(vm1g32e);
-        store.addObject(vm1g33);
-        store.addObjects(vm1g33e);
-        store.addObject(vm1g34);
-        store.addObjects(vm1g34e);
-        store.addObject(vm1g36);
-        store.addObjects(vm1g36e);
-        store.addObject(vm1g37);
-        store.addObjects(vm1g37e);
-        store.addObject(vm1g37ap1);
-        store.addObject(vm1g38);
-        store.addObjects(vm1g38e);
-                
-        store.addObject(vm2);
-		store.addObject(vm2g1);
-		store.addObjects(vm2g1e);
-
-        store.addObject(doc1);
-        store.addObject(doc2);
-        store.addObject(doc3);
-        store.addObject(doc4);        
-        store.addObject(doc5);
-        store.addObject(doc6);
-        store.addObject(docAmbiguous1);
-        store.addObject(docAmbiguous2);
-		store.addObjects(docE1);
-		store.addObjects(docE2);
-		store.addObjects(docE3);
-		store.addObjects(docE4);
-        store.addObjects(docE5);
-        store.addObject(vm1mc1);
-        store.addObjects(vm1mc1e);
-        store.addObjects(docE6);
-        
-        
-        store.addObject(rs1);
-        store.addObject(sq1);
-        store.addObject(rs2);
-        store.addObject(sq2);
-        store.addObject(rs3);
-        store.addObject(sp1);
-        store.addObject(rs4);
-        store.addObject(sqsp1);
-        store.addObject(rs5);
-		store.addObject(rs5a);
-        store.addObject(sq3);
-		store.addObject(sq3a);
-        store.addObject(sq3b);
-        store.addObject(sqDefaults);
-        store.addObject(sqBadDefault);
-        store.addObject(rs6);
-        store.addObject(sq4);
-        store.addObject(rs7);
-        store.addObject(sq5);
-        store.addObject(rs8);
-        store.addObject(sq6);
-        store.addObject(rs9);
-        store.addObject(sq7);
-        store.addObject(rs10);
-        store.addObject(sq8);
-        store.addObject(rs11);
-        store.addObject(sq9);
-        store.addObject(rs12);
-        store.addObject(sq10);
-        store.addObject(rs13);
-        store.addObject(sp2);
-        store.addObject(rs14);
-        store.addObject(sq11);
-        store.addObject(rs15);
-        store.addObject(sq12);
-        store.addObject(rs16);
-        store.addObject(sq13);
-        store.addObject(rs17);
-        store.addObject(sq14);
-        store.addObject(rs18);
-        store.addObject(sq15);
-        store.addObject(sq16);
-        store.addObject(rs19);
-        store.addObject(sq17);
-        store.addObject(sp3);
-        store.addObject(rs20);
-        store.addObject(sq18);
-        store.addObject(rs21);
-        store.addObject(sq19);
-        store.addObject(vsp1);        
-        store.addObject(vsp2);
-        store.addObject(vsp3);
-        store.addObject(vsp4);
-        store.addObject(vsp5);
-        store.addObject(vsp6);
-        store.addObject(vsp7);
-        store.addObject(vsp8);
-        store.addObject(vsp9);
-        store.addObject(vsp10);
-        store.addObject(vsp11);
-        store.addObject(vsp12);
-        store.addObject(vsp13);
-        store.addObject(vsp14);
-        store.addObject(vsp15);
-        store.addObject(vsp16);
-        store.addObject(vsp17);
-        store.addObject(vsp18);
-        store.addObject(vsp19);
-        store.addObject(vsp20);
-        store.addObject(vsp21);
-        store.addObject(vsp22);
-        store.addObject(vsp23);
-        store.addObject(vsp24);
-        store.addObject(vsp25);
-        store.addObject(vsp27);
-        store.addObject(vsp28);
-        store.addObject(vsp29);
-        store.addObject(vsp33);
-        store.addObject(vsp34);
-        store.addObject(sp4);
-        store.addObject(sp5);
-		store.addObject(vsp26);
-        store.addObject(vsprs30);
-        store.addObject(vsp30);
-        store.addObject(vsprs31);
-        store.addObject(vsp31);
-        store.addObject(vsp35);
-		store.addObject(vgvp1);
-		store.addObject(vgvp1e1);
-		store.addObject(vgvp1e2);
-		store.addObject(vgvp1e3);
-		store.addObject(vgvp2);
-		store.addObject(vgvp2e1);
-		store.addObject(vgvp2e2);
-		store.addObject(vgvp2e3);
-		store.addObject(vgvp3);
-		store.addObject(vgvp3e1);
-		store.addObject(vgvp3e2);
-		store.addObject(vgvp3e3);
-		store.addObject(vgvp4);
-		store.addObject(vgvp4e1);
-		store.addObject(vgvp4e2);
-		store.addObject(vgvp4e3);
-		store.addObject(vgvp5);
-		store.addObject(vgvp5e1);
-		store.addObject(vgvp5e2);
-		store.addObject(vgvp5e3);
-		store.addObject(vgvp6);
-		store.addObject(vgvp6e1);
-		store.addObject(vgvp6e2);
-		store.addObject(vgvp6e3);
-		store.addObject(vgvp6e4);
-        store.addObject(vgvp7);
-        store.addObject(vgvp7e1);
-        store.addObject(vgvp7e2);
-        store.addObject(vgvp7e3);
-        store.addObject(vgvp7e4);
-		store.addObject(vm1g35);
-		store.addObject(vm1g35e1);
-		store.addObject(vm1g35e2);
-        store.addObject(vsp36);
-        store.addObject(vsprs36);
-        store.addObject(vsp32);
-        store.addObject(vsp37);
-        store.addObject(vsp38);
-        store.addObject(vsp39);
-        store.addObject(vsp40);
-        store.addObject(vsp41);
-        store.addObject(vsp42);
-        store.addObject(vsp43);
-        store.addObject(vsp44);
-        store.addObject(vsp45);
-        store.addObject(vsp46);
-        store.addObject(vsp47);
-        store.addObject(vsp48rs);
-        store.addObject(vsp48);
-        store.addObject(vsp49rs);
-        store.addObject(vsp49);
-        store.addObject(vsp50rs);
-        store.addObject(vsp50);
-        store.addObject(vsp51rs);
-        store.addObject(vsp51);
-        store.addObject(vsp52rs);
-        store.addObject(vsp52);
-        store.addObject(vsp53rs);
-        store.addObject(vsp53);
-        store.addObject(vsp54rs);
-        store.addObject(vsp54);
-        store.addObject(vsp55);
-        store.addObject(vsp56);
-        store.addObject(vsp57);
-        store.addObject(vsp58);
-        store.addObject(vsp59);
-        store.addObject(vsp60);
-        store.addObject(vsp61);
-        store.addObject(vsp62);
-		store.addObject(vm1g39);
-		store.addObjects(vm1g39e);
-                
-		// Create the facade from the store
-		return new FakeMetadataFacade(store);
-	}
-
-    private static MappingDocument exampleDoc1() {
-        MappingDocument doc = new MappingDocument(false);
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-        MappingElement node1 = root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
-        MappingElement node2 = node1.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
-        node2.addChildElement(new MappingElement("node3")); //$NON-NLS-1$        
-        return doc;
-    }
-
-    private static MappingDocument exampleDoc2() {
-        
-        MappingDocument doc = new MappingDocument(false);
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-        MappingElement node1 = root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
-        
-        MappingSequenceNode node2 = node1.addSequenceNode(new MappingSequenceNode());    
-        node2.addChildElement(new MappingElement("node3")); //$NON-NLS-1$
-        root.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
-        return doc;
-    }
-
-    // has ambiguous short and long names
-    private static MappingDocument exampleDoc3() {
-        MappingDocument doc = new MappingDocument(false);
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
-        MappingSequenceNode node1 = root.addSequenceNode(new MappingSequenceNode());    
-        node1.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
-        root.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
-        return doc;
-    }
-    
-   
-    // has attributes and elements
-    private static MappingDocument exampleDoc4() {
-        
-        MappingDocument doc = new MappingDocument(false);
-        
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
-        root.addAttribute(new MappingAttribute("node6")); //$NON-NLS-1$
-        root.addStagingTable("tm1.g1"); //$NON-NLS-1$
-        
-        MappingElement node1 =root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
-        node1.addAttribute(new MappingAttribute("node2")); //$NON-NLS-1$
-        
-        MappingElement node3 =root.addChildElement(new MappingElement("node3")); //$NON-NLS-1$
-        node3.addAttribute(new MappingAttribute("node4")); //$NON-NLS-1$
-        
-        MappingElement node5 = node3.addChildElement(new MappingElement("node4")); //$NON-NLS-1$
-        MappingElement duplicateRoot = node5.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
-        duplicateRoot.addChildElement(new MappingElement("node6")); //$NON-NLS-1$        
-        return doc;
-    }    
-
-    // has a union in the mapping class
-    private static MappingDocument exampleDoc5() {
-        MappingDocument doc = new MappingDocument(false);
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
-        MappingElement node1 = root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
-        node1.addChildElement(new MappingElement("node2","xmltest.mc1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
-        node1.setSource("xmltest.mc1"); //$NON-NLS-1$
-        node1.setMaxOccurrs(-1);
-        return doc;
-    }	
-    
-    // has two elements with common suffix, but not ambiguous
-    private static MappingDocument exampleDoc6() {
-        MappingDocument doc = new MappingDocument(false);
-        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
-
-        root.addChildElement(new MappingElement("node")); //$NON-NLS-1$
-        root.addChildElement(new MappingElement("thenode")); //$NON-NLS-1$
-        return doc;
-    }    
-    
-    public static FakeMetadataFacade example3() {
-		// Create models
-		FakeMetadataObject pm1 = createPhysicalModel("pm1"); //$NON-NLS-1$
-		FakeMetadataObject pm2 = createPhysicalModel("pm2"); //$NON-NLS-1$
-        FakeMetadataObject pm3 = createPhysicalModel("pm3"); //$NON-NLS-1$
-
-		// Create physical groups
-		FakeMetadataObject pm1g1 = createPhysicalGroup("pm1.cat1.cat2.cat3.g1", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g2 = createPhysicalGroup("pm1.cat1.g2", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g3 = createPhysicalGroup("pm1.cat2.g3", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm2g1 = createPhysicalGroup("pm2.cat1.g1", pm2); //$NON-NLS-1$
-		FakeMetadataObject pm2g2 = createPhysicalGroup("pm2.cat2.g2", pm2); //$NON-NLS-1$
-		FakeMetadataObject pm2g3 = createPhysicalGroup("pm2.g3", pm2); //$NON-NLS-1$
-        FakeMetadataObject pm2g4 = createPhysicalGroup("pm2.g4", pm3);		 //$NON-NLS-1$
-		FakeMetadataObject pm2g5 = createPhysicalGroup("pm2.cat3.g1", pm2); //$NON-NLS-1$
-						
-		// Create physical elements
-		List pm1g1e = createElements(pm1g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g2e = createElements(pm1g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g3e = createElements(pm1g3, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g1e = createElements(pm2g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g2e = createElements(pm2g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g3e = createElements(pm2g3, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g4e = createElements(pm2g4, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g5e = createElements(pm2g5, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });			
-
-		
-		// Add all objects to the store
-		FakeMetadataStore store = new FakeMetadataStore();
-		store.addObject(pm1);
-		store.addObject(pm1g1);		
-		store.addObjects(pm1g1e);
-		store.addObject(pm1g2);		
-		store.addObjects(pm1g2e);
-		store.addObject(pm1g3);	
-		store.addObjects(pm1g3e);
-        	
-		store.addObject(pm2);
-		store.addObject(pm2g1);		
-		store.addObjects(pm2g1e);
-		store.addObject(pm2g2);		
-		store.addObjects(pm2g2e);
-		store.addObject(pm2g3);
-		store.addObject(pm2g4);
-		store.addObject(pm2g5);		
-		store.addObjects(pm2g3e);
-		store.addObjects(pm2g4e);
-		store.addObjects(pm2g5e);		
-        
-		store.addObject(pm3);
-						
-		// Create the facade from the store
-		return new FakeMetadataFacade(store);
-	}
-
-	/**
-	 * This example is for testing static costing using cardinality information from
-	 * metadata, as well as key information and maybe access patterns
-	 * @return FakeMetadataFacade
-	 */
-	public static FakeMetadataFacade example4() {
-		// Create models - physical ones will support joins
-		FakeMetadataObject pm1 = createPhysicalModel("pm1"); //$NON-NLS-1$
-		FakeMetadataObject pm2 = createPhysicalModel("pm2"); //$NON-NLS-1$
-		FakeMetadataObject pm3 = createPhysicalModel("pm3"); //$NON-NLS-1$
-        FakeMetadataObject pm4 = createPhysicalModel("pm4"); //$NON-NLS-1$
-		FakeMetadataObject vm1 = createVirtualModel("vm1");	 //$NON-NLS-1$
-
-		// Create physical groups
-		FakeMetadataObject pm1g1 = createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g2 = createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g3 = createPhysicalGroup("pm1.g3", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm2g1 = createPhysicalGroup("pm2.g1", pm2); //$NON-NLS-1$
-		FakeMetadataObject pm2g2 = createPhysicalGroup("pm2.g2", pm2); //$NON-NLS-1$
-		FakeMetadataObject pm2g3 = createPhysicalGroup("pm2.g3", pm2); //$NON-NLS-1$
-		FakeMetadataObject pm3g1 = createPhysicalGroup("pm3.g1", pm3); //$NON-NLS-1$
-		FakeMetadataObject pm3g2 = createPhysicalGroup("pm3.g2", pm3); //$NON-NLS-1$
-		FakeMetadataObject pm3g3 = createPhysicalGroup("pm3.g3", pm3); //$NON-NLS-1$
-        FakeMetadataObject pm4g1 = createPhysicalGroup("pm4.g1", pm4); //$NON-NLS-1$
-        FakeMetadataObject pm4g2 = createPhysicalGroup("pm4.g2", pm4); //$NON-NLS-1$
-		// Add group cardinality metadata
-		pm1g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
-		pm1g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
-		pm1g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(10));
-		pm2g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000));
-		pm2g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000));
-		pm3g1.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(100000));
-		pm3g2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(100000));
-        pm3g3.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(100000));
-        // leave pm4.g1 as unknown
-				
-		// Create physical elements
-		List pm1g1e = createElements(pm1g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g2e = createElements(pm1g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g3e = createElements(pm1g3, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g1e = createElements(pm2g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g2e = createElements(pm2g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g3e = createElements(pm2g3, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm3g1e = createElements(pm3g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm3g2e = createElements(pm3g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm3g3e = createElements(pm3g3, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm4g1e = createElements(pm4g1, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm4g2e = createElements(pm4g2, 
-                new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-                new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-
-		// Add key metadata
-		FakeMetadataObject pm1g1key1 = createKey("pm1.g1.key1", pm1g1, pm1g1e.subList(0, 1)); //e1 //$NON-NLS-1$
-		FakeMetadataObject pm3g1key1 = createKey("pm3.g1.key1", pm3g1, pm3g1e.subList(0, 1)); //e1 //$NON-NLS-1$
-		FakeMetadataObject pm3g3key1 = createKey("pm3.g3.key1", pm3g3, pm3g3e.subList(0, 1)); //e1 //$NON-NLS-1$
-        FakeMetadataObject pm4g1key1 = createKey("pm4.g1.key1", pm4g1, pm4g1e.subList(0, 2)); //e1, e2 //$NON-NLS-1$
-        FakeMetadataObject pm4g2key1 = createForeignKey("pm4.g2.fk", pm4g2, pm4g2e.subList(0, 2), pm4g1key1); //$NON-NLS-1$
-		// Add access pattern metadata
-		// Create access patterns - pm1
-		List elements = new ArrayList(1);
-		elements.add(pm1g1e.iterator().next());       
-		FakeMetadataObject pm1g1ap1 = createAccessPattern("pm1.g1.ap1", pm1g1, elements); //e1 //$NON-NLS-1$
-		elements = new ArrayList(2);
-		Iterator iter = pm1g3e.iterator();
-		elements.add(iter.next());       
-		elements.add(iter.next());       
-		FakeMetadataObject pm1g3ap1 = createAccessPattern("pm1.g3.ap1", pm1g3, elements); //e1,e2 //$NON-NLS-1$
-		// Create access patterns - pm2
-		elements = new ArrayList(1);
-		elements.add(pm2g1e.iterator().next());
-		FakeMetadataObject pm2g1ap1 = createAccessPattern("pm2.g1.ap1", pm2g1, elements); //e1 //$NON-NLS-1$
-
-
-		// Create virtual groups
-		QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g1 = createUpdatableVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
-
-		QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g2 = createUpdatableVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
-
-		QueryNode vm1g3n1 = new QueryNode("SELECT pm1.g3.e1 AS x, pm1.g3.e2 AS y from pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g3 = createUpdatableVirtualGroup("vm1.g3", vm1, vm1g3n1); //$NON-NLS-1$
-	
-        QueryNode vm1g4n1 = new QueryNode("SELECT distinct pm1.g2.e1 as ve1, pm1.g1.e1 as ve2 FROM pm1.g2 LEFT OUTER JOIN /* optional */ pm1.g1 on pm1.g1.e1 = pm1.g2.e1");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g4 = createVirtualGroup("vm1.g4", vm1, vm1g4n1); //$NON-NLS-1$
-        List vm1g4e = createElements(vm1g4,
-                  new String[] { "ve1", "ve2" }, //$NON-NLS-1$ //$NON-NLS-2$
-                  new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-		// Create virtual elements
-		List vm1g1e = createElements(vm1g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1g2e = createElements(vm1g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List vm1g3e = createElements(vm1g3,
-			new String[] { "e1", "e2","x", "y" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
-			
-		// Add all objects to the store
-		FakeMetadataStore store = new FakeMetadataStore();
-		store.addObject(pm1);
-		store.addObject(pm1g1);		
-		store.addObjects(pm1g1e);
-		store.addObject(pm1g2);		
-		store.addObjects(pm1g2e);
-		store.addObject(pm1g3);	
-		store.addObjects(pm1g3e);
-		store.addObject(pm1g1key1);
-		store.addObject(pm1g1ap1);
-		store.addObject(pm1g3ap1);
-        	
-		store.addObject(pm2);
-		store.addObject(pm2g1);		
-		store.addObjects(pm2g1e);
-		store.addObject(pm2g2);		
-		store.addObjects(pm2g2e);
-		store.addObject(pm2g3);		
-		store.addObjects(pm2g3e);
-		store.addObject(pm2g1ap1);
-        
-		store.addObject(pm3);
-		store.addObject(pm3g1);
-		store.addObjects(pm3g1e);
-		store.addObject(pm3g2);
-		store.addObjects(pm3g2e);
-		store.addObject(pm3g3);
-		store.addObjects(pm3g3e);
-		store.addObject(pm3g1key1);
-		store.addObject(pm3g3key1);
-
-        store.addObject(pm4);
-        store.addObject(pm4g1);
-        store.addObjects(pm4g1e);
-        store.addObject(pm4g1key1);
-        store.addObject(pm4g2);
-        store.addObjects(pm4g2e);
-        store.addObject(pm4g2key1);
-        
-        store.addObject(vm1);
-		store.addObject(vm1g1);
-		store.addObjects(vm1g1e);
-		store.addObject(vm1g2);
-		store.addObjects(vm1g2e);
-		store.addObject(vm1g3);
-		store.addObjects(vm1g3e);
-        store.addObject(vm1g4);
-        store.addObjects(vm1g4e);
-						
-		// Create the facade from the store
-		return new FakeMetadataFacade(store);
-	}
-	
-	public static FakeMetadataFacade exampleUpdateProc(String procedureType, String procedure) {
-		// Create models
-		FakeMetadataObject pm1 = createPhysicalModel("pm1"); //$NON-NLS-1$
-		FakeMetadataObject pm2 = createPhysicalModel("pm2"); //$NON-NLS-1$
-		FakeMetadataObject vm1 = createVirtualModel("vm1"); //$NON-NLS-1$
-
-		// Create physical groups
-		FakeMetadataObject pm1g1 = createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-		FakeMetadataObject pm1g2 = createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm2g1 = createPhysicalGroup("pm2.g1", pm2); //$NON-NLS-1$
-        FakeMetadataObject pm2g2 = createPhysicalGroup("pm2.g2", pm2); //$NON-NLS-1$
-
-		// Create physical group elements
-		List pm1g1e = createElements(pm1g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm1g2e = createElements(pm1g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g1e = createElements(pm2g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-		List pm2g2e = createElements(pm2g2, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-
-		// Create virtual groups
-		QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g1 = createUpdatableVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
-
-		QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g2 = createUpdatableVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
-
-		QueryNode vm1g3n1 = new QueryNode("SELECT CONCAT(e1, 'm') as x, (e2 +1) as y, 1 as e3, e4*50 as e4 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g3 = createUpdatableVirtualGroup("vm1.g3", vm1, vm1g3n1); //$NON-NLS-1$
-
-		QueryNode vm1g4n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-		FakeMetadataObject vm1g4 = createUpdatableVirtualGroup("vm1.g4", vm1, vm1g4n1); //$NON-NLS-1$
-
-		// Create virtual elements
-		List vm1g1e = createElementsWithDefaults(vm1g1, 
-			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
-			new Object[] { "xyz", Integer.getInteger("123"), Boolean.valueOf("true"), Double.valueOf("123.456")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-		List vm1g2e = createElementsWithDefaults(vm1g2, 
-			new String[] { "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN },
-			new Object[] { "abc", Integer.getInteger("456"), Boolean.valueOf("false")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		List vm1g3e = createElementsWithDefaults(vm1g3,
-			new String[] { "x", "y", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.DOUBLE },
-			new Object[] { "mno", Integer.getInteger("789"), Boolean.valueOf("true"), Double.valueOf("789.012")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-		List vm1g4e = createElementsWithDefaults(vm1g4, 
-				new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-				new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
-				new Object[] { "xyz", Integer.getInteger("123"), Boolean.valueOf("true"), Double.valueOf("123.456")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-
-		vm1g1.putProperty(procedureType, procedure);
-		vm1g2.putProperty(procedureType, procedure);
-		vm1g3.putProperty(procedureType, procedure);				
-		vm1g4.putProperty(procedureType, procedure);
-
-		// Add all objects to the store
-		FakeMetadataStore store = new FakeMetadataStore();
-		store.addObject(pm1);
-		store.addObject(pm1g1);		
-		store.addObjects(pm1g1e);
-		store.addObject(pm1g2);		
-		store.addObjects(pm1g2e);
-        	
-		store.addObject(pm2);
-		store.addObject(pm2g1);		
-		store.addObjects(pm2g1e);
-		store.addObject(pm2g2);		
-		store.addObjects(pm2g2e);
-
-		store.addObject(vm1);
-		store.addObject(vm1g1);
-		store.addObjects(vm1g1e);
-		store.addObject(vm1g2);
-		store.addObjects(vm1g2e);
-		store.addObject(vm1g3);
-		store.addObjects(vm1g3e);
-		store.addObject(vm1g4);
-		store.addObjects(vm1g4e);
-
-		// Create the facade from the store
-		return new FakeMetadataFacade(store);
-	}
-
-    public static FakeMetadataFacade exampleUpdateProc(String procedureType, String procedure1, String procedure2) {
-        // Create models
-        FakeMetadataObject pm1 = createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject pm2 = createPhysicalModel("pm2"); //$NON-NLS-1$
-        FakeMetadataObject vm1 = createVirtualModel("vm1"); //$NON-NLS-1$
-
-        // Create physical groups
-        FakeMetadataObject pm1g1 = createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm1g2 = createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-        FakeMetadataObject pm2g1 = createPhysicalGroup("pm2.g1", pm2); //$NON-NLS-1$
-        FakeMetadataObject pm2g2 = createPhysicalGroup("pm2.g2", pm2); //$NON-NLS-1$
-
-        // Create physical group elements
-        List pm1g1e = createElements(pm1g1, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm1g2e = createElements(pm1g2, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm2g1e = createElements(pm2g1, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-        List pm2g2e = createElements(pm2g2, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
-
-        // Create virtual groups
-        QueryNode vm1g1n1 = new QueryNode("SELECT * FROM vm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g1 = createUpdatableVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
-
-        QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g2 = createUpdatableVirtualGroup("vm1.g2", vm1, vm1g2n1); //$NON-NLS-1$
-
-        // Create virtual elements
-        List vm1g1e = createElementsWithDefaults(vm1g1, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
-            new Object[] { "xyz", Integer.getInteger("123"), Boolean.valueOf("true"), Double.valueOf("123.456")}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-        List vm1g2e = createElementsWithDefaults(vm1g2, 
-            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
-            new Object[] { "abc", Integer.getInteger("456"), Boolean.valueOf("false"), null}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
-        vm1g1.putProperty(procedureType, procedure1);
-        vm1g2.putProperty(procedureType, procedure2);
-
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
-        store.addObject(pm1g2);     
-        store.addObjects(pm1g2e);
-            
-        store.addObject(pm2);
-        store.addObject(pm2g1);     
-        store.addObjects(pm2g1e);
-        store.addObject(pm2g2);     
-        store.addObjects(pm2g2e);
-
-        store.addObject(vm1);
-        store.addObject(vm1g1);
-        store.addObjects(vm1g1e);
-        store.addObject(vm1g2);
-        store.addObjects(vm1g2e);
-
-        // Create the facade from the store
-        return new FakeMetadataFacade(store);
-    }
-    
-    public static VDBMetaData exampleBQTVDB() {
-    	VDBMetaData vdb = new VDBMetaData();
-    	vdb.setName("example1");
-    	vdb.setVersion(1);
-    	vdb.addModel(createModel("BQT1", true));
-    	vdb.addModel(createModel("BQT2", true));
-    	vdb.addModel(createModel("BQT3", true));
-    	vdb.addModel(createModel("LOB", true));
-    	vdb.addModel(createModel("VQT", false));
-    	vdb.addModel(createModel("pm1", true));
-    	vdb.addModel(createModel("pm2", true));
-    	vdb.addModel(createModel("pm3", true));
-    	vdb.addModel(createModel("pm4", true));
-    	
-    	return vdb;
-    }
-    
-    public static TransformationMetadata exampleBQT() { 
-    	return RealMetadataFactory.exampleBQT();
-    }
-
-    public static FakeMetadataFacade exampleYahoo() { 
-        // Create models
-        FakeMetadataObject yahoo = createPhysicalModel("Yahoo"); //$NON-NLS-1$
-        
-        // Create physical groups
-        FakeMetadataObject quotes = createPhysicalGroup("Yahoo.QuoteServer", yahoo); //$NON-NLS-1$
-                
-        // Create physical elements
-        String[] elemNames = new String[] {
-            "TickerSymbol", "LastTrade",  //$NON-NLS-1$ //$NON-NLS-2$
-            "LastTradeDate", "LastTradeTime", //$NON-NLS-1$ //$NON-NLS-2$
-            "PercentageChange", "TickerSymbol2",  //$NON-NLS-1$ //$NON-NLS-2$
-            "DaysHigh", "DaysLow",  //$NON-NLS-1$ //$NON-NLS-2$
-            "TotalVolume"             //$NON-NLS-1$
-        };
-        String[] elemTypes = new String[] {  
-            DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DOUBLE,
-            DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME,
-            DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING,
-            DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE,
-            DataTypeManager.DefaultDataTypes.BIG_INTEGER            
-        };
-        
-        List cols = createElements(quotes, elemNames, elemTypes);
-        
-        // Set name in source on each column
-        String[] nameInSource = new String[] {
-           "Symbol", "Last", "Date", "Time", "Change", "Symbol2", "High", "Low", "Volume"             //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$
-        };
-        for(int i=0; i<9; i++) {
-            FakeMetadataObject obj = (FakeMetadataObject) cols.get(i);
-            obj.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, nameInSource[i]);
-        }
-        
-        // Set column-specific properties
-        ((FakeMetadataObject) cols.get(0)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        for(int i=1; i<9; i++) {
-            ((FakeMetadataObject) cols.get(0)).putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
-            ((FakeMetadataObject) cols.get(0)).putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
-        }
-        
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(yahoo);
-        store.addObject(quotes);     
-        store.addObjects(cols);
-        
-        // Create the facade from the store
-        return new FakeMetadataFacade(store);
-    }
-    
-    public static VDBMetaData examplePrivatePhysicalModelVDB() {
-    	VDBMetaData vdb = new VDBMetaData();
-    	vdb.setName("example1");
-    	vdb.setVersion(1);
-    	ModelMetaData m = createModel("pm1", true);
-    	m.setVisible(false);
-    	vdb.addModel(m);
-    	vdb.addModel(createModel("vm1", false));
-    	
-    	return vdb;
-    }    
-    
-    public static FakeMetadataFacade examplePrivatePhysicalModel() { 
-        // Create models
-        FakeMetadataObject pm1 = createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject vm1 = createVirtualModel("vm1");  //$NON-NLS-1$
-
-        // Create physical groups
-        FakeMetadataObject pm1g1 = createPhysicalGroup("pm1.g1", pm1); //$NON-NLS-1$
-            
-        QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vm1g1 = createVirtualGroup("vm1.g1", vm1, vm1g1n1); //$NON-NLS-1$
-        
-        FakeMetadataObject pm1g2 = createPhysicalGroup("pm1.g2", pm1); //$NON-NLS-1$
-        
-        // Create physical elements
-        List pm1g1e = createElements(pm1g1, 
-            new String[] { "e1"}, //$NON-NLS-1$ 
-            new String[] { DataTypeManager.DefaultDataTypes.SHORT});
- 
-        // Create physical elements
-        List pm1g2e = createElements(pm1g2, 
-            new String[] { "e1"}, //$NON-NLS-1$ 
-            new String[] { DataTypeManager.DefaultDataTypes.BIG_DECIMAL});
-        
-        FakeMetadataObject e1 = (FakeMetadataObject)pm1g2e.get(0);
-        e1.putProperty(FakeMetadataObject.Props.PRECISION, "19"); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.LENGTH, "21"); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.SCALE, "4"); //$NON-NLS-1$
-        
-        List vm1g1e = createElements(vm1g1, 
-                                    new String[] { "e1" }, //$NON-NLS-1$
-                                    new String[] { DataTypeManager.DefaultDataTypes.STRING });
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(pm1);
-        store.addObject(pm1g1);     
-        store.addObjects(pm1g1e);
-        
-        store.addObject(vm1);
-        store.addObject(vm1g1);
-        store.addObjects(vm1g1e);
-        
-        store.addObject(pm1g2);     
-        store.addObjects(pm1g2e);
-
-        // Create the facade from the store
-        return new FakeMetadataFacade(store);
-    }
-
-    public static FakeMetadataFacade exampleBusObj() { 
-        // Create db2 tables
-        FakeMetadataObject db2Model = createPhysicalModel("db2model"); //$NON-NLS-1$
-        
-        FakeMetadataObject db2Table = createPhysicalGroup("db2model.DB2_TABLE", db2Model); //$NON-NLS-1$
-        List db2Elements = createElements(db2Table, 
-            new String[] { "PRODUCT", "REGION", "SALES"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DOUBLE});
-
-        FakeMetadataObject salesTable = createPhysicalGroup("db2model.SALES", db2Model); //$NON-NLS-1$
-        salesTable.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000000));
-        List salesElem = createElements(salesTable, 
-            new String[] { "CITY", "MONTH", "SALES"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DOUBLE});
-
-        FakeMetadataObject geographyTable2 = createPhysicalGroup("db2model.GEOGRAPHY2", db2Model); //$NON-NLS-1$
-        geographyTable2.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000));
-        List geographyElem2 = createElements(geographyTable2, 
-            new String[] { "CITY", "REGION"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        List geoPkElem2 = new ArrayList();
-        geoPkElem2.add(geographyElem2.get(0));
-        FakeMetadataObject geoPk2 = createKey("db2model.GEOGRAPHY2.GEOGRAPHY_PK", geographyTable2, geoPkElem2); //$NON-NLS-1$
-
-        FakeMetadataObject db2Table2 = createPhysicalGroup("db2model.DB2TABLE", db2Model); //$NON-NLS-1$
-        List db2Elements2 = createElements(db2Table2, 
-            new String[] { "c0", "c1", "c2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
-
-        // Create oracle tables 
-        FakeMetadataObject oraModel = createPhysicalModel("oraclemodel"); //$NON-NLS-1$
-
-        FakeMetadataObject oraTable = createPhysicalGroup("oraclemodel.Oracle_table", oraModel); //$NON-NLS-1$
-        List oracleElements = createElements(oraTable, 
-            new String[] { "COSTS", "REGION", "YEAR"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        FakeMetadataObject geographyTable = createPhysicalGroup("oraclemodel.GEOGRAPHY", oraModel); //$NON-NLS-1$
-        geographyTable.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000));
-        List geographyElem = createElements(geographyTable, 
-            new String[] { "CITY", "REGION"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        List geoPkElem = new ArrayList();
-        geoPkElem.add(geographyElem.get(0));
-        FakeMetadataObject geoPk = createKey("oraclemodel.GEOGRAPHY.GEOGRAPHY_PK", geographyTable, geoPkElem); //$NON-NLS-1$
-
-        FakeMetadataObject oraTable2 = createPhysicalGroup("oraclemodel.OraTable", oraModel); //$NON-NLS-1$
-        List oracleElements2 = createElements(oraTable2, 
-            new String[] { "b0", "b1", "b2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        // Create sql server tables 
-        FakeMetadataObject msModel = createPhysicalModel("msmodel"); //$NON-NLS-1$
-
-        FakeMetadataObject timeTable = createPhysicalGroup("msmodel.TIME", msModel); //$NON-NLS-1$
-        timeTable.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(120));
-        List timeElem = createElements(timeTable, 
-            new String[] { "MONTH", "YEAR"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-        List timePkElem = new ArrayList();
-        timePkElem.add(timeElem.get(0));
-        FakeMetadataObject timePk = createKey("msmodel.TIME.TIME_PK", timeTable, timePkElem); //$NON-NLS-1$
-
-        FakeMetadataObject virtModel = createVirtualModel("logical"); //$NON-NLS-1$
-        QueryNode n1 = new QueryNode("select sum(c0) as c0, c1, c2 from db2Table group by c1, c2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject logicalTable1 = createVirtualGroup("logical.logicalTable1", virtModel, n1); //$NON-NLS-1$
-        List logicalElem1 = createElements(logicalTable1, 
-            new String[] { "c0", "c1", "c2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
-
-        QueryNode n2 = new QueryNode("select sum(c0) as c0, c1, c2 from db2Table group by c1, c2"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject logicalTable2 = createVirtualGroup("logical.logicalTable2", virtModel, n2); //$NON-NLS-1$
-        List logicalElem2 = createElements(logicalTable2, 
-            new String[] { "b0", "b1", "b2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
-
-        // Add all objects to the store
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(db2Model);
-        store.addObject(db2Table);     
-        store.addObjects(db2Elements);
-        store.addObject(salesTable);     
-        store.addObjects(salesElem);
-        store.addObject(geographyTable2);     
-        store.addObjects(geographyElem2);
-        store.addObject(geoPk2);     
-        store.addObject(db2Table2);     
-        store.addObjects(db2Elements2);
-        
-        store.addObject(oraModel);
-        store.addObject(oraTable);
-        store.addObjects(oracleElements);
-        store.addObject(geographyTable);     
-        store.addObjects(geographyElem);
-        store.addObject(geoPk);     
-        store.addObject(oraTable2);
-        store.addObjects(oracleElements2);
-
-        store.addObject(msModel);
-        store.addObject(timeTable);
-        store.addObjects(timeElem);
-        store.addObject(timePk);
-
-        store.addObject(virtModel);
-        store.addObject(logicalTable1);
-        store.addObjects(logicalElem1);
-        store.addObject(logicalTable2);
-        store.addObjects(logicalElem2);
-
-        // Create the facade from the store
-        return new FakeMetadataFacade(store);
-    }
-
-    public static FakeMetadataFacade exampleAggregates() { 
-        FakeMetadataStore store = new FakeMetadataStore();
-        addAggregateTablesToModel("m1", store); //$NON-NLS-1$
-        addAggregateTablesToModel("m2", store); //$NON-NLS-1$
-
-        // Create the facade from the store
-        return new FakeMetadataFacade(store);
-    }
-    
-    public static void addAggregateTablesToModel(String modelName, FakeMetadataStore store) {
-        // Create db2 tables
-        FakeMetadataObject model = createPhysicalModel(modelName); 
-        
-        FakeMetadataObject orders = createPhysicalGroup(modelName + ".order", model); //$NON-NLS-1$
-        orders.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000000));
-        List orderElements = createElements(orders, 
-            new String[] { "O_OrderID", "O_ProductID", "O_DealerID", "O_Amount", "O_Date"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ 
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, DataTypeManager.DefaultDataTypes.DATE });
-
-        FakeMetadataObject products = createPhysicalGroup(modelName + ".product", model); //$NON-NLS-1$
-        products.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000));
-        List productsElements = createElements(products, 
-            new String[] { "P_ProductID", "P_Overhead", "P_DivID"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, DataTypeManager.DefaultDataTypes.INTEGER});
-
-        FakeMetadataObject divisions = createPhysicalGroup(modelName + ".division", model); //$NON-NLS-1$
-        divisions.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(100));
-        List divisionsElements = createElements(divisions, 
-            new String[] { "V_DIVID", "V_SectorID"}, //$NON-NLS-1$ //$NON-NLS-2$ 
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
-
-        FakeMetadataObject dealers = createPhysicalGroup(modelName + ".dealer", model); //$NON-NLS-1$
-        dealers.putProperty(FakeMetadataObject.Props.CARDINALITY, new Integer(1000));
-        List dealersElements = createElements(dealers, 
-            new String[] { "D_DealerID", "D_State", "D_Address"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
-            new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        // Add all objects to the store
-        store.addObject(model);
-        store.addObject(orders);     
-        store.addObjects(orderElements);
-        store.addObject(products);     
-        store.addObjects(productsElements);
-        store.addObject(divisions);     
-        store.addObjects(divisionsElements);
-        store.addObject(dealers);     
-        store.addObjects(dealersElements);
-    }
-    
-    
-    public static VDBMetaData exampleMultiBindingVDB() {
-    	VDBMetaData vdb = new VDBMetaData();
-    	vdb.setName("exampleMultiBinding");
-    	vdb.setVersion(1);
-    	
-    	ModelMetaData model = new ModelMetaData();
-    	model.setName("MultiModel");
-   		model.setModelType(Model.Type.PHYSICAL);
-    	model.setVisible(true);
-    	
-    	model.setSupportsMultiSourceBindings(true);
-    	vdb.addModel(model);
-    	vdb.addModel(createModel("Virt", false));
-    	
-    	return vdb;
-    }
-    
-    /** 
-     * Metadata for Multi-Binding models
-     * @return example
-     * @since 4.2
-     */
-    public static FakeMetadataFacade exampleMultiBinding() {
-        FakeMetadataObject virtModel = createVirtualModel("Virt"); //$NON-NLS-1$
-        FakeMetadataObject physModel = createPhysicalModel("MultiModel"); //$NON-NLS-1$
-        
-        FakeMetadataObject physGroup = createPhysicalGroup("MultiModel.Phys", physModel); //$NON-NLS-1$
-        List physElements = createElements(physGroup,
-                                      new String[] { "a", "b" }, //$NON-NLS-1$ //$NON-NLS-2$ 
-                                      new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        
-        QueryNode virtTrans = new QueryNode("SELECT * FROM MultiModel.Phys");         //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject virtGroup = createVirtualGroup("Virt.view", virtModel, virtTrans); //$NON-NLS-1$
-        List virtElements = createElements(virtGroup,
-                                           new String[] { "a", "b" }, //$NON-NLS-1$ //$NON-NLS-2$ 
-                                           new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        
-        FakeMetadataObject rs2 = FakeMetadataFactory.createResultSet("Virt.rs1", virtModel, new String[] { "a", "b" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs2p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs2);  //$NON-NLS-1$
-        FakeMetadataObject rs2p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        rs2p2.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
-                                        + "execute string 'SELECT a, b FROM MultiModel.Phys where SOURCE_NAME = Virt.sq1.in'; END"); //$NON-NLS-1$ 
-        FakeMetadataObject sq1 = FakeMetadataFactory.createVirtualProcedure("Virt.sq1", virtModel, Arrays.asList(new FakeMetadataObject[] { rs2p1, rs2p2 }), sq2n1);  //$NON-NLS-1$
-
-        FakeMetadataObject rs3 = FakeMetadataFactory.createResultSet("MultiModel.rs1", virtModel, new String[] { "a", "b" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject rs3p1 = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, rs3);  //$NON-NLS-1$
-        FakeMetadataObject rs3p2 = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject rs3p3 = FakeMetadataFactory.createParameter("source_name", 3, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        rs3p3.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        FakeMetadataObject sq2 = FakeMetadataFactory.createStoredProcedure("MultiModel.proc", physModel, Arrays.asList(new FakeMetadataObject[] { rs3p1, rs3p2, rs3p3 }));
-        rs3p2.putProperty(FakeMetadataObject.Props.GROUP, sq2);
-        rs3p3.putProperty(FakeMetadataObject.Props.GROUP, sq2);
-        
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(virtModel);
-        store.addObject(physModel);
-        store.addObject(physGroup);
-        store.addObjects(physElements);
-        store.addObject(virtGroup);
-        store.addObjects(virtElements);
-        
-        store.addObject(rs2);
-        store.addObject(sq1);
-        store.addObject(rs3);
-        store.addObject(sq2);
-        
-        return new FakeMetadataFacade(store);
-    }
-
-    /**
-     * set up metadata for virtual doc model of this basic structure:
-     * <pre>
-     * 
-     * items
-     *   --suppliers (many-to-many relationship between items and suppliers)
-     *       --orders
-     *       --employees (an employees works for a supplier and "specializes" in an item)
-     * 
-     * </pre> 
-     * @return
-     */
-    public static FakeMetadataFacade exampleCase3225() {
-        FakeMetadataStore store = new FakeMetadataStore();
-        FakeMetadataFacade facade = new FakeMetadataFacade(store);
-        
-        // Create models
-        FakeMetadataObject stock = FakeMetadataFactory.createPhysicalModel("stock"); //$NON-NLS-1$
-        FakeMetadataObject xmltest = FakeMetadataFactory.createVirtualModel("xmltest");     //$NON-NLS-1$
-
-        // Create physical groups
-        FakeMetadataObject items = FakeMetadataFactory.createPhysicalGroup("stock.items", stock); //$NON-NLS-1$
-        FakeMetadataObject item_supplier = FakeMetadataFactory.createPhysicalGroup("stock.item_supplier", stock); //$NON-NLS-1$
-        FakeMetadataObject suppliers = FakeMetadataFactory.createPhysicalGroup("stock.suppliers", stock); //$NON-NLS-1$
-        FakeMetadataObject orders = FakeMetadataFactory.createPhysicalGroup("stock.orders", stock); //$NON-NLS-1$
-        FakeMetadataObject employees = FakeMetadataFactory.createPhysicalGroup("stock.employees", stock); //$NON-NLS-1$
-             
-        // Create physical elements
-        List itemElements = FakeMetadataFactory.createElements(items, 
-            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
-
-        //many-to-many join table
-        List itemSupplierElements = FakeMetadataFactory.createElements(item_supplier, 
-            new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-        List supplierElements = FakeMetadataFactory.createElements(suppliers, 
-            new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-        List stockOrders = FakeMetadataFactory.createElements(orders, 
-            new String[] { "orderNum", "itemFK", "supplierFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
-
-        List supplierEmployees = FakeMetadataFactory.createElements(employees, 
-            new String[] { "employeeNum", "supplierNumFK", "specializesInItemNum", "supervisorNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        // Create mapping classes - items doc
-        QueryNode rsQuery = new QueryNode("SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rsItems = FakeMetadataFactory.createVirtualGroup("xmltest.items", xmltest, rsQuery); //$NON-NLS-1$
-
-        QueryNode rsQuery2 = new QueryNode("SELECT stock.suppliers.supplierNum, supplierName, supplierZipCode, stock.item_supplier.itemNum FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery2.addBinding("xmltest.items.itemNum"); //$NON-NLS-1$
-        FakeMetadataObject rsSuppliers = FakeMetadataFactory.createVirtualGroup("xmltest.suppliers", xmltest, rsQuery2); //$NON-NLS-1$
-
-        QueryNode rsQuery3 = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus, itemFK, supplierFK FROM stock.orders WHERE itemFK = ? AND supplierFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery3.addBinding("xmltest.suppliers.itemNum"); //$NON-NLS-1$
-        rsQuery3.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
-        FakeMetadataObject rsOrders = FakeMetadataFactory.createVirtualGroup("xmltest.orders", xmltest, rsQuery3); //$NON-NLS-1$
-
-        QueryNode rsQuery4 = new QueryNode("SELECT employeeNum, firstName, lastName, supervisorNum, specializesInItemNum, supplierNumFK FROM stock.employees WHERE specializesInItemNum = ? AND supplierNumFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        rsQuery4.addBinding("xmltest.suppliers.itemNum"); //$NON-NLS-1$
-        rsQuery4.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
-        FakeMetadataObject rsEmployees = FakeMetadataFactory.createVirtualGroup("xmltest.employees", xmltest, rsQuery4); //$NON-NLS-1$
-
-        // Create mapping classes elements - items doc
-        List rsItemsElements = FakeMetadataFactory.createElements(rsItems, 
-            new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
-
-        List rsSuppliersElements = FakeMetadataFactory.createElements(rsSuppliers, 
-            new String[] { "supplierNum", "supplierName", "supplierZipCode", "itemNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-
-        List rsOrdersElements = FakeMetadataFactory.createElements(rsOrders, 
-            new String[] { "orderNum", "orderDate", "orderQty", "orderStatus", "itemFK", "supplierFK" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsEmployeesElements = FakeMetadataFactory.createElements(rsEmployees, 
-            new String[] { "employeeNum", "firstName", "lastName", "supervisorNum", "specializesInItemNum", "supplierNumFK" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        // MAPPING DOC ======================================================================
-        MappingDocument doc = new MappingDocument(true);
-        MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
-        
-        MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
-        MappingElement itemsA = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
-
-        MappingElement item = itemsA.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
-        item.setSource("xmltest.items");//$NON-NLS-1$
-        item.setMaxOccurrs(-1);
-        item.addAttribute(new MappingAttribute("ItemID", "xmltest.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Name", "xmltest.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
-        item.addChildElement(new MappingElement("Quantity", "xmltest.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        //NESTED STUFF======================================================================
-        MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
-        MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
-        supplier.setSource("xmltest.suppliers");//$NON-NLS-1$
-        supplier.setMaxOccurrs(-1);
-        supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
-        supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$
-        MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
-        order.setSource("xmltest.orders"); //$NON-NLS-1$
-        order.setMaxOccurrs(-1);
-        order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
-        order.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        order.addChildElement(new MappingElement("OrderStatus", "xmltest.orders.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
-            .setMinOccurrs(0);                
-        //NESTED STUFF======================================================================
-        
-        MappingElement employeesWrapper = supplier.addChildElement(new MappingElement("Employees")); //$NON-NLS-1$
-        MappingElement employee = employeesWrapper.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
-        employee.setSource("xmltest.employees"); //$NON-NLS-1$
-        employee.setMaxOccurrs(-1);
-        employee.addAttribute(new MappingAttribute("EmployeeID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        employee.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        employee.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-        employee.addAttribute(new MappingAttribute("SupervisorID", "xmltest.employees.supervisorNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        
-        // END MAPPING DOC ======================================================================
-        
-        // Create virtual docs and doc elements
-        FakeMetadataObject itemsDoc = FakeMetadataFactory.createVirtualGroup("xmltest.itemsDoc", xmltest, doc); //$NON-NLS-1$
-        List docE1 = FakeMetadataFactory.createElements(itemsDoc, 
-            new String[] { "Catalogs",  //$NON-NLS-1$
-                           "Catalogs.Catalog",  //$NON-NLS-1$
-                           "Catalogs.Catalog.items",  //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item",  //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item. at ItemID",  //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Name",  //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Quantity", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier. at SupplierID", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Name", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Zip", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order. at OrderID", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order.OrderDate", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order.OrderQuantity", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order.OrderStatus", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee. at EmployeeID", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee.FirstName", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee.LastName", //$NON-NLS-1$
-                           "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee. at SupervisorID", //$NON-NLS-1$
-        
-            }, 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.INTEGER, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           });
-            
-        // Create mapping classes - baseball players employees doc
-        QueryNode playersNode = new QueryNode("SELECT stock.employees.employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE specializesInItemNum is not null"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject rsPlayers = FakeMetadataFactory.createVirtualGroup("xmltest.players", xmltest, playersNode); //$NON-NLS-1$
-
-        QueryNode managersNode = new QueryNode("SELECT stock.employees.employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE stock.employees.employeeNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
-        managersNode.addBinding("xmltest.players.supervisorNum"); //$NON-NLS-1$
-        FakeMetadataObject rsManagers = FakeMetadataFactory.createVirtualGroup("xmltest.managers", xmltest, managersNode); //$NON-NLS-1$
-
-            // TODO what if elements in criteria weren't fully qualified? see defect 19541
-        QueryNode ownersNode = new QueryNode("SELECT stock.employees.employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE stock.employees.employeeNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$ 
-        ownersNode.addBinding("xmltest.managers.supervisorNum"); //$NON-NLS-1$
-        FakeMetadataObject rsOwners = FakeMetadataFactory.createVirtualGroup("xmltest.owners", xmltest, ownersNode); //$NON-NLS-1$
-
-        // Create mapping classes elements - items doc
-        List rsPlayersElements = FakeMetadataFactory.createElements(rsPlayers, 
-            new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsManagersElements = FakeMetadataFactory.createElements(rsManagers, 
-             new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-        List rsOwnersElements = FakeMetadataFactory.createElements(rsOwners, 
-           new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
-           new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
-
-
-        
-        // MAPPING DOC - baseball players ======================================================================
-        MappingDocument doc2 = new MappingDocument(true);
-        MappingElement root2 = doc2.addChildElement(new MappingElement("BaseballPlayers")); //$NON-NLS-1$
-        
-        MappingElement player = root2.addChildElement(new MappingElement("Player")); //$NON-NLS-1$
-        player.setSource("xmltest.players"); //$NON-NLS-1$
-        player.setMaxOccurrs(-1);
-        player.addAttribute(new MappingAttribute("PlayerID", "xmltest.players.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        player.addChildElement(new MappingElement("FirstName", "xmltest.players.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        player.addChildElement(new MappingElement("LastName", "xmltest.players.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-
-        MappingElement manager = player.addChildElement(new MappingElement("Manager")); //$NON-NLS-1$
-        manager.setSource("xmltest.managers");//$NON-NLS-1$
-        manager.setMaxOccurrs(-1);
-        manager.addAttribute(new MappingAttribute("ManagerID", "xmltest.managers.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        manager.addChildElement(new MappingElement("FirstName", "xmltest.managers.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        manager.addChildElement(new MappingElement("LastName", "xmltest.managers.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
-                
-        MappingElement owner = manager.addChildElement(new MappingElement("Owner")); //$NON-NLS-1$
-        owner.setSource("xmltest.owners"); //$NON-NLS-1$
-        owner.setMaxOccurrs(-1);
-        owner.addAttribute(new MappingAttribute("OwnerID", "xmltest.owners.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
-        owner.addChildElement(new MappingElement("FirstName", "xmltest.owners.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
-        owner.addChildElement(new MappingElement("LastName", "xmltest.owners.lastName")); //$NON-NLS-1$ //$NON-NLS-2$       
-        // END MAPPING DOC ======================================================================
-        
-        // Create virtual docs and doc elements
-        FakeMetadataObject playersDoc = FakeMetadataFactory.createVirtualGroup("xmltest.playersDoc", xmltest, doc2); //$NON-NLS-1$
-        List playersDocElements = FakeMetadataFactory.createElements(playersDoc, 
-            new String[] { "BaseballPlayers",  //$NON-NLS-1$
-                           "BaseballPlayers.Player",  //$NON-NLS-1$
-                           "BaseballPlayers.Player. at PlayerID",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.FirstName",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.LastName",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager. at ManagerID",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager.FirstName",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager.LastName",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager.Owner",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager.Owner. at OwnerID",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager.Owner.FirstName",  //$NON-NLS-1$
-                           "BaseballPlayers.Player.Manager.Owner.LastName",  //$NON-NLS-1$
-        
-            }, 
-            new String[] { DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-                           DataTypeManager.DefaultDataTypes.STRING, 
-            });        
-        
-        
-        
-        // Add all objects to the store
-        store.addObject(stock);
-        store.addObject(items);
-        store.addObject(item_supplier);
-   
-        store.addObject(suppliers);
-        store.addObject(orders);
-        store.addObject(employees);
-        store.addObjects(itemElements);
-        store.addObjects(itemSupplierElements);
-        store.addObjects(supplierElements);
-        store.addObjects(stockOrders);
-        store.addObjects(supplierEmployees);
-     
-        store.addObject(xmltest);
-        store.addObject(rsItems);
-        store.addObject(rsSuppliers);
-        store.addObject(rsOrders);
-        store.addObject(rsEmployees);
-        store.addObject(rsPlayers);
-        store.addObject(rsManagers);
-        store.addObject(rsOwners);
-  
-        store.addObjects(rsItemsElements);
-        store.addObjects(rsSuppliersElements);
-        store.addObjects(rsOrdersElements);
-        store.addObjects(rsEmployeesElements);
-        store.addObjects(rsPlayersElements);
-        store.addObjects(rsManagersElements);
-        store.addObjects(rsOwnersElements);
-
-        store.addObject(itemsDoc);
-        store.addObject(playersDoc);
-        
-        store.addObjects(docE1);
-        store.addObjects(playersDocElements);
-        return facade;
-    }    
-    
-    /**
-     * Create a physical model with default settings.
-     * @param name Name of model
-     * @return FakeMetadataObject Metadata object for model
-     */
-	public static FakeMetadataObject createPhysicalModel(String name) {
-		FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.MODEL);
-		obj.putProperty(FakeMetadataObject.Props.IS_VIRTUAL, Boolean.FALSE);		
-		obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.TRUE);
-		return obj;	
-	}
-	
-    /**
-     * Create a virtual model with default settings.
-     * @param name Name of virtual model
-     * @return FakeMetadataObject Metadata object for model
-     */
-	public static FakeMetadataObject createVirtualModel(String name) {
-		FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.MODEL);
-		obj.putProperty(FakeMetadataObject.Props.IS_VIRTUAL, Boolean.TRUE);
-		return obj;	
-	}
-	
-    /**
-     * Create a physical group with default settings.
-     * @param name Name of physical group, must match model name
-     * @param model Associated model
-     * @return FakeMetadataObject Metadata object for group
-     */
-	public static FakeMetadataObject createPhysicalGroup(String name, FakeMetadataObject model) {
-		FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.GROUP);
-		obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-		obj.putProperty(FakeMetadataObject.Props.IS_VIRTUAL, model.getProperty(FakeMetadataObject.Props.IS_VIRTUAL));
-		obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.TRUE);	
-        obj.putProperty(FakeMetadataObject.Props.TEMP, Boolean.FALSE);
-        obj.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, (name.lastIndexOf(".") == -1)? name : name.substring(name.lastIndexOf(".") + 1) );	 //$NON-NLS-1$ //$NON-NLS-2$
-		return obj;	
-	}
-
-    public static FakeMetadataObject createPhysicalGroup(String name, FakeMetadataObject model, boolean flag) {
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.GROUP);
-        obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-        obj.putProperty(FakeMetadataObject.Props.IS_VIRTUAL, model.getProperty(FakeMetadataObject.Props.IS_VIRTUAL));
-        obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.TRUE); 
-        obj.putProperty(FakeMetadataObject.Props.TEMP, Boolean.FALSE);
-        // actually, the name may be fully qualified, which means, the model + categories + name
-        obj.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, name ); 
-        return obj; 
-    }
-    	
-    /**
-     * Create a virtual group with default settings.
-     * @param name Name of virtual group, must match model name
-     * @param model Associated model
-     * @param plan Appropriate query plan definition object for the virtual group
-     * @return FakeMetadataObject Metadata object for group
-     */
-	public static FakeMetadataObject createVirtualGroup(String name, FakeMetadataObject model, Object plan) {
-		FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.GROUP);
-		obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-		obj.putProperty(FakeMetadataObject.Props.IS_VIRTUAL, model.getProperty(FakeMetadataObject.Props.IS_VIRTUAL));
-		obj.putProperty(FakeMetadataObject.Props.PLAN, plan);
-		obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);		
-        obj.putProperty(FakeMetadataObject.Props.TEMP, Boolean.FALSE);  
-		return obj;
-	}
-
-    /**
-     * Create a temp group with default settings.
-     * @param name Name of virtual group, must match model name
-     * @param model Associated model
-     * @param plan Appropriate query plan definition object for the temp group
-     * @return FakeMetadataObject Metadata object for group
-     */
-    public static FakeMetadataObject createTempGroup(String name, FakeMetadataObject model, Object plan) {
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.GROUP);
-        obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-        obj.putProperty(FakeMetadataObject.Props.IS_VIRTUAL, Boolean.FALSE);
-        obj.putProperty(FakeMetadataObject.Props.PLAN, plan);
-        obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE); 
-        obj.putProperty(FakeMetadataObject.Props.TEMP, Boolean.TRUE);  
-        return obj; 
-    }
-	
-    /**
-     * Create a virtual group that allows updates with default settings.
-     * @param name Name of virtual group, must match model name
-     * @param model Associated model
-     * @param plan Appropriate query plan definition object for the virtual group
-     * @return FakeMetadataObject Metadata object for group
-     */
-	public static FakeMetadataObject createUpdatableVirtualGroup(String name, FakeMetadataObject model, QueryNode plan) {
-		return createUpdatableVirtualGroup(name, model, plan, null);
-	}
-    
-    public static FakeMetadataObject createUpdatableVirtualGroup(String name, FakeMetadataObject model, QueryNode plan, String updatePlan) {
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.GROUP);
-        obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-        obj.putProperty(FakeMetadataObject.Props.IS_VIRTUAL, model.getProperty(FakeMetadataObject.Props.IS_VIRTUAL));
-        obj.putProperty(FakeMetadataObject.Props.PLAN, plan);
-        obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.TRUE);
-        obj.putProperty(FakeMetadataObject.Props.UPDATE_PROCEDURE, updatePlan);
-        obj.putProperty(FakeMetadataObject.Props.INSERT_PROCEDURE, "");
-        obj.putProperty(FakeMetadataObject.Props.DELETE_PROCEDURE, "");
-        return obj;
-    }
-		
-    /**
-     * Create element with default settings.
-     * @param name Name of virtual group, must match model name
-     * @param group Associated group
-     * @param type Type of the element (see DataTypeManager)
-     * @param index Column index in group
-     * @return FakeMetadataObject Metadata object for element
-     */
-    public static FakeMetadataObject createElement(String name, FakeMetadataObject group, String type, int index) {
-    	return createElement(name, group, type, index, true);
-    }
-
-    public static FakeMetadataObject createElement(String name, FakeMetadataObject group, String type, int index, boolean flag) { 
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.ELEMENT);
-        obj.putProperty(FakeMetadataObject.Props.MODEL, group.getProperty(FakeMetadataObject.Props.MODEL));
-        obj.putProperty(FakeMetadataObject.Props.GROUP, group);
-        obj.putProperty(FakeMetadataObject.Props.TYPE, type);
-        
-        obj.putProperty(FakeMetadataObject.Props.SELECT, Boolean.TRUE); 
-        if(type.equals(DataTypeManager.DefaultDataTypes.STRING)) {  
-            obj.putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.TRUE);        
-        } else {
-            obj.putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
-        }   
-        obj.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.TRUE);     
-        obj.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        obj.putProperty(FakeMetadataObject.Props.AUTO_INCREMENT, Boolean.FALSE);
-        obj.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, null);
-        obj.putProperty(FakeMetadataObject.Props.INDEX, new Integer(index));
-        obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.TRUE);
-        obj.putProperty(FakeMetadataObject.Props.LENGTH, "100"); //$NON-NLS-1$
-        
-        int indexOfDot = name.lastIndexOf("."); //$NON-NLS-1$
-        if (flag) {
-            name = name.substring(indexOfDot+1);
-        } else {
-            name = String.valueOf(index);
-        }
-        
-        obj.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, name);
-        return obj; 
-    }
-    
-    /**
-     * Create a set of elements in batch 
-     * @param group The group metadata object
-     * @param names Array of element names 
-     * @param types Array of element types
-     * @return List Ordered list of elements in the group
-     */
-	public static List<FakeMetadataObject> createElements(FakeMetadataObject group, String[] names, String[] types) { 
-		String groupRoot = group.getName() + "."; //$NON-NLS-1$
-		List<FakeMetadataObject> elements = new ArrayList<FakeMetadataObject>();
-		
-		for(int i=0; i<names.length; i++) { 
-            FakeMetadataObject element = createElement(groupRoot + names[i], group, types[i], i);
-			elements.add(element);		
-		}
-		
-		return elements;
-	}
-
-    public static List createElements(FakeMetadataObject group, String[] names, String[] types, boolean flag) { 
-        String groupRoot = group.getName() + "."; //$NON-NLS-1$
-        List elements = new ArrayList();
-        
-        for(int i=0; i<names.length; i++) { 
-            FakeMetadataObject element = createElement(groupRoot + names[i], group, types[i], i, flag);
-            elements.add(element);      
-        }
-        
-        return elements;
-    }
-    	
-    /**
-     * Create a set of elements in batch 
-     * @param group The group metadata object
-     * @param names Array of element names 
-     * @param types Array of element types
-     * @return List Ordered list of elements in the group
-     */
-	public static List createElementsWithDefaults(FakeMetadataObject group, String[] names, String[] types, Object[] defaults) {
-		String groupRoot = group.getName() + "."; //$NON-NLS-1$
-		List elements = new ArrayList();
-		
-		for(int i=0; i<names.length; i++) { 
-            FakeMetadataObject element = createElement(groupRoot + names[i], group, types[i], i);
-            element.setDefaultValue(defaults[i]);
-			elements.add(element);		
-		}
-		
-		return elements;
-	}	
-
-    /**
-     * Create index.  The name will be used as the Object metadataID.
-     * @param name String name of index
-     * @param group the group for the index
-     * @param elements the elements of the index (will be used as if they were
-     * metadata IDs)
-     * @return key metadata object
-     */
-    public static FakeMetadataObject createIndex(String name, FakeMetadataObject group, List elements) { 
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.KEY);
-        obj.putProperty(FakeMetadataObject.Props.KEY_TYPE, FakeMetadataObject.TYPE_INDEX);
-        obj.putProperty(FakeMetadataObject.Props.KEY_ELEMENTS, elements);
-        Collection keys = (Collection)group.getProperty(FakeMetadataObject.Props.KEYS);
-        if (keys == null){
-            keys = new ArrayList();
-            group.putProperty(FakeMetadataObject.Props.KEYS, keys);
-        }
-        keys.add(obj);
-        return obj; 
-    }
-
-	/**
-	 * Create primary key.  The name will be used as the Object metadataID.
-	 * @param name String name of key
-	 * @param group the group for the key
-	 * @param elements the elements of the key (will be used as if they were
-	 * metadata IDs)
-	 * @return key metadata object
-	 */
-	public static FakeMetadataObject createKey(String name, FakeMetadataObject group, List elements) { 
-		FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.KEY);
-        obj.putProperty(FakeMetadataObject.Props.KEY_TYPE, FakeMetadataObject.TYPE_PRIMARY_KEY);
-		obj.putProperty(FakeMetadataObject.Props.KEY_ELEMENTS, elements);
-		Collection keys = (Collection)group.getProperty(FakeMetadataObject.Props.KEYS);
-		if (keys == null){
-			keys = new ArrayList();
-			group.putProperty(FakeMetadataObject.Props.KEYS, keys);
-		}
-		keys.add(obj);
-		return obj; 
-	}
-
-    /**
-     * Create foreign key.  The name will be used as the Object metadataID.
-     * @param name String name of key
-     * @param group the group for the key
-     * @param elements the elements of the key (will be used as if they were
-     * @param primaryKey referenced by this foreign key
-     * metadata IDs)
-     * @return key metadata object
-     */
-    public static FakeMetadataObject createForeignKey(String name, FakeMetadataObject group, List elements, FakeMetadataObject primaryKey) { 
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.KEY);
-        obj.putProperty(FakeMetadataObject.Props.KEY_TYPE, FakeMetadataObject.TYPE_FOREIGN_KEY);
-        obj.putProperty(FakeMetadataObject.Props.KEY_ELEMENTS, elements);
-        obj.putProperty(FakeMetadataObject.Props.REFERENCED_KEY, primaryKey);
-        Collection keys = (Collection)group.getProperty(FakeMetadataObject.Props.KEYS);
-        if (keys == null){
-            keys = new ArrayList();
-            group.putProperty(FakeMetadataObject.Props.KEYS, keys);
-        }
-        keys.add(obj);
-        return obj; 
-    }
-
-    /**
-     * Create access pattern (currently an access pattern is implemented as a type of key).  The name will
-     * be used as the Object metadataID.
-     * @param name String name of key
-     * @param group the group for the access pattern
-     * @param elements the elements of the access pattern (will be used as if they were
-     * metadata IDs)
-     * @return Access pattern metadata object
-     */
-    public static FakeMetadataObject createAccessPattern(String name, FakeMetadataObject group, List elements) { 
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.KEY);
-        obj.putProperty(FakeMetadataObject.Props.KEY_TYPE, FakeMetadataObject.TYPE_ACCESS_PATTERN);
-        obj.putProperty(FakeMetadataObject.Props.KEY_ELEMENTS, elements);
-        Collection keys = (Collection)group.getProperty(FakeMetadataObject.Props.KEYS);
-        if (keys == null){
-            keys = new ArrayList();
-            group.putProperty(FakeMetadataObject.Props.KEYS, keys);
-        }
-        keys.add(obj);
-        return obj; 
-    }
-    
-    /**
-     * Create stored procedure parameter.
-     * @param name Name of parameter
-     * @param direction Direction of parameter
-     * @param type Type of parameter
-     * @param resultSet Result set metadata object or null if type is not result set
-     * @return Metadata object for parameter
-     */
-    public static FakeMetadataObject createParameter(String name, int index, int direction, String type, Object resultSet) {
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.PARAMETER);
-        obj.putProperty(FakeMetadataObject.Props.INDEX, new Integer(index));
-        obj.putProperty(FakeMetadataObject.Props.DIRECTION, new Integer(direction));
-        if(resultSet != null) {
-            obj.putProperty(FakeMetadataObject.Props.RESULT_SET, resultSet);
-            obj.putProperty(FakeMetadataObject.Props.TYPE, DataTypeManager.DefaultDataTypes.INTEGER);
-        } else {
-            obj.putProperty(FakeMetadataObject.Props.TYPE, type);            
-        }
-        obj.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, name);
-        return obj;
-    }
-
-    /**
-     * Create stored procedure.
-     * @param name Name of procedure, must match model name
-     * @param model Metadata object for the model
-     * @param params List of FakeMetadataObject that are the parameters for the procedure
-     * @return Metadata object for stored procedure
-     */
-    public static FakeMetadataObject createStoredProcedure(String name, FakeMetadataObject model, List params) {
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.PROCEDURE);
-        obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-        obj.putProperty(FakeMetadataObject.Props.PARAMS, params);
-        
-        return obj;    
-    }
-    
-    /**
-     * Create virtual sotred procedure.
-     * @param name Name of stored query, must match model name
-     * @param model Metadata object for the model
-     * @param params List of FakeMetadataObject that are the parameters for the procedure
-     * @param queryPlan Object representing query plan
-     * @return Metadata object for stored procedure
-     */
-    public static FakeMetadataObject createVirtualProcedure(String name, FakeMetadataObject model, List params, Object queryPlan) {
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.PROCEDURE);
-        obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-        obj.putProperty(FakeMetadataObject.Props.PARAMS, params);
-        obj.putProperty(FakeMetadataObject.Props.PLAN, queryPlan);
-        return obj;
-    }
-
-    /**
-     * Create a result set.
-     * @param name Name of result set, must match model name
-     * @param model Associated model
-     * @param colNames Result set column names
-     * @param colTypes Result set column types
-     * @return FakeMetadataObject Metadata object for result set
-     */
-    public static FakeMetadataObject createResultSet(String name, FakeMetadataObject model, String[] colNames, String[] colTypes) {
-        FakeMetadataObject obj = new FakeMetadataObject(name, FakeMetadataObject.RESULT_SET);
-        obj.putProperty(FakeMetadataObject.Props.MODEL, model);
-                
-        List columns = new ArrayList();
-        for(int i=0; i<colNames.length; i++) {
-            ElementSymbol col = new ElementSymbol(colNames[i]);
-            col.setType(DataTypeManager.getDataTypeClass(colTypes[i]));
-            FakeMetadataObject colId = new FakeMetadataObject(colNames[i], FakeMetadataObject.ELEMENT);
-            colId.putProperty(FakeMetadataObject.Props.TYPE, colTypes[i]);
-            colId.putProperty(FakeMetadataObject.Props.LENGTH, "10"); //$NON-NLS-1$
-            colId.putProperty(FakeMetadataObject.Props.SELECT, Boolean.TRUE);
-            col.setMetadataID(colId);
-            columns.add(col);
-        }
-        
-        obj.putProperty(FakeMetadataObject.Props.COLUMNS, columns);
-        return obj;
-    }
-
-}

Deleted: branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataObject.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -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 org.teiid.query.unittest;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-public class FakeMetadataObject implements Comparable, Serializable {
-
-	public static final String MODEL = "Model"; //$NON-NLS-1$
-	public static final String GROUP = "Group"; //$NON-NLS-1$
-	public static final String ELEMENT = "Element"; //$NON-NLS-1$
-    public static final String KEY = "Key"; //$NON-NLS-1$
-    public static final String PROCEDURE = "Procedure"; //$NON-NLS-1$
-    public static final String PARAMETER = "Parameter"; //$NON-NLS-1$
-    public static final String RESULT_SET = "ResultSet"; //$NON-NLS-1$
-
-    //KEY TYPES
-    public static final Integer TYPE_PRIMARY_KEY = new Integer(2);
-    public static final Integer TYPE_FOREIGN_KEY = new Integer(3);
-    public static final Integer TYPE_INDEX = new Integer(4);
-    public static final Integer TYPE_ACCESS_PATTERN = new Integer(5);
-
-
-	private String name;
-	private String type;
-	private Object defaultValue;	
-	private Map props = new HashMap();
-	private Properties extensionProps;
-	
-	public FakeMetadataObject(String name, String type) { 
-		this.name = name;
-		this.type = type;
-	}
-
-	public void setDefaultValue(Object defaultValue) {
-		this.defaultValue = defaultValue;
-	}
-
-	public String getName() {
-		return this.name;
-	}
-
-	public String getType() { 
-		return this.type;
-	}
-
-	public Object getDefaultValue() {
-		return this.defaultValue;
-	}
-
-	public void putProperty(String propName, Object value) {
-		props.put(propName, value);
-	}
-	
-	public Object getProperty(String propName) { 
-		return props.get(propName);
-	}
-	
-	public Object getProperty(String propName, Object defaultValue) { 
-        Object result = props.get(propName);
-        if (result == null) {
-            return defaultValue;
-        }
-        return result;
-    }
-		
-	public boolean equals(Object obj) { 
-		if(this == obj) { 
-			return true;
-		}
-		
-		if(obj == null || ! (obj instanceof FakeMetadataObject)) { 
-			return false;
-		}
-		
-		FakeMetadataObject other = (FakeMetadataObject) obj;	
-		return (	this.getType().equals(other.getType()) && 
-					this.getName().equalsIgnoreCase(other.getName()) );
-	}
-	
-	public int hashCode() { 
-		return this.getName().toUpperCase().hashCode();
-	}
-	
-	public int compareTo(Object obj) { 
-		FakeMetadataObject other = (FakeMetadataObject) obj;
-
-        if ( this.getProperty(Props.INDEX) != null &&
-            other.getProperty(Props.INDEX) != null){
-
-            return compareToWithIndices(other);           
-        }
-        return compareToWithHashCodes(other);
-	}
-
-    private int compareToWithIndices(FakeMetadataObject other) { 
-        Integer otherIndex = (Integer)other.getProperty(Props.INDEX);
-        Integer myIndex = (Integer)this.getProperty(Props.INDEX);
-        return myIndex.compareTo(otherIndex);
-    }
-    
-    private int compareToWithHashCodes(FakeMetadataObject other) { 
-            
-        int otherHash = other.hashCode();
-        int myHash = this.hashCode();
-        
-        if(myHash < otherHash) { 
-            return -1;
-        } else if(myHash > otherHash) { 
-            return 1;
-        } else {
-            return 0;
-        }
-    }
-    
-    public void setExtensionProp(String name, String value) {
-		if (this.extensionProps == null) {
-			this.extensionProps = new Properties();
-		}
-		this.extensionProps.setProperty(name, value);
-	}
-    
-    public Properties getExtensionProps() {
-		return extensionProps;
-	}
-	
-	public String toString() { 
-		return getType() + "(" + getName() + ")"; //$NON-NLS-1$ //$NON-NLS-2$
-	}
-	
-	
-	public static class Props { 
-        // Shared properties
-		public static final String IS_VIRTUAL = "isVirtual";  // model/group //$NON-NLS-1$
-		public static final String MODEL = "model";			// element/group/procedure //$NON-NLS-1$
-		public static final String TYPE = "type";			// element/parameter //$NON-NLS-1$
-        public static final String INDEX = "index";           // element/parameter - integer //$NON-NLS-1$
-        public static final String NAME_IN_SOURCE = "nameInSource";  // group/element //$NON-NLS-1$
-	
-		// Model properties
-        public static final String PLAN = "plan";                     // object - query plan //$NON-NLS-1$
-		public static final String UPDATE = "supUpdate";              // Boolean //$NON-NLS-1$
-        public static final String MAX_SET_SIZE = "maxSetSize";       // Integer //$NON-NLS-1$
-
-        // Group properties
-        public static final String TEMP = "temp";                     // Boolean //$NON-NLS-1$
-        public static final String KEYS = "keys";                     // Collection<FakeMetadataObject keys> //$NON-NLS-1$
-		public static final String CARDINALITY = "cardinality";       // Integer - estimated size of table (# of rows) //$NON-NLS-1$
-        public static final String MAT_GROUP = "matGroup";            // FakeMetadataObject - materialization group //$NON-NLS-1$
-        public static final String MAT_STAGE = "matStage";            // FakeMetadataObject - materialization staging group //$NON-NLS-1$
-        public static final String XML_SCHEMAS = "xmlSchemas";        // List<String> - xml schemas for a doc //$NON-NLS-1$
-		
-		// Element properties		
-        public static final String GROUP = "group";                   // FakeMetadataObject group         //$NON-NLS-1$
-		public static final String SELECT = "supSelect";              // Boolean //$NON-NLS-1$
-		public static final String SEARCHABLE_LIKE = "supLike";       // Boolean //$NON-NLS-1$
-		public static final String SEARCHABLE_COMPARE = "supCompare"; // Boolean //$NON-NLS-1$
-		public static final String NULL = "supNull";                  // Boolean //$NON-NLS-1$
-		public static final String AUTO_INCREMENT = "supAutoIncrement";   // Boolean //$NON-NLS-1$
-		public static final String DEFAULT_VALUE = "supDefaultvalue";	// Boolean	 //$NON-NLS-1$
-        public static final String LENGTH = "length";   // Integer   //$NON-NLS-1$
-        public static final String CASE_SENSITIVE = "caseSensitive";   // Boolean //$NON-NLS-1$
-        public static final String SIGNED = "signed";   // Boolean //$NON-NLS-1$
-        public static final String PRECISION = "precision";   // Integer //$NON-NLS-1$
-        public static final String SCALE = "scale";   // Integer //$NON-NLS-1$
-        public static final String RADIX = "radix";   // Integer //$NON-NLS-1$
-        public static final String NATIVE_TYPE = "nativeType";  // String  //$NON-NLS-1$
-        public static final String MAX_VALUE = "maxValue";      // String //$NON-NLS-1$
-        public static final String MIN_VALUE = "minValue";      // String //$NON-NLS-1$
-        public static final String DISTINCT_VALUES = "distinctValues";      // Integer //$NON-NLS-1$
-        public static final String NULL_VALUES = "nullValues";      // Integer //$NON-NLS-1$
-        public static final String MODELED_TYPE = "modeledType";    // String //$NON-NLS-1$
-        public static final String MODELED_BASE_TYPE = "baseType";    // String //$NON-NLS-1$
-        public static final String MODELED_PRIMITIVE_TYPE = "primitiveType";    // String //$NON-NLS-1$
-         
-        // Key properties
-        public static final String KEY_TYPE = "keyType";              // Integer //$NON-NLS-1$
-        public static final String KEY_ELEMENTS = "keyElements";      // List<FakeMetadataObject elements> //$NON-NLS-1$
-        public static final String REFERENCED_KEY = "referencedKey";       // FakeMetadataObject referenced primary key (if this is a fk) //$NON-NLS-1$
-        
-        // Procedure properties
-        public static final String PARAMS = "params";                 // List<FakeMetadataObject parameters> //$NON-NLS-1$
-        public static final String INSERT_PROCEDURE = "insertProcedure"; // string giving the insert procedure //$NON-NLS-1$
-        public static final String UPDATE_PROCEDURE = "updateProcedure"; // string giving the update procedure //$NON-NLS-1$
-        public static final String DELETE_PROCEDURE = "deleteProcedure"; // string giving the delete procedure //$NON-NLS-1$
-        public static final String UPDATE_COUNT = "updateCount";       // integer giving the update count //$NON-NLS-1$
-        
-        // Parameter properties
-        public static final String DIRECTION = "direction";           // integer - see query.sql.lang.SPParameter //$NON-NLS-1$
-        public static final String RESULT_SET = "isRS";               // FakeMetadataObject result set //$NON-NLS-1$
-        
-        // Result set properties
-        public static final String COLUMNS = "columns";               // List<FakeMetadataObject elements> //$NON-NLS-1$
-	}
-
-}

Deleted: branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/unittest/FakeMetadataStore.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,129 +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 org.teiid.query.unittest;
-
-import java.util.*;
-
-public class FakeMetadataStore {
-
-	private Map models = new HashMap();
-	private Map groups = new HashMap();
-	private Map elements = new HashMap();
-    private Map keys = new HashMap();
-    private Map procedures = new HashMap();
-    private Map resultSets = new HashMap();
-
-	public FakeMetadataStore() { 			
-	}
-	
-	public void addObject(FakeMetadataObject object) { 
-		String lookupName = object.getName().toUpperCase();
-		if(object.getType().equals(FakeMetadataObject.ELEMENT)) { 
-			elements.put(lookupName, object); 
-		} else if(object.getType().equals(FakeMetadataObject.GROUP)) { 
-			groups.put(lookupName, object); 
-		} else if(object.getType().equals(FakeMetadataObject.MODEL)) { 
-			models.put(lookupName, object); 		
-        } else if(object.getType().equals(FakeMetadataObject.KEY)) { 
-            keys.put(lookupName, object);   
-        } else if(object.getType().equals(FakeMetadataObject.PROCEDURE)) {
-            procedures.put(lookupName, object);      
-        } else if(object.getType().equals(FakeMetadataObject.RESULT_SET)) {
-            resultSets.put(lookupName, object);
-		} else {
-			throw new IllegalArgumentException("Bad FakeMetadataObject type: " + object.getType()); //$NON-NLS-1$
-		}
-	}
-
-	public void addObjects(Collection objects) { 
-		Iterator iter = objects.iterator();
-		while(iter.hasNext()) { 
-			addObject((FakeMetadataObject) iter.next());
-		}
-	}
-		
-	public FakeMetadataObject findObject(String name, String type) { 
-		String lookupName = name.toUpperCase();
-		if(type.equals(FakeMetadataObject.ELEMENT)) { 
-			return (FakeMetadataObject) elements.get(lookupName); 
-		} else if(type.equals(FakeMetadataObject.GROUP)) { 
-			return (FakeMetadataObject) groups.get(lookupName); 
-		} else if(type.equals(FakeMetadataObject.MODEL)) { 
-			return (FakeMetadataObject) models.get(lookupName); 		
-        } else if(type.equals(FakeMetadataObject.KEY)) { 
-            return (FakeMetadataObject) keys.get(lookupName);         
-        } else if(type.equals(FakeMetadataObject.PROCEDURE)) {
-            return (FakeMetadataObject) procedures.get(lookupName);
-        } else if(type.equals(FakeMetadataObject.RESULT_SET)) {
-            return (FakeMetadataObject) resultSets.get(lookupName);
-		} else {
-			throw new IllegalArgumentException("Bad FakeMetadataObject type: " + type); //$NON-NLS-1$
-		}
-	}
-
-	public List findObjects(String type, String propertyName, Object matchValue) { 
-		Map domain = null;
-		if(type.equals(FakeMetadataObject.ELEMENT)) { 
-			domain = elements; 
-		} else if(type.equals(FakeMetadataObject.GROUP)) { 
-			domain = groups; 
-		} else if(type.equals(FakeMetadataObject.MODEL)) { 
-			domain = models; 
-        } else if(type.equals(FakeMetadataObject.KEY)) { 
-            domain = keys; 
-        } else if(type.equals(FakeMetadataObject.PROCEDURE)) {
-            domain = procedures;
-        } else if(type.equals(FakeMetadataObject.RESULT_SET)) {
-            domain = resultSets;
-		} else {
-			throw new IllegalArgumentException("Bad FakeMetadataObject type: " + type); //$NON-NLS-1$
-		}
-		
-		List found = new ArrayList();
-		
-		Iterator iter = domain.values().iterator();
-		while(iter.hasNext()) { 
-			FakeMetadataObject mdobj = (FakeMetadataObject) iter.next();
-			if(compareWithNull(mdobj.getProperty(propertyName), matchValue)) { 
-				found.add(mdobj);
-			}			
-		}
-		
-		return found;
-	}
-
-
-	public boolean compareWithNull(Object obj1, Object obj2) { 
-		if(obj1 == null) { 
-			if(obj2 == null) { 
-				return true;
-			}
-			return false;
-		}
-		if(obj2 == null) { 
-			return false;
-		}
-		return obj1.equals(obj2);
-	}
-
-}

Modified: branches/as7/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/unittest/RealMetadataFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,13 +22,23 @@
 
 package org.teiid.query.unittest;
 
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Iterator;
 import java.util.List;
 
+import org.teiid.adminapi.Model;
+import org.teiid.adminapi.impl.ModelMetaData;
+import org.teiid.adminapi.impl.SessionMetadata;
 import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.api.exception.query.QueryMetadataException;
 import org.teiid.client.metadata.ParameterInfo;
+import org.teiid.core.TeiidComponentException;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.dqp.internal.process.DQPWorkContext;
 import org.teiid.metadata.Column;
 import org.teiid.metadata.ColumnSet;
 import org.teiid.metadata.ForeignKey;
@@ -43,24 +53,41 @@
 import org.teiid.metadata.BaseColumn.NullType;
 import org.teiid.metadata.Column.SearchType;
 import org.teiid.metadata.ProcedureParameter.Type;
+import org.teiid.metadata.Table.TriggerEvent;
 import org.teiid.query.function.FunctionTree;
+import org.teiid.query.function.SystemFunctionManager;
 import org.teiid.query.function.UDFSource;
 import org.teiid.query.mapping.relational.QueryNode;
+import org.teiid.query.mapping.xml.MappingAttribute;
+import org.teiid.query.mapping.xml.MappingDocument;
+import org.teiid.query.mapping.xml.MappingElement;
+import org.teiid.query.mapping.xml.MappingOutputter;
+import org.teiid.query.mapping.xml.MappingSequenceNode;
 import org.teiid.query.metadata.CompositeMetadataStore;
 import org.teiid.query.metadata.QueryMetadataInterface;
 import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.query.optimizer.FakeFunctionMetadataSource;
 import org.teiid.query.sql.lang.SPParameter;
 
 @SuppressWarnings("nls")
 public class RealMetadataFactory {
 
-    private static TransformationMetadata CACHED_BQT = exampleBQT();
+	public static final SystemFunctionManager SFM = new SystemFunctionManager();
+
+    private static TransformationMetadata CACHED_EXAMPLE1 = example1();
+	private static TransformationMetadata CACHED_BQT = exampleBQT();
+	static TransformationMetadata CACHED_AGGREGATES = exampleAggregates();
         
 	private RealMetadataFactory() { }
 	
     public static TransformationMetadata exampleBQTCached() {
         return CACHED_BQT;
     }
+    
+    public static TransformationMetadata example1Cached() {
+        return CACHED_EXAMPLE1;
+    }
+
     public static MetadataStore exampleBQTStore() {
     	MetadataStore metadataStore = new MetadataStore();
     	
@@ -197,31 +224,31 @@
         Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
         ProcedureParameter rs1p1 = createParameter("intkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);         //$NON-NLS-1$
         ColumnSet<Procedure> rs1 = createResultSet("rs1", new String[] { "IntKey", "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest5 = createStoredProcedure("spTest5", pm1, Arrays.asList(rs1p1), "spTest5"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure spTest5 = createStoredProcedure("spTest5", pm1, Arrays.asList(rs1p1)); //$NON-NLS-1$ //$NON-NLS-2$
         spTest5.setResultSet(rs1);
 
         Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
         ProcedureParameter rs2p1 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
         ProcedureParameter rs2p2 = createParameter("outkey", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
         ColumnSet<Procedure> rs2 = createResultSet("rs2", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest8 = createStoredProcedure("spTest8", pm2, Arrays.asList(rs2p1, rs2p2), "spTest8"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure spTest8 = createStoredProcedure("spTest8", pm2, Arrays.asList(rs2p1, rs2p2)); //$NON-NLS-1$ //$NON-NLS-2$
         spTest8.setResultSet(rs2);
         
         ProcedureParameter rs2p2a = createParameter("outkey", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
         ColumnSet<Procedure> rs2a = createResultSet("rs2", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest8a = createStoredProcedure("spTest8a", pm2, Arrays.asList(rs2p2a), "spTest8a"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure spTest8a = createStoredProcedure("spTest8a", pm2, Arrays.asList(rs2p2a)); //$NON-NLS-1$ //$NON-NLS-2$
         spTest8a.setResultSet(rs2a);
         
         Schema pm4 = createPhysicalModel("pm4", metadataStore); //$NON-NLS-1$
         ProcedureParameter rs4p1 = createParameter("ret", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
         ProcedureParameter rs4p2 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
-        createStoredProcedure("spTest9", pm4, Arrays.asList(rs4p1, rs4p2), "spTest9"); //$NON-NLS-1$ //$NON-NLS-2$
+        createStoredProcedure("spTest9", pm4, Arrays.asList(rs4p1, rs4p2)); //$NON-NLS-1$ //$NON-NLS-2$
         
         Schema pm3 = createPhysicalModel("pm3", metadataStore); //$NON-NLS-1$
         ProcedureParameter rs3p1 = createParameter("inkey", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
         ProcedureParameter rs3p2 = createParameter("outkey", ParameterInfo.INOUT, DataTypeManager.DefaultDataTypes.INTEGER);                 //$NON-NLS-1$
         ColumnSet<Procedure> rs3 = createResultSet("rs3", new String[] { "IntKey", "StringKey"}, new String[] { DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        Procedure spTest11 = createStoredProcedure("spTest11", pm3, Arrays.asList(rs3p1, rs3p2), "spTest11"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure spTest11 = createStoredProcedure("spTest11", pm3, Arrays.asList(rs3p1, rs3p2)); //$NON-NLS-1$ //$NON-NLS-2$
         spTest11.setResultSet(rs3);
         
         //add virtual stored procedures 
@@ -259,7 +286,7 @@
         vsp6.setResultSet(vsprs6);
         
         createStoredProcedure("spRetOut", pm4, Arrays.asList(createParameter("ret", ParameterInfo.RETURN_VALUE, DataTypeManager.DefaultDataTypes.INTEGER),
-        		createParameter("x", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER)), "spRetOut"); //$NON-NLS-1$ //$NON-NLS-2$
+        		createParameter("x", ParameterInfo.OUT, DataTypeManager.DefaultDataTypes.INTEGER))); //$NON-NLS-1$ //$NON-NLS-2$
         
         ColumnSet<Procedure> vsprs7 = createResultSet("TEIIDSP7.vsprs1", new String[] { "StringKey" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
         ProcedureParameter vsp7p1 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
@@ -293,20 +320,20 @@
 		return createTransformationMetadata(exampleBQTStore(), "bqt");	
 	}
     
-
-	public static TransformationMetadata createTransformationMetadata(MetadataStore metadataStore, String vdbName) {
+	public static TransformationMetadata createTransformationMetadata(MetadataStore metadataStore, String vdbName, FunctionTree... functionModels) {
 		CompositeMetadataStore store = new CompositeMetadataStore(metadataStore);
     	VDBMetaData vdbMetaData = new VDBMetaData();
     	vdbMetaData.setName(vdbName); //$NON-NLS-1$
     	vdbMetaData.setVersion(1);
     	List<FunctionTree> udfs = new ArrayList<FunctionTree>();
+    	udfs.addAll(Arrays.asList(functionModels));
     	for (Schema schema : metadataStore.getSchemas().values()) {
-			vdbMetaData.addModel(FakeMetadataFactory.createModel(schema.getName(), schema.isPhysical()));
+			vdbMetaData.addModel(RealMetadataFactory.createModel(schema.getName(), schema.isPhysical()));
 			if (!schema.getFunctions().isEmpty()) {
 				udfs.add(new FunctionTree(schema.getName(), new UDFSource(schema.getFunctions().values()), true));
 			}
 		}
-    	return new TransformationMetadata(vdbMetaData, store, null, FakeMetadataFactory.SFM.getSystemFunctions(), udfs);
+    	return new TransformationMetadata(vdbMetaData, store, null, SFM.getSystemFunctions(), udfs);
 	}
 	
     /** 
@@ -442,6 +469,1061 @@
 
         return createTransformationMetadata(metadataStore, "");
     }
+
+	public static MetadataStore example1Store() {
+		MetadataStore metadataStore = new MetadataStore();
+		// Create models
+		Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+		
+		pm1.addFunction(new FakeFunctionMetadataSource().getFunctionMethods().iterator().next());
+		
+		Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
+		Schema pm3 = createPhysicalModel("pm3", metadataStore); //allows push of SELECT DISTINCT //$NON-NLS-1$
+		Schema pm4 = createPhysicalModel("pm4", metadataStore); //all groups w/ access pattern(s) //$NON-NLS-1$
+		Schema pm5 = createPhysicalModel("pm5", metadataStore); //all groups w/ access pattern(s); model supports join //$NON-NLS-1$
+		Schema pm6 = createPhysicalModel("pm6", metadataStore); //model does not support where all //$NON-NLS-1$
+		Schema vm1 = createVirtualModel("vm1", metadataStore);	 //$NON-NLS-1$
+		Schema vm2 = createVirtualModel("vm2", metadataStore);	 //$NON-NLS-1$
+		Schema xmltest = createVirtualModel("xmltest", metadataStore); //$NON-NLS-1$
+
+		// Create physical groups
+		Table pm1g1 = createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+		Table pm1g2 = createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+		Table pm1g3 = createPhysicalGroup("g3", pm1); //$NON-NLS-1$
+		Table pm1g4 = createPhysicalGroup("g4", pm1); //$NON-NLS-1$
+		Table pm1g5 = createPhysicalGroup("g5", pm1); //$NON-NLS-1$
+		Table pm1g6 = createPhysicalGroup("g6", pm1); //$NON-NLS-1$
+		Table pm1table = createPhysicalGroup("table1", pm1); //$NON-NLS-1$
+		Table pm2g1 = createPhysicalGroup("g1", pm2); //$NON-NLS-1$
+		Table pm2g2 = createPhysicalGroup("g2", pm2); //$NON-NLS-1$
+		Table pm2g3 = createPhysicalGroup("g3", pm2); //$NON-NLS-1$
+		Table pm3g1 = createPhysicalGroup("g1", pm3); //$NON-NLS-1$
+		Table pm3g2 = createPhysicalGroup("g2", pm3); //$NON-NLS-1$
+		Table pm4g1 = createPhysicalGroup("g1", pm4); //$NON-NLS-1$
+		Table pm4g2 = createPhysicalGroup("g2", pm4); //$NON-NLS-1$
+		Table pm5g1 = createPhysicalGroup("g1", pm5); //$NON-NLS-1$
+		Table pm5g2 = createPhysicalGroup("g2", pm5); //$NON-NLS-1$
+		Table pm5g3 = createPhysicalGroup("g3", pm5); //$NON-NLS-1$
+		Table pm6g1 = createPhysicalGroup("g1", pm6); //$NON-NLS-1$
+				
+		// Create physical elements
+		createElements(pm1g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm1g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm1g3, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        List<Column> pm1g4e = createElements(pm1g4,
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        pm1g4e.get(1).setSelectable(false);
+        pm1g4e.get(3).setSelectable(false);
+        List<Column> pm1g5e = createElements(pm1g5,
+            new String[] { "e1" }, //$NON-NLS-1$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING });
+        pm1g5e.get(0).setSelectable(false);
+        createElements(pm1g6,
+            new String[] { "in", "in3" }, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(pm1table, 
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g3, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm3g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
+		createElements(pm3g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
+        List<Column> pm4g1e = createElements(pm4g1, 
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        List<Column> pm4g2e = createElements(pm4g2, 
+            new String[] { "e1", "e2", "e3", "e4", "e5", "e6" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        List<Column> pm5g1e = createElements(pm5g1,
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        List<Column> pm5g2e = createElements(pm5g2,
+			new String[] { "e1", "e2", "e3", "e4", "e5", "e6" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+		createElements(pm5g3,
+	        new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.SHORT });
+        createElements(pm6g1,
+            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        
+
+        // Create access patterns - pm4
+        List<Column> elements = new ArrayList<Column>(1);
+        elements.add(pm4g1e.iterator().next());       
+        createAccessPattern("pm4.g1.ap1", pm4g1, elements); //e1 //$NON-NLS-1$
+        elements = new ArrayList<Column>(2);
+        Iterator<Column> iter = pm4g2e.iterator();
+        elements.add(iter.next());       
+        elements.add(iter.next());       
+        createAccessPattern("pm4.g2.ap1", pm4g2, elements); //e1,e2 //$NON-NLS-1$
+		elements = new ArrayList<Column>(1);
+		elements.add(pm4g2e.get(4)); //"e5"
+		KeyRecord pm4g2ap2 =createAccessPattern("pm4.g2.ap2", pm4g2, elements); //e5 //$NON-NLS-1$
+		// Create access patterns - pm5
+		elements = new ArrayList<Column>(1);
+		elements.add(pm5g1e.iterator().next());
+		createAccessPattern("pm5.g1.ap1", pm5g1, elements); //e1 //$NON-NLS-1$
+		elements = new ArrayList<Column>(2);
+		iter = pm5g2e.iterator();
+		elements.add(iter.next());
+		elements.add(iter.next());
+		createAccessPattern("pm5.g2.ap1", pm5g2, elements); //e1,e2 //$NON-NLS-1$
+		elements = new ArrayList<Column>(1);
+		elements.add(pm5g2e.get(4)); //"e5"
+		createAccessPattern("pm5.g2.ap2", pm5g2, elements); //e5 //$NON-NLS-1$
+
+        // Create temp groups
+        Table tm1g1 = createXmlStagingTable("doc4.tm1.g1", xmltest, new QueryNode("select null, null, null, null, null")); //$NON-NLS-1$
+
+        // Create temp elements - the element "node1" is purposely named to be ambiguous with a document node named "node1"
+        createElements(tm1g1, 
+            new String[] { "e1", "e2", "e3", "e4", "node1"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING });
+            
+		// Create virtual groups
+		QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g1 = createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+
+		QueryNode vm2g1n1 = new QueryNode("SELECT pm1.g1.* FROM pm1.g1, pm1.g2 where pm1.g1.e2 = pm1.g2.e2"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm2g1 = createUpdatableVirtualGroup("g1", vm2, vm2g1n1); //$NON-NLS-1$		
+		
+        QueryNode vm1g1n1_defect10711 = new QueryNode("SELECT * FROM vm1.g1 as X"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g1_defect10711 = createVirtualGroup("g1a", vm1, vm1g1n1_defect10711); //$NON-NLS-1$
+
+        QueryNode vm1g1n1_defect12081 = new QueryNode("SELECT e1, upper(e1) as e1Upper FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g1_defect12081 = createVirtualGroup("g1b", vm1, vm1g1n1_defect12081); //$NON-NLS-1$
+
+        QueryNode vm1g1n1c = new QueryNode("SELECT PARSETIMESTAMP(pm1.g1.e1, 'MMM dd yyyy hh:mm:ss') as e5, e2, e3, e4 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g1c = createVirtualGroup("g1c", vm1, vm1g1n1c); //$NON-NLS-1$
+        
+        QueryNode vm1g2an1 = new QueryNode("SELECT * FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g2a = createVirtualGroup("g2a", vm1, vm1g2an1); //$NON-NLS-1$
+
+		QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g1.e1, pm1.g1.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1=pm1.g2.e1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g2 = createVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
+
+        QueryNode vm1g4n1 = new QueryNode("SELECT e1 FROM pm1.g1 UNION ALL SELECT convert(e2, string) as x FROM pm1.g2 ORDER BY e1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g4 = createVirtualGroup("g4", vm1, vm1g4n1); //$NON-NLS-1$
+	
+        QueryNode vm1g5n1 = new QueryNode("SELECT concat(e1, 'val'), e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g5 = createVirtualGroup("g5", vm1, vm1g5n1); //$NON-NLS-1$
+
+        QueryNode vm1g6n1 = new QueryNode("SELECT concat(e1, 'val') AS e, e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g6 = createVirtualGroup("g6", vm1, vm1g6n1); //$NON-NLS-1$
+
+        QueryNode vm1g7n1 = new QueryNode("SELECT concat(e1, e2) AS e, e2 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g7 = createVirtualGroup("g7", vm1, vm1g7n1); //$NON-NLS-1$
+
+        QueryNode vm1g8n1 = new QueryNode("SELECT concat(e1, 'val') AS e, e2 FROM pm1.g1 ORDER BY e"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g8 = createVirtualGroup("g8", vm1, vm1g8n1); //$NON-NLS-1$
+
+        QueryNode vm1g9n1 = new QueryNode("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1, pm4.g1 WHERE pm1.g1.e1 = pm4.g1.e1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g9 = createVirtualGroup("g9", vm1, vm1g9n1); //$NON-NLS-1$
+
+        QueryNode vm1g10n1 = new QueryNode("SELECT pm1.g1.e1, pm1.g1.e2 FROM pm1.g1, pm4.g2 WHERE pm1.g1.e1 = pm4.g2.e1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g10 = createVirtualGroup("g10", vm1, vm1g10n1); //$NON-NLS-1$
+
+        QueryNode vm1g11n1 = new QueryNode("SELECT * FROM pm4.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g11 = createVirtualGroup("g11", vm1, vm1g11n1); //$NON-NLS-1$
+
+        QueryNode vm1g12n1 = new QueryNode("SELECT DISTINCT * FROM pm3.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g12 = createVirtualGroup("g12", vm1, vm1g12n1); //$NON-NLS-1$
+
+        QueryNode vm1g13n1 = new QueryNode("SELECT DISTINCT * FROM pm3.g1 ORDER BY e1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g13 = createVirtualGroup("g13", vm1, vm1g13n1); //$NON-NLS-1$
+
+        QueryNode vm1g14n1 = new QueryNode("SELECT * FROM pm3.g1 ORDER BY e1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g14 = createVirtualGroup("g14", vm1, vm1g14n1); //$NON-NLS-1$
+   
+        QueryNode vm1g15n1 = new QueryNode("SELECT e1, concat(e1, convert(e2, string)) AS x FROM pm3.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g15 = createVirtualGroup("g15", vm1, vm1g15n1); //$NON-NLS-1$
+
+        QueryNode vm1g16n1 = new QueryNode("SELECT concat(e1, 'val') AS e, e2 FROM pm3.g1 ORDER BY e"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g16 = createVirtualGroup("g16", vm1, vm1g16n1); //$NON-NLS-1$
+
+        QueryNode vm1g17n1 = new QueryNode("SELECT pm3.g1.e1, pm3.g1.e2 FROM pm3.g1 UNION ALL SELECT pm3.g2.e1, pm3.g2.e2 FROM pm3.g2 ORDER BY e2");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g17 = createVirtualGroup("g17", vm1, vm1g17n1); //$NON-NLS-1$
+
+        QueryNode vm1g18n1 = new QueryNode("SELECT (e4 * 100.0) as x FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g18 = createVirtualGroup("g18", vm1, vm1g18n1); //$NON-NLS-1$
+
+        // Transformations with subqueries and correlated subqueries
+        QueryNode vm1g19n1 = new QueryNode("Select * from vm1.g4 where not (e1 in (select e1 FROM vm1.g1 WHERE vm1.g4.e1 = e1))");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g19 = createVirtualGroup("g19", vm1, vm1g19n1); //$NON-NLS-1$
+
+        QueryNode vm1g20n1 = new QueryNode("Select * from vm1.g1 where exists (select e1 FROM vm1.g2 WHERE vm1.g1.e1 = e1)");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g20 = createVirtualGroup("g20", vm1, vm1g20n1); //$NON-NLS-1$
+
+        QueryNode vm1g21n1 = new QueryNode("Select * from pm1.g1 where exists (select e1 FROM pm2.g1 WHERE pm1.g1.e1 = e1)");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g21 = createVirtualGroup("g21", vm1, vm1g21n1); //$NON-NLS-1$
+
+        QueryNode vm1g22n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM vm1.g21 WHERE vm1.g20.e4 = e4 and e4 = 7.0) as E5 from vm1.g20");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g22 = createVirtualGroup("g22", vm1, vm1g22n1); //$NON-NLS-1$
+
+        QueryNode vm1g23n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM vm1.g21 WHERE vm1.g20.e4 = 7.0 and e4 = 7.0) as E5 from vm1.g20");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g23 = createVirtualGroup("g23", vm1, vm1g23n1); //$NON-NLS-1$
+
+        QueryNode vm1g24n1 = new QueryNode("Select * from vm1.g20 where exists (select * FROM vm1.g21 WHERE vm1.g20.e4 = E4)");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g24 = createVirtualGroup("g24", vm1, vm1g24n1); //$NON-NLS-1$
+
+        QueryNode vm1g25n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM pm1.g2 WHERE e1 = 'b') as E5 from pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g25 = createVirtualGroup("g25", vm1, vm1g25n1); //$NON-NLS-1$
+
+        QueryNode vm1g26n1 = new QueryNode("Select e1, e2, e3, e4, (select e4 FROM pm1.g2 WHERE e4 = pm1.g1.e4 and e1 = 'b') as E5 from pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g26 = createVirtualGroup("g26", vm1, vm1g26n1); //$NON-NLS-1$
+
+        //defect 10976
+//        QueryNode vm1g27n1 = new QueryNode("vm1.g27", "SELECT DISTINCT x as a, lower(e1) as x FROM vm1.g28");         //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vm1g27n1 = new QueryNode("SELECT upper(e1) as x, e1 FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g27 = createVirtualGroup("g27", vm1, vm1g27n1); //$NON-NLS-1$
+
+        QueryNode vm1g28n1 = new QueryNode("SELECT DISTINCT x as a, lower(e1) as x FROM vm1.g27");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g28 = createVirtualGroup("g28", vm1, vm1g28n1); //$NON-NLS-1$
+
+        QueryNode vm1g29n1 = new QueryNode("SELECT DISTINCT x, lower(e1) FROM vm1.g27");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g29 = createVirtualGroup("g29", vm1, vm1g29n1); //$NON-NLS-1$
+
+        QueryNode vm1g30n1 = new QueryNode("SELECT DISTINCT e1 as x, e1 as y FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g30 = createVirtualGroup("g30", vm1, vm1g30n1); //$NON-NLS-1$
+
+        QueryNode vm1g31n1 = new QueryNode("SELECT e1 as x, e1 as y FROM pm1.g1 ORDER BY x");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g31 = createVirtualGroup("g31", vm1, vm1g31n1); //$NON-NLS-1$
+
+        QueryNode vm1g32n1 = new QueryNode("SELECT DISTINCT e1 as x, e1 as y FROM pm1.g1 ORDER BY x");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g32 = createVirtualGroup("g32", vm1, vm1g32n1); //$NON-NLS-1$
+
+        QueryNode vm1g33n1 = new QueryNode("SELECT e2 FROM pm1.g1 WHERE 2 = e2");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g33 = createVirtualGroup("g33", vm1, vm1g33n1); //$NON-NLS-1$
+
+        QueryNode vm1g34n1 = new QueryNode("SELECT e1 as e1_, e2 as e2_ FROM pm1.g1 UNION ALL SELECT e1 as e1_, e2 as e2_ FROM pm2.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g34 = createVirtualGroup("g34", vm1, vm1g34n1); //$NON-NLS-1$
+
+        QueryNode vm1g36n1 = new QueryNode("SELECT pm1.g1.e1 as ve1, pm1.g2.e1 as ve2 FROM pm1.g1 LEFT OUTER JOIN /* optional */ pm1.g2 on pm1.g1.e1 = pm1.g2.e1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g36 = createVirtualGroup("g36", vm1, vm1g36n1); //$NON-NLS-1$
+
+        QueryNode vm1g37n1 = new QueryNode("SELECT * from pm4.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g37 = createVirtualGroup("g37", vm1, vm1g37n1); //$NON-NLS-1$
+        vm1g37.setSupportsUpdate(true);
+
+        QueryNode vm1g38n1 = new QueryNode("SELECT a.e1, b.e2 from pm1.g1 as a, pm6.g1 as b where a.e1=b.e1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g38 = createVirtualGroup("g38", vm1, vm1g38n1); //$NON-NLS-1$
+        
+		// Create virtual groups
+		QueryNode vm1g39n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g39 = createUpdatableVirtualGroup("g39", vm1, vm1g39n1, "CREATE PROCEDURE BEGIN LOOP ON (SELECT pm1.g1.e2 FROM pm1.g1 where pm1.g1.e2=3) AS mycursor begin update pm1.g1 set pm1.g1.e1 = input.e1 where pm1.g1.e1 = input.e1; ROWS_UPDATED = ROWS_UPDATED + ROWCOUNT;\nupdate pm1.g1 set pm1.g1.e2 = input.e2 where pm1.g1.e2 = input.e2; END END"); //$NON-NLS-1$ //$NON-NLS-2$
+        
+		// Create virtual elements
+		createElements(vm1g39, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(vm1g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(vm2g1, 
+    		new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g1_defect10711, 
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g1_defect12081, 
+            new String[] { "e1", "e1Upper" }, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g1c, 
+            new String[] { "e5", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.TIMESTAMP, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g2a, 
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(vm1g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(vm1g4,
+			new String[] { "e1" }, //$NON-NLS-1$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g5,
+            new String[] { "expr", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g6,
+            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g7,
+            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g8,
+            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g9,
+            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g10,
+            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g11,
+            new String[] { "e1", "e2", "e3", "e4", "e5", "e6"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g12,
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
+        createElements(vm1g13,
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
+        createElements(vm1g14,
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME, DataTypeManager.DefaultDataTypes.TIMESTAMP });
+        createElements(vm1g15,
+            new String[] { "e1", "x" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g16,
+            new String[] { "e", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE });
+        createElements(vm1g17,
+            new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DATE });
+        createElements(vm1g18,
+            new String[] { "x" }, //$NON-NLS-1$
+            new String[] { DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g19,
+            new String[] { "e1" }, //$NON-NLS-1$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g20,
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g21,
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g22,
+            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g23,
+            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g24,
+            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g25,
+            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g26,
+            new String[] { "e1", "e2", "e3", "e4", "e5" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g27,
+            new String[] { "x", "e1"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g28,
+            new String[] { "a", "x"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g29,
+            new String[] { "x", "expr"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g30,
+            new String[] { "x", "y"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g31,
+            new String[] { "x", "y"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g32,
+            new String[] { "x", "y"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(vm1g33,
+            new String[] { "e2"}, //$NON-NLS-1$  
+            new String[] { DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g34,
+            new String[] { "e1_", "e2_"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+        createElements(vm1g36,
+             new String[] { "ve1", "ve2" }, //$NON-NLS-1$ //$NON-NLS-2$
+             new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        List<Column> vm1g37e = createElements(vm1g37,
+              new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+        createElements(vm1g38,
+              new String[] { "e1", "e2" }, //$NON-NLS-1$ //$NON-NLS-2$
+              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+
+        //Create access patterns on vm1.g37
+        elements = new ArrayList<Column>(1);
+        elements.add(vm1g37e.iterator().next());       
+        createAccessPattern("vm1.g37.ap1", vm1g37, elements); //e1 //$NON-NLS-1$
+        
+        //XML STUFF =============================================
+        Table doc1 = createXmlDocument("doc1", xmltest, exampleDoc1()); //$NON-NLS-1$
+        Table doc2 = createXmlDocument("doc2", xmltest, exampleDoc2()); //$NON-NLS-1$
+        Table doc3 = createXmlDocument("doc3", xmltest, exampleDoc3()); //$NON-NLS-1$
+        Table doc4 = createXmlDocument("doc4", xmltest, exampleDoc4());         //$NON-NLS-1$
+        Table doc5 = createXmlDocument("doc5", xmltest, exampleDoc5()); //$NON-NLS-1$
+        Table doc6 = createXmlDocument("doc6", xmltest, exampleDoc6()); //$NON-NLS-1$
+
+        // Defect 11479 - test ambiguous doc short names
+        createXmlDocument("xmltest2.docA", vm1, exampleDoc1()); //$NON-NLS-1$
+        createXmlDocument("xmltest3.docA", vm1, exampleDoc2()); //$NON-NLS-1$
+
+		createElements(doc1, new String[] { "root", "root.node1", "root.node1.node2", "root.node1.node2.node3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+		createElements(doc2, new String[] { "root", "root.node1", "root.node1.node3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+		createElements(doc3, new String[] { "root", "root.node1.node2", "root.node2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+		createElements(doc4, new String[] { "root", "root. at node6", "root.node1", "root.node1. at node2", "root.node3", "root.node3. at node4", "root.node3.node4", "root.node3.root.node6" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+        createElements(doc5, new String[] { "root", "root.node1", "root.node1.node2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+            
+        // Create mapping classes for xmltest.doc5
+        QueryNode mc1n1 = new QueryNode("SELECT e1 FROM pm1.g1 UNION ALL SELECT e1 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1mc1 = createVirtualGroup("mc1", xmltest, mc1n1); //$NON-NLS-1$
+        createElements(vm1mc1,
+            new String[] { "e1" }, //$NON-NLS-1$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING });
+
+        createElements(doc6, new String[] { "root", "root.node", "root.thenode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+            
+        //XML STUFF =============================================
+
+        // Procedures and stored queries
+        ColumnSet<Procedure> rs1 = createResultSet("pm1.rs1", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        QueryNode sq1n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq1 = createVirtualProcedure("sq1", pm1, null, sq1n1); //$NON-NLS-1$
+        sq1.setResultSet(rs1);
+        
+        ColumnSet<Procedure> rs2 = createResultSet("ret", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs2p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq2.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq2 = createVirtualProcedure("sq2", pm1, Arrays.asList(rs2p2), sq2n1);  //$NON-NLS-1$
+        sq2.setResultSet(rs2);
+
+        ColumnSet<Procedure> rs5 = createResultSet("pm1.r5", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs5p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs5p3 = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        QueryNode sq3n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq3.in UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sq3.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq3 = createVirtualProcedure("sq3", pm1, Arrays.asList(rs5p2, rs5p3), sq3n1);  //$NON-NLS-1$
+        sq3.setResultSet(rs5);
+
+        //For defect 8211 - this stored query has two input params, no return param, and
+        //the input params are PURPOSELY numbered with indices "1" and "3" - see defect 8211
+        ColumnSet<Procedure> rs5a = createResultSet("pm1.r5a", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs5p1a = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs5p2a = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        QueryNode sq3n1a = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq3a.in UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sq3a.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq3a = createVirtualProcedure("sq3a", pm1, Arrays.asList(rs5p1a, rs5p2a), sq3n1a);  //$NON-NLS-1$
+        sq3a.setResultSet(rs5a);
+        //Case 3281 - create procedures with optional parameter(s)
+        
+        //make "in2" parameter optional, make "in3" required but with a default value
+        ColumnSet<Procedure> rs5b = createResultSet("pm1.r5b", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs5p2b = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs5p3b = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        ProcedureParameter rs5p4b = createParameter("in3", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        rs5p3b.setNullType(NullType.Nullable);
+        rs5p4b.setDefaultValue("YYZ"); //$NON-NLS-1$
+        QueryNode sq3n1b = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sq3b.in UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sq3b.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq3b = createVirtualProcedure("sq3b", pm1, Arrays.asList(rs5p2b, rs5p3b, rs5p4b), sq3n1b);  //$NON-NLS-1$
+        sq3b.setResultSet(rs5b);
+        
+        //Make parameters of all different types, all with appropriate default values
+        //Make some parameters required, some optional
+        //Also, fully-qualify the param names
+        ColumnSet<Procedure> rsDefaults = createResultSet("pm1.rDefaults", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rsDefaultsParameterString = createParameter("inString", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        //rsDefaultsParameterString.setNullType(NullType.Nullable);
+        rsDefaultsParameterString.setDefaultValue(new String("x")); //$NON-NLS-1$
+        ProcedureParameter rsParameterBigDecimal = createParameter("inBigDecimal", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BIG_DECIMAL);  //$NON-NLS-1$
+        rsParameterBigDecimal.setNullType(NullType.Nullable);
+        rsParameterBigDecimal.setDefaultValue(new String("13.0")); //$NON-NLS-1$
+        ProcedureParameter rsParameterBigInteger = createParameter("inBigInteger", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BIG_INTEGER);  //$NON-NLS-1$
+        rsParameterBigInteger.setNullType(NullType.Nullable);
+        rsParameterBigInteger.setDefaultValue(new String("13")); //$NON-NLS-1$
+        ProcedureParameter rsParameterBoolean = createParameter("inBoolean", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BOOLEAN);  //$NON-NLS-1$
+        rsParameterBoolean.setNullType(NullType.Nullable);
+        rsParameterBoolean.setDefaultValue(new String("True")); //$NON-NLS-1$
+        ProcedureParameter rsParameterByte = createParameter("inByte", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BYTE);  //$NON-NLS-1$
+        rsParameterByte.setNullType(NullType.Nullable);
+        rsParameterByte.setDefaultValue(new String("1")); //$NON-NLS-1$
+        ProcedureParameter rsParameterChar = createParameter("inChar", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.CHAR);  //$NON-NLS-1$
+        rsParameterChar.setNullType(NullType.Nullable);
+        rsParameterChar.setDefaultValue(new String("q")); //$NON-NLS-1$
+        ProcedureParameter rsParameterDate = createParameter("inDate", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.DATE);  //$NON-NLS-1$
+        rsParameterDate.setNullType(NullType.Nullable);
+        rsParameterDate.setDefaultValue(new String("2003-03-20")); //$NON-NLS-1$
+        ProcedureParameter rsParameterDouble = createParameter("inDouble", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.DOUBLE);  //$NON-NLS-1$
+        rsParameterDouble.setNullType(NullType.Nullable);
+        rsParameterDouble.setDefaultValue(new String("13.0")); //$NON-NLS-1$
+        ProcedureParameter rsParameterFloat = createParameter("inFloat", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.FLOAT);  //$NON-NLS-1$
+        rsParameterFloat.setNullType(NullType.Nullable);
+        rsParameterFloat.setDefaultValue(new String("13")); //$NON-NLS-1$
+        ProcedureParameter rsParameterInteger = createParameter("inInteger", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        rsParameterInteger.setNullType(NullType.Nullable);
+        rsParameterInteger.setDefaultValue(new String("13")); //$NON-NLS-1$
+        ProcedureParameter rsParameterLong = createParameter("inLong", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.LONG);  //$NON-NLS-1$
+        rsParameterLong.setNullType(NullType.Nullable);
+        rsParameterLong.setDefaultValue(new String("13")); //$NON-NLS-1$
+        ProcedureParameter rsParameterShort = createParameter("inShort", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.SHORT);  //$NON-NLS-1$
+        rsParameterShort.setNullType(NullType.Nullable);
+        rsParameterShort.setDefaultValue(new String("13")); //$NON-NLS-1$
+        ProcedureParameter rsParameterTimestamp = createParameter("inTimestamp", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.TIMESTAMP);  //$NON-NLS-1$
+        rsParameterTimestamp.setNullType(NullType.Nullable);
+        rsParameterTimestamp.setDefaultValue(new String("2003-03-20 21:26:00.000000")); //$NON-NLS-1$
+        ProcedureParameter rsParameterTime = createParameter("inTime", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.TIME);  //$NON-NLS-1$
+        rsParameterTime.setNullType(NullType.Nullable);
+        rsParameterTime.setDefaultValue(new String("21:26:00")); //$NON-NLS-1$
+        QueryNode sqDefaultsNode = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e1=pm1.sqDefaults.inString UNION ALL SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sqDefaults.inInteger; END"); //$NON-NLS-1$ //$NON-NLS-2$
+
+        Procedure sqDefaults = createVirtualProcedure("sqDefaults", pm1, //$NON-NLS-1$
+                                                          Arrays.asList( 
+                                                              rsDefaultsParameterString, 
+                                                              rsParameterBigDecimal, 
+                                                              rsParameterBigInteger, 
+                                                              rsParameterBoolean, 
+                                                              rsParameterByte, 
+                                                              rsParameterChar, 
+                                                              rsParameterDate, 
+                                                              rsParameterDouble, 
+                                                              rsParameterFloat, 
+                                                              rsParameterInteger, 
+                                                              rsParameterLong, 
+                                                              rsParameterShort, 
+                                                              rsParameterTimestamp, 
+                                                              rsParameterTime 
+                                                          ), sqDefaultsNode);  
+        sqDefaults.setResultSet(rsDefaults);
+        
+        ColumnSet<Procedure> rsBadDefault = createResultSet("pm1.rBadDefault", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter paramBadDefaultIn = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        paramBadDefaultIn.setNullType(NullType.Nullable);
+        paramBadDefaultIn.setDefaultValue("Clearly Not An Integer"); //$NON-NLS-1$
+        QueryNode sqnBadDefault = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e2=pm1.sqBadDefault.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sqBadDefault = createVirtualProcedure("sqBadDefault", pm1, Arrays.asList(paramBadDefaultIn), sqnBadDefault);  //$NON-NLS-1$
+        
+        //end case 3281
+        
+        ColumnSet<Procedure> rs3 = createResultSet("pm1.rs3", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Procedure sp1 = createStoredProcedure("sp1", pm1, null);  //$NON-NLS-1$ //$NON-NLS-2$
+        sp1.setResultSet(rs3);
+
+        ColumnSet<Procedure> rs4 = createResultSet("pm1.rs4", new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode sqsp1n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sp1()) as x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sqsp1 = createVirtualProcedure("sqsp1", pm1, null, sqsp1n1);  //$NON-NLS-1$
+        sqsp1.setResultSet(rs4);
+
+        ColumnSet<Procedure> rs6 = createResultSet("pm1.rs6", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        QueryNode sq4n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sq1(); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq4 = createVirtualProcedure("sq4", pm1, null, sq4n1);  //$NON-NLS-1$
+        sq4.setResultSet(rs6);
+
+        ColumnSet<Procedure> rs7 = createResultSet("pm1.rs7", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs7p2 = createParameter("in1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode sq5n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sq2(pm1.sq5.in1); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq5 = createVirtualProcedure("sq5", pm1, Arrays.asList( rs7p2 ), sq5n1);  //$NON-NLS-1$
+        sq5.setResultSet(rs7);
+
+        ColumnSet<Procedure> rs8 = createResultSet("pm1.rs8", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        QueryNode sq6n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sq2(\'1\'); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq6 = createVirtualProcedure("sq6", pm1, null, sq6n1);  //$NON-NLS-1$
+        sq6.setResultSet(rs8);
+
+        ColumnSet<Procedure> rs9 = createResultSet("pm1.rs9", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode sq7n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq1()) as x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq7 = createVirtualProcedure("sq7", pm1, null, sq7n1);  //$NON-NLS-1$
+        sq7.setResultSet(rs9);
+
+        ColumnSet<Procedure> rs10 = createResultSet("pm1.rs10", new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs10p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode sq8n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq1()) as x WHERE x.e1=pm1.sq8.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq8 = createVirtualProcedure("sq8", pm1, Arrays.asList( rs10p2 ), sq8n1);  //$NON-NLS-1$
+        sq8.setResultSet(rs10);
+
+        ColumnSet<Procedure> rs11 = createResultSet("pm1.rs11", new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs11p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode sq9n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq2(pm1.sq9.in)) as x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq9 = createVirtualProcedure("sq9", pm1, Arrays.asList( rs11p2 ), sq9n1);  //$NON-NLS-1$
+        sq9.setResultSet(rs11);
+
+        ColumnSet<Procedure> rs12 = createResultSet("pm1.rs12", new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs12p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs12p3 = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        QueryNode sq10n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sq2(pm1.sq10.in)) as x where e2=pm1.sq10.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq10 = createVirtualProcedure("sq10", pm1, Arrays.asList( rs12p2,  rs12p3), sq10n1);  //$NON-NLS-1$
+        sq10.setResultSet(rs12);
+
+        ColumnSet<Procedure> rs13 = createResultSet("pm1.rs13", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs13p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        Procedure sp2 = createStoredProcedure("sp2", pm1, Arrays.asList( rs13p2 ));  //$NON-NLS-1$ //$NON-NLS-2$
+        sp2.setResultSet(rs13);
+
+        ColumnSet<Procedure> rs14 = createResultSet("pm1.rs14", new String[] { "e1"}, new String[] { DataTypeManager.DefaultDataTypes.STRING}); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs14p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs14p3 = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        QueryNode sq11n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM (EXEC pm1.sp2(?)) as x where e2=pm1.sq11.in; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq11 = createVirtualProcedure("sq11", pm1, Arrays.asList( rs14p2,  rs14p3), sq11n1);  //$NON-NLS-1$
+        sq11.setResultSet(rs14);
+
+        ColumnSet<Procedure> rs15 = createResultSet("pm1.rs15", new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs15p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs15p3 = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        QueryNode sq12n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN INSERT INTO pm1.g1 ( e1, e2 ) VALUES( pm1.sq12.in, pm1.sq12.in2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq12 = createVirtualProcedure("sq12", pm1, Arrays.asList( rs15p2, rs15p3 ), sq12n1);  //$NON-NLS-1$
+        sq12.setResultSet(rs15);
+
+        ColumnSet<Procedure> rs16 = createResultSet("pm1.rs16", new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs16p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode sq13n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN INSERT INTO pm1.g1 ( e1, e2 ) VALUES( pm1.sq13.in, 2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq13 = createVirtualProcedure("sq13", pm1, Arrays.asList( rs16p2 ), sq13n1);  //$NON-NLS-1$
+        sq13.setResultSet(rs16);
+
+        ColumnSet<Procedure> rs17 = createResultSet("pm1.rs17", new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs17p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs17p3 = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        QueryNode sq14n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN UPDATE pm1.g1 SET e1 = pm1.sq14.in WHERE e2 = pm1.sq14.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq14 = createVirtualProcedure("sq14", pm1, Arrays.asList( rs17p2, rs17p3 ), sq14n1);  //$NON-NLS-1$
+        sq14.setResultSet(rs17);
+
+        ColumnSet<Procedure> rs18 = createResultSet("pm1.rs17", new String[] { "count" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter rs18p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        ProcedureParameter rs18p3 = createParameter("in2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER);  //$NON-NLS-1$
+        QueryNode sq15n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DELETE FROM pm1.g1 WHERE e1 = pm1.sq15.in AND e2 = pm1.sq15.in2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq15 = createVirtualProcedure("sq15", pm1, Arrays.asList( rs18p2, rs18p3 ), sq15n1);  //$NON-NLS-1$
+        sq15.setResultSet(rs18);
+
+		QueryNode sq16n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN INSERT INTO pm1.g1 ( e1, e2 ) VALUES( 1, 2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
+		createVirtualProcedure("sq16", pm1, null, sq16n1);  //$NON-NLS-1$
+
+        ColumnSet<Procedure> rs19 = createResultSet("pm1.rs19", new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode sq17n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM xmltest.doc1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq17 = createVirtualProcedure("sq17", pm1, null, sq17n1);  //$NON-NLS-1$
+        sq17.setResultSet(rs19);
+
+        createStoredProcedure("sp3", pm1, null);  //$NON-NLS-1$ //$NON-NLS-2$
+
+		ColumnSet<Procedure> rs20 = createResultSet("pm1.rs20", new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode sq18n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM xmltest.doc1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq18 = createVirtualProcedure("sq18", pm1, null, sq18n1); //$NON-NLS-1$
+        sq18.setResultSet(rs20);
+
+        ColumnSet<Procedure> rs21 = createResultSet("pm1.rs21", new String[] { "xml" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter sq19p2 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        QueryNode sq19n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM xmltest.doc4 WHERE root.node1 = param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure sq19 = createVirtualProcedure("sq19", pm1, Arrays.asList( sq19p2 ), sq19n1); //$NON-NLS-1$
+        sq19.setResultSet(rs21);
+
+        ColumnSet<Procedure> rs22 = createResultSet("pm1.rs13", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter rs22p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.BIG_INTEGER);  //$NON-NLS-1$
+        Procedure sp4 = createStoredProcedure("sp4", pm1, Arrays.asList( rs22p2 ));  //$NON-NLS-1$ //$NON-NLS-2$
+        sp4.setResultSet(rs22);
+        
+        // no params or result set at all
+        createStoredProcedure("sp5", pm1, new ArrayList<ProcedureParameter>());  //$NON-NLS-1$ //$NON-NLS-2$
+
+        //virtual stored procedures
+        ColumnSet<Procedure> vsprs1 = vsprs1(); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vspqn1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e2; IF(x = 15) BEGIN BREAK; END END SELECT e1 FROM pm1.g1 where pm1.g1.e2 = x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp1 = createVirtualProcedure("vsp1", pm1, null, vspqn1); //$NON-NLS-1$\
+        vsp1.setResultSet(vsprs1);
+
+        QueryNode vspqn2 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e2; END SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp2 = createVirtualProcedure("vsp2", pm1, null, vspqn2); //$NON-NLS-1$
+        vsp2.setResultSet(vsprs1());
+        
+        QueryNode vspqn3 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp3 = createVirtualProcedure("vsp3", pm1, null, vspqn3); //$NON-NLS-1$
+        vsp3.setResultSet(vsprs1());
+
+        QueryNode vspqn4 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN IF(mycursor.e2 > 10) BEGIN BREAK; END x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp4 = createVirtualProcedure("vsp4", pm1, null, vspqn4); //$NON-NLS-1$
+        vsp4.setResultSet(vsprs1());
+        
+        QueryNode vspqn5 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN IF(mycursor.e2 > 10) BEGIN CONTINUE; END x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp5 = createVirtualProcedure("vsp5", pm1, null, vspqn5); //$NON-NLS-1$
+        vsp5.setResultSet(vsprs1());
+        
+        QueryNode vspqn6 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < 15) BEGIN x=x+1; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp6 = createVirtualProcedure("vsp6", pm1, null, vspqn6); //$NON-NLS-1$
+        vsp6.setResultSet(vsprs1());
+        
+        ProcedureParameter vspp2 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn7 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < 12) BEGIN x=x+pm1.vsp7.param1; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp7 = createVirtualProcedure("vsp7", pm1, Arrays.asList( vspp2 ), vspqn7); //$NON-NLS-1$
+        vsp7.setResultSet(vsprs1());
+
+        ProcedureParameter vspp8 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn8 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < 12) BEGIN x=x+pm1.vsp8.param1; END SELECT e1 FROM pm1.g1 WHERE e2 >= param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp8 = createVirtualProcedure("vsp8", pm1, Arrays.asList( vspp8 ), vspqn8); //$NON-NLS-1$
+        vsp8.setResultSet(vsprs1());
+        
+        ProcedureParameter vspp9 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn9 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x=0; WHILE (x < param1) BEGIN x=x+pm1.vsp9.param1; END SELECT e1 FROM pm1.g1 WHERE e2 >= param1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp9 = createVirtualProcedure("vsp9", pm1, Arrays.asList( vspp9 ), vspqn9); //$NON-NLS-1$
+        vsp9.setResultSet(vsprs1());
+        
+        ProcedureParameter vspp3 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn10 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1 WHERE e2=param1) AS mycursor BEGIN x=mycursor.e2; END END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp10 = createVirtualProcedure("vsp10", pm1, Arrays.asList( vspp3 ), vspqn10); //$NON-NLS-1$
+
+        //invalid
+        QueryNode vspqn11 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN LOOP ON (SELECT e1 FROM pm1.g1) AS mycursor BEGIN END END SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp11 = createVirtualProcedure("vsp11", pm1, null, vspqn11); //$NON-NLS-1$
+        vsp11.setResultSet(vsprs1());
+
+        //invalid
+        QueryNode vspqn12 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN END x=mycursor.e2; SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp12 = createVirtualProcedure("vsp12", pm1, null, vspqn12); //$NON-NLS-1$
+        vsp12.setResultSet(vsprs1());
+
+        ColumnSet<Procedure> vsprs2 = vspp4(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        QueryNode vspqn13 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; LOOP ON (SELECT e1 FROM pm1.g1) AS mycursor BEGIN x=mycursor.e1; END SELECT x, 5; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp13 = createVirtualProcedure("vsp13", pm1, null, vspqn13); //$NON-NLS-1$
+        vsp13.setResultSet(vsprs2);
+
+        QueryNode vspqn14 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1; SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp14 = createVirtualProcedure("vsp14", pm1, null, vspqn14); //$NON-NLS-1$
+        vsp14.setResultSet(vsprs1());
+        
+        QueryNode vspqn15 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable, pm1.g2 WHERE #temptable.e2 = pm1.g2.e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp15 = createVirtualProcedure("vsp15", pm1, null, vspqn15); //$NON-NLS-1$
+        vsp15.setResultSet(vsprs1());
+        
+        QueryNode vspqn16 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT a.e1 FROM (SELECT pm1.g2.e1 FROM #temptable, pm1.g2 WHERE #temptable.e2 = pm1.g2.e2) AS a; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        //QueryNode vspqn16 = new QueryNode("vsp16", "CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT e1 FROM #temptable where e1 in (SELECT pm1.g2.e1 FROM  #temptable, pm1.g2 WHERE #temptable.e2 = pm1.g2.e2); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp16 = createVirtualProcedure("vsp16", pm1, null, vspqn16); //$NON-NLS-1$
+        vsp16.setResultSet(vsprs1());
+
+        QueryNode vspqn17 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; SELECT e1, e2 INTO #temptable FROM pm1.g1; LOOP ON (SELECT e1, e2 FROM #temptable) AS mycursor BEGIN x=mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp17 = createVirtualProcedure("vsp17", pm1, null, vspqn17); //$NON-NLS-1$
+        vsp17.setResultSet(vsprs1());
+        
+        //invalid
+         QueryNode vspqn18 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO temptable FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+         Procedure vsp18 = createVirtualProcedure("vsp18", pm1, null, vspqn18); //$NON-NLS-1$
+         vsp18.setResultSet(vsprs1());
+
+        QueryNode vspqn19 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1; SELECT e1 INTO #temptable FROM pm1.g1; SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp19 = createVirtualProcedure("vsp19", pm1, null, vspqn19); //$NON-NLS-1$
+        vsp19.setResultSet(vsprs1());
+
+        QueryNode vspqn20 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1; INSERT INTO #temptable(e1) VALUES( 'Fourth'); SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp20 = createVirtualProcedure("vsp20", pm1, null, vspqn20); //$NON-NLS-1$
+        vsp20.setResultSet(vsprs1());
+
+        ProcedureParameter vspp21 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn21 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; INSERT INTO #temptable(#temptable.e1, e2) VALUES( 'Fourth', param1); SELECT e1, e2 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp21 = createVirtualProcedure("vsp21", pm1, Arrays.asList( vspp21 ), vspqn21); //$NON-NLS-1$
+        vsp21.setResultSet(vspp4());
+
+        ProcedureParameter vspp22 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn22 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1 where e2 > param1; SELECT e1, e2 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp22 = createVirtualProcedure("vsp22", pm1, Arrays.asList( vspp22 ), vspqn22); //$NON-NLS-1$
+        vsp22.setResultSet(vspp4());
+
+        ProcedureParameter vspp23 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn23 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; SELECT e1, e2 INTO #temptable FROM pm1.g1 where e2 > param1; x = SELECT e1 FROM #temptable WHERE e2=15; SELECT x, 15; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp23 = createVirtualProcedure("vsp23", pm1, Arrays.asList( vspp23 ), vspqn23); //$NON-NLS-1$
+        vsp23.setResultSet(vspp4());
+ 
+        QueryNode vspqn24 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable WHERE #temptable.e2=15; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp24 = createVirtualProcedure("vsp24", pm1, null, vspqn24); //$NON-NLS-1$
+        vsp24.setResultSet(vspp4());
+ 
+        QueryNode vspqn25 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 INTO #temptable FROM pm1.g1 WHERE e1 ='no match'; SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp25 = createVirtualProcedure("vsp25", pm1, null, vspqn25); //$NON-NLS-1$
+        vsp25.setResultSet(vsprs1());
+
+        QueryNode vspqn27 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 from (exec pm1.vsp25())as c; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp27 = createVirtualProcedure("vsp27", pm1, null, vspqn27); //$NON-NLS-1$
+        vsp27.setResultSet(vsprs1());
+
+        QueryNode vspqn28 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT 0 AS e1 ORDER BY e1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp28 = createVirtualProcedure("vsp28", pm1, null, vspqn28); //$NON-NLS-1$
+        vsp28.setResultSet(vsprs1());
+
+        QueryNode vspqn29 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1 ORDER BY e1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp29 = createVirtualProcedure("vsp29", pm1, null, vspqn29); //$NON-NLS-1$
+        vsp29.setResultSet(vsprs1());
+
+        ColumnSet<Procedure> vsprs30 = createResultSet("pm1.vsprs30", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vspqn30 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp30 = createVirtualProcedure("vsp30", pm1, null, vspqn30); //$NON-NLS-1$
+        vsp30.setResultSet(vsprs30);
+
+        ColumnSet<Procedure> vsprs31 = createResultSet("pm1.vsprs31", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vsp31p2 = createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn31 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1 WHERE e2 = pm1.vsp31.p1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp31 = createVirtualProcedure("vsp31", pm1, Arrays.asList(createParameter("p1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER)), vspqn31); //$NON-NLS-1$
+        vsp31.setResultSet(vsprs31);
+
+        QueryNode vspqn38 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer VARIABLES.y; VARIABLES.y=5; EXEC pm1.vsp7(VARIABLES.y); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp38 = createVirtualProcedure("vsp38", pm1, null, vspqn38); //$NON-NLS-1$
+        vsp38.setResultSet(vsprs1());
+  
+        QueryNode vspqn39 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer VARIABLES.x; VARIABLES.x=5; EXEC pm1.vsp7(VARIABLES.x); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp39 = createVirtualProcedure("vsp39", pm1, null, vspqn39); //$NON-NLS-1$
+        vsp39.setResultSet(vsprs1());
+
+        QueryNode vspqn40 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN LOOP ON (SELECT e2 FROM pm1.g1) AS mycursor BEGIN EXEC pm1.vsp41(); END END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp40 = createVirtualProcedure("vsp40", pm1, null, vspqn40); //$NON-NLS-1$
+        vsp40.setResultSet(vsprs1());
+
+        QueryNode vspqn41 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1 FROM pm1.g1 where e2=15; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp41 = createVirtualProcedure("vsp41", pm1, null, vspqn41); //$NON-NLS-1$
+        vsp41.setResultSet(vsprs1());
+
+        vm1g1.setInsertPlan("CREATE PROCEDURE BEGIN ROWS_UPDATED = INSERT INTO pm1.g1(e1, e2, e3, e4) values(INPUT.e1, INPUT.e2, INPUT.e3, INPUT.e4); END"); //$NON-NLS-1$
+        vm1g1.setUpdatePlan("CREATE PROCEDURE BEGIN ROWS_UPDATED = UPDATE pm1.g1 SET e1 = INPUT.e1, e2 = INPUT.e2, e3 = INPUT.e3, e4=INPUT.e4 WHERE TRANSLATE CRITERIA; END"); //$NON-NLS-1$       
+        vm1g1.setDeletePlan("CREATE PROCEDURE BEGIN ROWS_UPDATED = DELETE FROM pm1.g1 WHERE TRANSLATE CRITERIA; END"); //$NON-NLS-1$       
+
+        vm1g37.setInsertPlan("CREATE PROCEDURE BEGIN ROWS_UPDATED = INSERT INTO pm4.g1(e1, e2, e3, e4) values(INPUT.e1, INPUT.e2, INPUT.e3, INPUT.e4); END"); //$NON-NLS-1$
+        vm1g37.setDeletePlan("CREATE PROCEDURE BEGIN ROWS_UPDATED = DELETE FROM pm4.g1 where translate criteria; END"); //$NON-NLS-1$
+        QueryNode vspqn37 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; VARIABLES.x=5; INSERT INTO vm1.g1(e2) values(VARIABLES.x); SELECT ROWCOUNT; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp37 = createVirtualProcedure("vsp37", pm1, null, vspqn37); //$NON-NLS-1$
+        vsp37.setResultSet(vsprs1());
+
+        QueryNode vspqn33 = new QueryNode(new StringBuffer("CREATE VIRTUAL PROCEDURE")  //$NON-NLS-1$//$NON-NLS-2$
+                                                            .append(" BEGIN") //$NON-NLS-1$
+                                                            .append(" SELECT 3 AS temp1 INTO #myTempTable;") //$NON-NLS-1$
+                                                            .append(" SELECT 2 AS temp1 INTO #myTempTable;") //$NON-NLS-1$
+                                                            .append(" SELECT 1 AS temp1 INTO #myTempTable;") //$NON-NLS-1$
+                                                            .append(" SELECT temp1 AS e1 FROM #myTempTable ORDER BY e1;") //$NON-NLS-1$
+                                                            .append(" END").toString() //$NON-NLS-1$
+                                         );
+        Procedure vsp33 = createVirtualProcedure("vsp33", pm1, null, vspqn33); //$NON-NLS-1$
+        vsp33.setResultSet(vsprs1());
+
+        ColumnSet<Procedure> vsprs35 = createResultSet("pm1.vsprs31", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$
+        QueryNode vspqn35 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer VARIABLES.ID; VARIABLES.ID = pm1.vsp35.p1; SELECT e1 FROM pm1.g1 WHERE e2 = VARIABLES.ID; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp35 = createVirtualProcedure("vsp35", pm1, Arrays.asList(vsp31p2), vspqn35); //$NON-NLS-1$
+        vsp35.setResultSet(vsprs35);
+
+        QueryNode vspqn34 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, 0 AS const FROM pm1.g1 ORDER BY const; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp34 = createVirtualProcedure("vsp34", pm1, null, vspqn34); //$NON-NLS-1$
+        vsp34.setResultSet(vspp4());
+
+        QueryNode vspqn45 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable where #temptable.e1 in (SELECT pm1.g2.e1 FROM pm1.g2 ); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp45 = createVirtualProcedure("vsp45", pm1, null, vspqn45); //$NON-NLS-1$
+        vsp45.setResultSet(vsprs1());
+        
+        // Virtual group w/ procedure in transformation, optional params, named parameter syntax
+        QueryNode vspqn47 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp47.param1 IS NOT NULL) BEGIN SELECT 'FOO' as e1, pm1.vsp47.param1 as e2; END ELSE BEGIN SELECT pm1.vsp47.param2 as e1, 2112 as e2; END END"); //$NON-NLS-1$ //$NON-NLS-2$
+        ColumnSet<Procedure> vsprs47 = createResultSet("pm1.vsprs47", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter vspp47_2 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vspp47_2.setNullType(NullType.Nullable);
+        ProcedureParameter vspp47_3 = createParameter("param2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vspp47_3.setNullType(NullType.Nullable);
+        Procedure vsp47 = createVirtualProcedure("vsp47", pm1, Arrays.asList( vspp47_2, vspp47_3 ), vspqn47); //$NON-NLS-1$
+        vsp47.setResultSet(vsprs47);
+        
+        QueryNode vgvpn7 = new QueryNode("SELECT P.e2 as ve3, P.e1 as ve4 FROM (EXEC pm1.vsp47(param1=vm1.vgvp7.ve1, param2=vm1.vgvp7.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
+//        QueryNode vgvpn7 = new QueryNode("vm1.vgvp7", "SELECT P.e2 as ve1, P.e1 as ve2 FROM (EXEC pm1.vsp47(vm1.vgvp7.ve1, vm1.vgvp7.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
+        Table vgvp7 = createVirtualGroup("vgvp7", vm1, vgvpn7); //$NON-NLS-1$
+        Column vgvp7e1 = createElement("ve1", vgvp7, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vgvp7e1.setSelectable(false);
+        Column vgvp7e2 = createElement("ve2", vgvp7, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vgvp7e2.setSelectable(false);
+        Column vgvp7e3 = createElement("ve3", vgvp7, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        Column vgvp7e4 = createElement("ve4", vgvp7, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        
+        
+        //invalid
+        QueryNode vspqn32 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; LOOP ON (SELECT e2 FROM pm1.g1) AS #mycursor BEGIN IF(#mycursor.e2 > 10) BEGIN CONTINUE; END x=#mycursor.e2; END SELECT e1 FROM pm1.g1 WHERE x=e2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp32 = createVirtualProcedure("vsp32", pm1, null, vspqn32); //$NON-NLS-1$
+        vsp32.setResultSet(vsprs1());
+
+        //virtual group with procedure in transformation
+        QueryNode vspqn26 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1 WHERE e2 >= pm1.vsp26.param1 and e1 = pm1.vsp26.param2; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vspp26_1 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        ProcedureParameter vspp26_2 = createParameter("param2", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        ColumnSet<Procedure> vsprs3 = createResultSet("pm1.vsprs3", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        Procedure vsp26 = createVirtualProcedure("vsp26", pm1, Arrays.asList( vspp26_1, vspp26_2 ), vspqn26); //$NON-NLS-1$
+        vsp26.setResultSet(vsprs3);
+        
+		QueryNode vgvpn1 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp1.ve1, vm1.vgvp1.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vgvp1 = createVirtualGroup("vgvp1", vm1, vgvpn1); //$NON-NLS-1$
+		Column vgvp1e1 = createElement("ve1", vgvp1, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vgvp1e1.setSelectable(false);
+        Column vgvp1e2 = createElement("ve2", vgvp1, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vgvp1e2.setSelectable(false);
+        Column vgvp1e3 = createElement("ve3", vgvp1, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+      
+		QueryNode vgvpn2 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp2.ve1, vm1.vgvp2.ve2)) as P where P.e1='a'"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vgvp2 = createVirtualGroup("vgvp2", vm1, vgvpn2); //$NON-NLS-1$
+		Column vgvp2e1 = createElement("ve1", vgvp2, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vgvp2e1.setSelectable(false);
+        Column vgvp2e2 = createElement("ve2", vgvp2, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vgvp2e2.setSelectable(false);
+        Column vgvp2e3 = createElement("ve3", vgvp2, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+   
+		QueryNode vgvpn3 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp3.ve1, vm1.vgvp3.ve2)) as P, pm1.g2 where P.e1=g2.e1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vgvp3 = createVirtualGroup("vgvp3", vm1, vgvpn3); //$NON-NLS-1$
+		Column vgvp3e1 = createElement("ve1", vgvp3, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vgvp3e1.setSelectable(false);
+        Column vgvp3e2 = createElement("ve2", vgvp3, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vgvp3e2.setSelectable(false);
+        createElement("ve3", vgvp3, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+
+		QueryNode vgvpn4 = new QueryNode("SELECT P.e1 as ve3 FROM (EXEC pm1.vsp26(vm1.vgvp4.ve1, vm1.vgvp4.ve2)) as P, vm1.g1 where P.e1=g1.e1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vgvp4 = createVirtualGroup("vgvp4", vm1, vgvpn4); //$NON-NLS-1$
+		Column vgvp4e1 = createElement("ve1", vgvp4, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vgvp4e1.setSelectable(false);
+        Column vgvp4e2 = createElement("ve2", vgvp4, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vgvp4e2.setSelectable(false);
+        createElement("ve3", vgvp4, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        
+		QueryNode vgvpn5 = new QueryNode("SELECT * FROM vm1.vgvp4 where vm1.vgvp4.ve1=vm1.vgvp5.ve1 and  vm1.vgvp4.ve2=vm1.vgvp5.ve2"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vgvp5 = createVirtualGroup("vgvp5", vm1, vgvpn5); //$NON-NLS-1$
+		Column vgvp5e1 = createElement("ve1", vgvp5, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vgvp5e1.setSelectable(false);
+        Column vgvp5e2 = createElement("ve2", vgvp5, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vgvp5e2.setSelectable(false);
+        createElement("ve3", vgvp5, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+
+		QueryNode vgvpn6 = new QueryNode("SELECT P.e1 as ve3, P.e2 as ve4 FROM (EXEC pm1.vsp26(vm1.vgvp6.ve1, vm1.vgvp6.ve2)) as P"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vgvp6 = createVirtualGroup("vgvp6", vm1, vgvpn6); //$NON-NLS-1$
+		Column vgvp6e1 = createElement("ve1", vgvp6, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        vgvp6e1.setSelectable(false);
+        Column vgvp6e2 = createElement("ve2", vgvp6, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vgvp6e2.setSelectable(false);
+        createElement("ve3", vgvp6, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        createElement("ve4", vgvp6, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+
+        //virtual group with two elements. One selectable, one not.
+        QueryNode vm1g35n1 = new QueryNode("SELECT e1, e2 FROM pm1.g1");         //$NON-NLS-1$ //$NON-NLS-2$
+        Table vm1g35 = createVirtualGroup("g35", vm1, vm1g35n1); //$NON-NLS-1$
+        Column vm1g35e1 = createElement("e1", vm1g35, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        vm1g35e1.setSelectable(false);
+        createElement("e2", vm1g35, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+		
+        ColumnSet<Procedure> vsprs36 = createResultSet("pm1.vsprs36", new String[] { "x" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vsp36p2 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn36 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x = pm1.vsp36.param1 * 2; SELECT x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp36 = createVirtualProcedure("vsp36", pm1, Arrays.asList( vsp36p2 ), vspqn36); //$NON-NLS-1$
+        vsp36.setResultSet(vsprs36);
+
+        ColumnSet<Procedure> vsprs42 = createResultSet("pm1.vsprs42", new String[] { "x" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$
+        ProcedureParameter vsp42p2 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn42 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp42 = createVirtualProcedure("vsp42", pm1, Arrays.asList( vsp42p2 ), vspqn42); //$NON-NLS-1$
+        vsp42.setResultSet(vsprs42);
+
+        ProcedureParameter vspp44 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn44 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT pm1.vsp44.param1 INTO #temptable; SELECT e1 from pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$    
+        Procedure vsp44 = createVirtualProcedure("vsp44", pm1, Arrays.asList( vspp44 ), vspqn44); //$NON-NLS-1$
+        vsp44.setResultSet(vsprs1());
+
+        ProcedureParameter vspp43 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn43 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN exec pm1.vsp44(pm1.vsp43.param1); END"); //$NON-NLS-1$ //$NON-NLS-2$    
+        Procedure vsp43 = createVirtualProcedure("vsp43", pm1, Arrays.asList( vspp43 ), vspqn43); //$NON-NLS-1$
+        vsp43.setResultSet(vsprs1());
+        
+        QueryNode vspqn46 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table #temptable (e1 string, e2 string); LOOP ON (SELECT e1 FROM pm1.g1) AS mycursor BEGIN select mycursor.e1, a.e1 as e2 into #temptable from (SELECT pm1.g1.e1 FROM pm1.g1 where pm1.g1.e1 = mycursor.e1) a; END SELECT e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp46 = createVirtualProcedure("vsp46", pm1, null, vspqn46); //$NON-NLS-1$
+        vsp46.setResultSet(vsprs1());
+        
+        ColumnSet<Procedure> vsp48rs = createResultSet("pm1vsp48.rs", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcedureParameter vsp48p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode vspqn48 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; SELECT e1 FROM (EXEC pm1.sq2(pm1.vsp48.in)) as e; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp48 = createVirtualProcedure("vsp48", pm1, Arrays.asList( vsp48p2 ), vspqn48); //$NON-NLS-1$
+        vsp48.setResultSet(vsp48rs);
+        
+        ColumnSet<Procedure> vsp49rs = createResultSet("pm1vsp49.rs", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+        QueryNode vspqn49 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; EXEC pm1.sq2(x); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp49 = createVirtualProcedure("vsp49", pm1, null, vspqn49); //$NON-NLS-1$
+        vsp49.setResultSet(vsp49rs);
+
+        ColumnSet<Procedure> vsp50rs = createResultSet("pm1vsp50.rs", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
+        QueryNode vspqn50 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; SELECT e1 FROM (EXEC pm1.sq2(x)) as e; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp50 = createVirtualProcedure("vsp50", pm1, null, vspqn50); //$NON-NLS-1$
+        vsp50.setResultSet(vsp50rs);
+        
+        ColumnSet<Procedure> vsp51rs = createResultSet("pm1vsp51.rs", new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
+        QueryNode vspqn51 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; LOOP ON (SELECT e1 FROM (EXEC pm1.sq2(x)) as e) AS c BEGIN x = x || 'b'; END SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp51 = createVirtualProcedure("vsp51", pm1, null, vspqn51); //$NON-NLS-1$
+        vsp51.setResultSet(vsp51rs);
+        
+        ColumnSet<Procedure> vsp52rs = createResultSet("pm1vsp52.rs", new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
+        QueryNode vspqn52 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'c'; x = SELECT e1 FROM (EXEC pm1.sq2(x)) as e; SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp52 = createVirtualProcedure("vsp52", pm1, null, vspqn52); //$NON-NLS-1$
+        vsp52.setResultSet(vsp52rs);
+
+        ColumnSet<Procedure> vsp53rs = createResultSet("pm1vsp53.rs", new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcedureParameter vsp53p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode vspqn53 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'b'; LOOP ON (SELECT e1 FROM (EXEC pm1.sq2(pm1.vsp53.in)) as e) AS c BEGIN x = x || 'b'; END SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp53 = createVirtualProcedure("vsp53", pm1, Arrays.asList( vsp53p2 ), vspqn53); //$NON-NLS-1$
+        vsp53.setResultSet(vsp53rs);
+
+        ColumnSet<Procedure> vsp54rs = createResultSet("pm1vsp54.rs", new String[] { "result" }, new String[] { DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ 
+        ProcedureParameter vsp54p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        QueryNode vspqn54 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN DECLARE string x; x = 'c'; x = SELECT e1 FROM (EXEC pm1.sq2(pm1.vsp54.in)) as e; SELECT x AS result; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp54 = createVirtualProcedure("vsp54", pm1, Arrays.asList( vsp54p2 ), vspqn54); //$NON-NLS-1$
+        vsp54.setResultSet(vsp54rs);
+        
+        ProcedureParameter vspp55 = createParameter("param1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn55 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN select e1, param1 as a from vm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp55 = createVirtualProcedure("vsp55", pm1, Arrays.asList( vspp55 ), vspqn55); //$NON-NLS-1$
+        vsp55.setResultSet(vsprs1());
+
+        QueryNode vspqn56 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp56 = createVirtualProcedure("vsp56", pm1, null, vspqn56); //$NON-NLS-1$
+        vsp56.setResultSet(vsprs1());
+
+        QueryNode vspqn57 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; SELECT #temptable.e1 FROM #temptable order by #temptable.e1; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp57 = createVirtualProcedure("vsp57", pm1, null, vspqn57); //$NON-NLS-1$
+        vsp57.setResultSet(vsprs1());
+        
+        ProcedureParameter vspp58 = createParameter("inp", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        QueryNode vspqn58 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT vsp58.inp; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp58 = createVirtualProcedure("vsp58", pm1, Arrays.asList( vspp58 ), vspqn58); //$NON-NLS-1$
+        vsp58.setResultSet(vsprs1());
+        
+        QueryNode vspqn59 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temp FROM pm5.g3;INSERT INTO #temp (e1, e2) VALUES('integer',1); END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp59 = createVirtualProcedure("vsp59", pm6, null, vspqn59); //$NON-NLS-1$
+        vsp59.setResultSet(vsprs1());
+        
+        QueryNode vspqn60 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table temp_table (column1 string);insert into temp_table (column1) values ('First');insert into temp_table (column1) values ('Second');insert into temp_table (column1) values ('Third');select * from temp_table; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp60 = createVirtualProcedure("vsp60", pm1, null, vspqn60); //$NON-NLS-1$
+        vsp60.setResultSet(vsprs1());
+
+        QueryNode vspqn61 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table temp_table (column1 string);insert into temp_table (column1) values ('First');drop table temp_table;create local temporary table temp_table (column1 string);insert into temp_table (column1) values ('First');insert into temp_table (column1) values ('Second');insert into temp_table (column1) values ('Third');select * from temp_table; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp61 = createVirtualProcedure("vsp61", pm1, null, vspqn61); //$NON-NLS-1$
+        vsp61.setResultSet(vsprs1());
+        
+        QueryNode vspqn62 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN create local temporary table temp_table (column1 string); select e1 as column1 into temp_table from pm1.g1;select * from temp_table; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp62 = createVirtualProcedure("vsp62", pm1, null, vspqn62); //$NON-NLS-1$
+        vsp62.setResultSet(vsprs1());
+        
+        QueryNode vspqn63 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN declare string o; if(1>0) begin declare string a; a='b'; o=a; end if(1>0) begin declare string a; a='c'; o=a; end  select o; END"); //$NON-NLS-1$ //$NON-NLS-2$
+        Procedure vsp63 = createVirtualProcedure("vsp63", pm1, null, vspqn63); //$NON-NLS-1$
+        vsp63.setResultSet(vsprs1());
+        
+        return metadataStore;
+	}
+	
+	public static TransformationMetadata example1() {
+        return createTransformationMetadata(example1Store(), "example1");
+	}
+
+	private static ColumnSet<Procedure> vspp4() {
+		return createResultSet("pm1.vsprs2", new String[] { "e1", "const" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+	}
+
+	private static ColumnSet<Procedure> vsprs1() {
+		return createResultSet("pm1.vsprs1", new String[] { "e1" }, new String[] { DataTypeManager.DefaultDataTypes.STRING });
+	}
     
 	/**
 	 * Create primary key.  The name will be used as the Object metadataID.
@@ -467,6 +1549,9 @@
 		case Unique:
 			group.getUniqueKeys().add(key);
 			break;
+		case AccessPattern:
+			group.getAccessPatterns().add(key);
+			break;
 		default:
 			throw new AssertionError("TODO");
 		}
@@ -517,6 +1602,7 @@
 		model.addTable(table);
 		table.setSupportsUpdate(true);
 		table.setNameInSource((fullyQualify || name.lastIndexOf(".") == -1)? name : name.substring(name.lastIndexOf(".") + 1));  //$NON-NLS-1$ //$NON-NLS-2$
+		table.setTableType(org.teiid.metadata.Table.Type.Table);
 		return table;
 	}
 
@@ -532,10 +1618,38 @@
         table.setName(name);
         model.addTable(table);
         table.setVirtual(true);
+        table.setTableType(org.teiid.metadata.Table.Type.View);
         table.setSelectTransformation(plan.getQuery());
+    	table.setBindings(plan.getBindings());
 		return table;
 	}
+	
+	public static Table createXmlStagingTable(String name, Schema model, QueryNode plan) {
+		Table table = createVirtualGroup(name, model, plan);
+        table.setTableType(org.teiid.metadata.Table.Type.XmlStagingTable);
+        return table;
+	}
+	
+	public static Table createXmlDocument(String name, Schema model, MappingDocument plan) {
+		String doc = docToString(plan);
+		Table table = createVirtualGroup(name, model, new QueryNode(doc));
+		table.setTableType(org.teiid.metadata.Table.Type.Document);
+		table.setColumns(new ArrayList<Column>(2));
+		return table;
+	}
 
+	public static String docToString(MappingDocument plan) {
+		MappingOutputter out = new MappingOutputter();
+        StringWriter stream = new StringWriter();
+        try {
+			out.write(plan, new PrintWriter(stream));
+		} catch (IOException e) {
+			throw new RuntimeException(e);
+		}
+		String doc = stream.toString();
+		return doc;
+	}
+
     /**
      * Create a virtual group that allows updates with default settings.
      */
@@ -623,10 +1737,9 @@
      * @param name Name of procedure, must match model name
      * @param model Metadata object for the model
      * @param params List of FakeMetadataObject that are the parameters for the procedure
-     * @param callableName Callable name of procedure, usually same as procedure name
      * @return Metadata object for stored procedure
      */
-    public static Procedure createStoredProcedure(String name, Schema model, List<ProcedureParameter> params, String callableName) {
+    public static Procedure createStoredProcedure(String name, Schema model, List<ProcedureParameter> params) {
     	Procedure proc = new Procedure();
     	proc.setName(name);
     	if (params != null) {
@@ -650,7 +1763,7 @@
      * @return Metadata object for stored procedure
      */
     public static Procedure createVirtualProcedure(String name, Schema model, List<ProcedureParameter> params, QueryNode queryPlan) {
-    	Procedure proc = createStoredProcedure(name, model, params, null);
+    	Procedure proc = createStoredProcedure(name, model, params);
     	proc.setVirtual(true);
     	proc.setQueryPlan(queryPlan.getQuery());
         return proc;
@@ -667,5 +1780,950 @@
         }
         return rs;
     }
+    
+    public static KeyRecord createAccessPattern(String name, Table group, List<Column> elements) { 
+    	return createKey(org.teiid.metadata.KeyRecord.Type.AccessPattern, name, group, elements);
+    }
+    
+    private static MappingDocument exampleDoc1() {
+        MappingDocument doc = new MappingDocument(false);
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+        MappingElement node1 = root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
+        MappingElement node2 = node1.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
+        node2.addChildElement(new MappingElement("node3")); //$NON-NLS-1$        
+        return doc;
+    }
 
+    private static MappingDocument exampleDoc2() {
+        
+        MappingDocument doc = new MappingDocument(false);
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+        MappingElement node1 = root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
+        
+        MappingSequenceNode node2 = node1.addSequenceNode(new MappingSequenceNode());    
+        node2.addChildElement(new MappingElement("node3")); //$NON-NLS-1$
+        root.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
+        return doc;
+    }
+
+    // has ambiguous short and long names
+    private static MappingDocument exampleDoc3() {
+        MappingDocument doc = new MappingDocument(false);
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+        MappingSequenceNode node1 = root.addSequenceNode(new MappingSequenceNode());    
+        node1.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
+        root.addChildElement(new MappingElement("node2")); //$NON-NLS-1$
+        return doc;
+    }
+    
+   
+    // has attributes and elements
+    private static MappingDocument exampleDoc4() {
+        
+        MappingDocument doc = new MappingDocument(false);
+        
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+        root.addAttribute(new MappingAttribute("node6")); //$NON-NLS-1$
+        root.addStagingTable("xmltest.doc4.tm1.g1"); //$NON-NLS-1$
+        
+        MappingElement node1 =root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
+        node1.addAttribute(new MappingAttribute("node2")); //$NON-NLS-1$
+        
+        MappingElement node3 =root.addChildElement(new MappingElement("node3")); //$NON-NLS-1$
+        node3.addAttribute(new MappingAttribute("node4")); //$NON-NLS-1$
+        
+        MappingElement node5 = node3.addChildElement(new MappingElement("node4")); //$NON-NLS-1$
+        MappingElement duplicateRoot = node5.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+        duplicateRoot.addChildElement(new MappingElement("node6")); //$NON-NLS-1$        
+        return doc;
+    }    
+
+    // has a union in the mapping class
+    private static MappingDocument exampleDoc5() {
+        MappingDocument doc = new MappingDocument(false);
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+        MappingElement node1 = root.addChildElement(new MappingElement("node1")); //$NON-NLS-1$
+        node1.addChildElement(new MappingElement("node2","xmltest.mc1.e1")); //$NON-NLS-1$ //$NON-NLS-2$
+        node1.setSource("xmltest.mc1"); //$NON-NLS-1$
+        node1.setMaxOccurrs(-1);
+        return doc;
+    }	
+    
+    // has two elements with common suffix, but not ambiguous
+    private static MappingDocument exampleDoc6() {
+        MappingDocument doc = new MappingDocument(false);
+        MappingElement root = doc.addChildElement(new MappingElement("root")); //$NON-NLS-1$
+
+        root.addChildElement(new MappingElement("node")); //$NON-NLS-1$
+        root.addChildElement(new MappingElement("thenode")); //$NON-NLS-1$
+        return doc;
+    }
+
+	public static VDBMetaData example1VDB() {
+		VDBMetaData vdb = new VDBMetaData();
+		vdb.setName("example1");
+		vdb.setVersion(1);
+		vdb.addModel(RealMetadataFactory.createModel("pm1", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm2", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm3", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm4", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm5", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm6", true));
+		vdb.addModel(RealMetadataFactory.createModel("vm1", false));
+		vdb.addModel(RealMetadataFactory.createModel("vm2", false));
+		vdb.addModel(RealMetadataFactory.createModel("tm1", false));
+		
+		return vdb;
+	}
+
+	public static VDBMetaData exampleBQTVDB() {
+		VDBMetaData vdb = new VDBMetaData();
+		vdb.setName("example1");
+		vdb.setVersion(1);
+		vdb.addModel(RealMetadataFactory.createModel("BQT1", true));
+		vdb.addModel(RealMetadataFactory.createModel("BQT2", true));
+		vdb.addModel(RealMetadataFactory.createModel("BQT3", true));
+		vdb.addModel(RealMetadataFactory.createModel("LOB", true));
+		vdb.addModel(RealMetadataFactory.createModel("VQT", false));
+		vdb.addModel(RealMetadataFactory.createModel("pm1", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm2", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm3", true));
+		vdb.addModel(RealMetadataFactory.createModel("pm4", true));
+		
+		return vdb;
+	}
+
+	public static VDBMetaData exampleMultiBindingVDB() {
+		VDBMetaData vdb = new VDBMetaData();
+		vdb.setName("exampleMultiBinding");
+		vdb.setVersion(1);
+		
+		ModelMetaData model = new ModelMetaData();
+		model.setName("MultiModel");
+		model.setModelType(Model.Type.PHYSICAL);
+		model.setVisible(true);
+		
+		model.setSupportsMultiSourceBindings(true);
+		vdb.addModel(model);
+		vdb.addModel(RealMetadataFactory.createModel("Virt", false));
+		
+		return vdb;
+	}
+
+	public static DQPWorkContext buildWorkContext(TransformationMetadata metadata) {
+		return buildWorkContext(metadata, metadata.getVdbMetaData());
+	}
+
+	public static DQPWorkContext buildWorkContext(QueryMetadataInterface metadata, VDBMetaData vdb) {
+		DQPWorkContext workContext = new DQPWorkContext();
+		SessionMetadata session = new SessionMetadata();
+		workContext.setSession(session);
+		session.setVDBName(vdb.getName()); 
+		session.setVDBVersion(vdb.getVersion()); 
+		session.setSessionId(String.valueOf(1));
+		session.setUserName("foo"); //$NON-NLS-1$
+		session.setVdb(vdb);
+	    workContext.getVDB().addAttchment(QueryMetadataInterface.class, metadata);
+	    if (metadata instanceof TransformationMetadata) {
+	    	workContext.getVDB().addAttchment(TransformationMetadata.class, (TransformationMetadata)metadata);
+	    }
+	    DQPWorkContext.setWorkContext(workContext);
+		return workContext;
+	}
+
+	public static ModelMetaData createModel(String name, boolean source) {
+		ModelMetaData model = new ModelMetaData();
+		model.setName(name);
+		if (source) {
+			model.setModelType(Model.Type.PHYSICAL);
+		}
+		else {
+			model.setModelType(Model.Type.VIRTUAL);
+		}
+		model.setVisible(true);
+		model.setSupportsMultiSourceBindings(false);
+		model.addSourceMapping(name, name, null);
+		
+		return model;
+	}
+
+	public static TransformationMetadata exampleBitwise() { 
+		MetadataStore store = new MetadataStore();
+	    Schema phys = createPhysicalModel("phys", store); //$NON-NLS-1$
+	    Table t = createPhysicalGroup("t", phys); //$NON-NLS-1$
+	    createElements(t, 
+	                                new String[] { "ID", "Name", "source_bits" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	                                new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+	
+	    Schema virt = createVirtualModel("virt", store); //$NON-NLS-1$
+	    ColumnSet<Procedure> rs = createResultSet("rs", new String[] { "ID", "Name", "source_bits" }, new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	    QueryNode qn = new QueryNode("CREATE VIRTUAL PROCEDURE " //$NON-NLS-1$
+		  + "BEGIN " //$NON-NLS-1$
+		  + "        DECLARE integer VARIABLES.BITS;" //$NON-NLS-1$
+		  + "        create local temporary table #temp (id integer, name string, bits integer);" //$NON-NLS-1$
+		  + "        LOOP ON (SELECT DISTINCT phys.t.ID, phys.t.Name FROM phys.t) AS idCursor" //$NON-NLS-1$
+		  + "        BEGIN" //$NON-NLS-1$
+		  + "                VARIABLES.BITS = 0;" //$NON-NLS-1$
+		  + "                LOOP ON (SELECT phys.t.source_bits FROM phys.t WHERE phys.t.ID = idCursor.id) AS bitsCursor" //$NON-NLS-1$
+		  + "                BEGIN" //$NON-NLS-1$
+		  + "                        VARIABLES.BITS = bitor(VARIABLES.BITS, bitsCursor.source_bits);" //$NON-NLS-1$
+		  + "                END" //$NON-NLS-1$
+		  + "                SELECT idCursor.id, idCursor.name, VARIABLES.BITS INTO #temp;" //$NON-NLS-1$
+		  + "        END" //$NON-NLS-1$
+		  + "        SELECT ID, Name, #temp.BITS AS source_bits FROM #temp;" //$NON-NLS-1$                                          
+		  + "END"); //$NON-NLS-1$ 
+	    Procedure proc = createVirtualProcedure("agg", virt, null, qn); //$NON-NLS-1$
+	    proc.setResultSet(rs);
+	
+	    return createTransformationMetadata(store, "bitwise");
+	}
+
+	public static void setCardinality(String group, int cardinality, QueryMetadataInterface metadata) throws QueryMetadataException, TeiidComponentException {
+		if (metadata instanceof TransformationMetadata) {
+			Table t = (Table)metadata.getGroupID(group);
+			t.setCardinality(cardinality);
+		} else {
+			throw new RuntimeException("unknown metadata"); //$NON-NLS-1$
+		}
+	}
+
+	public static TransformationMetadata exampleAggregatesCached() {
+	    return CACHED_AGGREGATES;
+	}
+
+	public static TransformationMetadata example3() {
+		MetadataStore metadataStore = new MetadataStore();
+		// Create models
+		Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+		Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
+	    Schema pm3 = createPhysicalModel("pm3", metadataStore); //$NON-NLS-1$
+	
+		// Create physical groups
+		Table pm1g1 = createPhysicalGroup("cat1.cat2.cat3.g1", pm1); //$NON-NLS-1$
+		Table pm1g2 = createPhysicalGroup("cat1.g2", pm1); //$NON-NLS-1$
+		Table pm1g3 = createPhysicalGroup("cat2.g3", pm1); //$NON-NLS-1$
+		Table pm2g1 = createPhysicalGroup("cat1.g1", pm2); //$NON-NLS-1$
+		Table pm2g2 = createPhysicalGroup("cat2.g2", pm2); //$NON-NLS-1$
+		Table pm2g3 = createPhysicalGroup("g3", pm2); //$NON-NLS-1$
+	    Table pm2g4 = createPhysicalGroup("g4", pm3);		 //$NON-NLS-1$
+		Table pm2g5 = createPhysicalGroup("cat3.g1", pm2); //$NON-NLS-1$
+						
+		// Create physical elements
+		createElements(pm1g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm1g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm1g3, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g3, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g4, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g5, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });			
+	
+		// Create the facade from the store
+		return createTransformationMetadata(metadataStore, "example3");
+	}
+
+	public static TransformationMetadata exampleUpdateProc(Table.TriggerEvent event, String procedure) {
+		MetadataStore metadataStore = new MetadataStore();
+		// Create models
+		Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+		Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
+		Schema vm1 = createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
+	
+		// Create physical groups
+		Table pm1g1 = createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+		Table pm1g2 = createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+	    Table pm2g1 = createPhysicalGroup("g1", pm2); //$NON-NLS-1$
+	    Table pm2g2 = createPhysicalGroup("g2", pm2); //$NON-NLS-1$
+	
+		// Create physical group elements
+		createElements(pm1g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm1g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+	
+		// Create virtual groups
+		QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g1 = createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+	
+		QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g2 = createUpdatableVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
+	
+		QueryNode vm1g3n1 = new QueryNode("SELECT CONCAT(e1, 'm') as x, (e2 +1) as y, 1 as e3, e4*50 as e4 FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g3 = createUpdatableVirtualGroup("g3", vm1, vm1g3n1); //$NON-NLS-1$
+	
+		QueryNode vm1g4n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g4 = createUpdatableVirtualGroup("g4", vm1, vm1g4n1); //$NON-NLS-1$
+	
+		// Create virtual elements
+		createElementsWithDefaults(vm1g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
+			new String[] { "xyz", "123", "true", "123.456"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		createElementsWithDefaults(vm1g2, 
+			new String[] { "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN },
+			new String[] { "abc", "456", "false"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		createElementsWithDefaults(vm1g3,
+			new String[] { "x", "y", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER , DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.DOUBLE },
+			new String[] { "mno", "789", "true", "789.012"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		createElementsWithDefaults(vm1g4, 
+				new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+				new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
+				new String[] { "xyz", "123", "true", "123.456"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	
+		setInsteadOfTriggerDefinition(vm1g1, event, procedure);
+		setInsteadOfTriggerDefinition(vm1g2, event, procedure);
+		setInsteadOfTriggerDefinition(vm1g3, event, procedure);
+		setInsteadOfTriggerDefinition(vm1g4, event, procedure);
+		
+		// Create the facade from the store
+		return createTransformationMetadata(metadataStore, "proc");
+	}
+
+	public static void setInsteadOfTriggerDefinition(Table view, TriggerEvent event, String proc) {
+		switch (event) {
+		case DELETE:
+			view.setDeletePlan(proc);
+			break;
+		case INSERT:
+			view.setInsertPlan(proc);
+			break;
+		case UPDATE:
+			view.setUpdatePlan(proc);
+			break;
+		}
+	}
+
+	public static TransformationMetadata exampleUpdateProc(TriggerEvent procedureType, String procedure1, String procedure2) {
+		MetadataStore metadataStore = new MetadataStore();
+	    // Create models
+	    Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+	    Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
+	    Schema vm1 = createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
+	
+	    // Create physical groups
+	    Table pm1g1 = createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+	    Table pm1g2 = createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+	    Table pm2g1 = createPhysicalGroup("g1", pm2); //$NON-NLS-1$
+	    Table pm2g2 = createPhysicalGroup("g2", pm2); //$NON-NLS-1$
+	
+	    // Create physical group elements
+	    createElements(pm1g1, 
+	        new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+	    createElements(pm1g2, 
+	        new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+	    createElements(pm2g1, 
+	        new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+	    createElements(pm2g2, 
+	        new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+	
+	    // Create virtual groups
+	    QueryNode vm1g1n1 = new QueryNode("SELECT * FROM vm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table vm1g1 = createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+	
+	    QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3, pm1.g2.e4 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table vm1g2 = createUpdatableVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
+	
+	    // Create virtual elements
+	    createElementsWithDefaults(vm1g1, 
+	        new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
+	        new String[] { "xyz", "123", "true", "123.456"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	    createElementsWithDefaults(vm1g2, 
+	        new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE },
+	        new String[] { "abc", "456", "false", null}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	
+	    setInsteadOfTriggerDefinition(vm1g1, procedureType, procedure1);
+	    setInsteadOfTriggerDefinition(vm1g2, procedureType, procedure2);
+	
+	    // Create the facade from the store
+	    return createTransformationMetadata(metadataStore, "proc");
+	}
+
+	public static TransformationMetadata exampleBusObj() { 
+		MetadataStore metadataStore = new MetadataStore();
+	    // Create db2 tables
+	    Schema db2Model = createPhysicalModel("db2model", metadataStore); //$NON-NLS-1$
+	    
+	    Table db2Table = createPhysicalGroup("DB2_TABLE", db2Model); //$NON-NLS-1$
+	    createElements(db2Table, 
+	        new String[] { "PRODUCT", "REGION", "SALES"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DOUBLE});
+	
+	    Table salesTable = createPhysicalGroup("SALES", db2Model); //$NON-NLS-1$
+	    salesTable.setCardinality(1000000);
+	    createElements(salesTable, 
+	        new String[] { "CITY", "MONTH", "SALES"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DOUBLE});
+	
+	    Table geographyTable2 = createPhysicalGroup("GEOGRAPHY2", db2Model); //$NON-NLS-1$
+	    geographyTable2.setCardinality(1000);
+	    List<Column> geographyElem2 = createElements(geographyTable2, 
+	        new String[] { "CITY", "REGION"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	    List<Column> geoPkElem2 = new ArrayList<Column>();
+	    geoPkElem2.add(geographyElem2.get(0));
+	    createKey(KeyRecord.Type.Primary, "db2model.GEOGRAPHY2.GEOGRAPHY_PK", geographyTable2, geoPkElem2); //$NON-NLS-1$
+	
+	    Table db2Table2 = createPhysicalGroup("DB2TABLE", db2Model); //$NON-NLS-1$
+	    createElements(db2Table2, 
+	        new String[] { "c0", "c1", "c2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
+	
+	    // Create oracle tables 
+	    Schema oraModel = createPhysicalModel("oraclemodel", metadataStore); //$NON-NLS-1$
+	
+	    Table oraTable = createPhysicalGroup("Oracle_table", oraModel); //$NON-NLS-1$
+	    createElements(oraTable, 
+	        new String[] { "COSTS", "REGION", "YEAR"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    Table geographyTable = createPhysicalGroup("GEOGRAPHY", oraModel); //$NON-NLS-1$
+	    geographyTable.setCardinality(1000);
+	    List<Column> geographyElem = createElements(geographyTable, 
+	        new String[] { "CITY", "REGION"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	    List<Column> geoPkElem = new ArrayList<Column>();
+	    geoPkElem.add(geographyElem.get(0));
+	    createKey(KeyRecord.Type.Primary, "oraclemodel.GEOGRAPHY.GEOGRAPHY_PK", geographyTable, geoPkElem); //$NON-NLS-1$
+	
+	    Table oraTable2 = createPhysicalGroup("OraTable", oraModel); //$NON-NLS-1$
+	    createElements(oraTable2, 
+	        new String[] { "b0", "b1", "b2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    // Create sql server tables 
+	    Schema msModel = createPhysicalModel("msmodel", metadataStore); //$NON-NLS-1$
+	
+	    Table timeTable = createPhysicalGroup("TIME", msModel); //$NON-NLS-1$
+	    timeTable.setCardinality(120);
+	    List<Column> timeElem = createElements(timeTable, 
+	        new String[] { "MONTH", "YEAR"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	    List<Column> timePkElem = new ArrayList<Column>();
+	    timePkElem.add(timeElem.get(0));
+	    createKey(KeyRecord.Type.Primary, "msmodel.TIME.TIME_PK", timeTable, timePkElem); //$NON-NLS-1$
+	
+	    Schema virtModel = createVirtualModel("logical", metadataStore); //$NON-NLS-1$
+	    QueryNode n1 = new QueryNode("select sum(c0) as c0, c1, c2 from db2Table group by c1, c2"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table logicalTable1 = createVirtualGroup("logicalTable1", virtModel, n1); //$NON-NLS-1$
+	    createElements(logicalTable1, 
+	        new String[] { "c0", "c1", "c2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
+	
+	    QueryNode n2 = new QueryNode("select sum(c0) as c0, c1, c2 from db2Table group by c1, c2"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table logicalTable2 = createVirtualGroup("logicalTable2", virtModel, n2); //$NON-NLS-1$
+	    createElements(logicalTable2, 
+	        new String[] { "b0", "b1", "b2"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.LONG, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
+	
+	    // Create the facade from the store
+	    return createTransformationMetadata(metadataStore, "busObj");
+	}
+
+	public static TransformationMetadata exampleAggregates() { 
+	    MetadataStore store = new MetadataStore();
+	    addAggregateTablesToModel("m1", store); //$NON-NLS-1$
+	    addAggregateTablesToModel("m2", store); //$NON-NLS-1$
+	
+	    // Create the facade from the store
+	    return createTransformationMetadata(store, "exampleAggregates");
+	}
+
+	public static void addAggregateTablesToModel(String modelName, MetadataStore metadataStore) {
+	    // Create db2 tables
+	    Schema model = createPhysicalModel(modelName, metadataStore); 
+	    
+	    Table orders = createPhysicalGroup("order", model); //$NON-NLS-1$
+	    orders.setCardinality(1000000);
+	    createElements(orders, 
+	        new String[] { "O_OrderID", "O_ProductID", "O_DealerID", "O_Amount", "O_Date"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, DataTypeManager.DefaultDataTypes.DATE });
+	
+	    Table products = createPhysicalGroup("product", model); //$NON-NLS-1$
+	    products.setCardinality(1000);
+	    createElements(products, 
+	        new String[] { "P_ProductID", "P_Overhead", "P_DivID"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BIG_DECIMAL, DataTypeManager.DefaultDataTypes.INTEGER});
+	
+	    Table divisions = createPhysicalGroup("division", model); //$NON-NLS-1$
+	    divisions.setCardinality(100);
+	    createElements(divisions, 
+	        new String[] { "V_DIVID", "V_SectorID"}, //$NON-NLS-1$ //$NON-NLS-2$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.INTEGER});
+	
+	    Table dealers = createPhysicalGroup("dealer", model); //$NON-NLS-1$
+	    dealers.setCardinality(1000);
+	    createElements(dealers, 
+	        new String[] { "D_DealerID", "D_State", "D_Address"}, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	}
+
+	/** 
+	 * Metadata for Multi-Binding models
+	 * @return example
+	 * @since 4.2
+	 */
+	public static TransformationMetadata exampleMultiBinding() {
+		MetadataStore metadataStore = new MetadataStore();
+	    Schema virtModel = createVirtualModel("Virt", metadataStore); //$NON-NLS-1$
+	    Schema physModel = createPhysicalModel("MultiModel", metadataStore); //$NON-NLS-1$
+	    
+	    Table physGroup = createPhysicalGroup("Phys", physModel); //$NON-NLS-1$
+	    createElements(physGroup,
+	                                  new String[] { "a", "b" }, //$NON-NLS-1$ //$NON-NLS-2$ 
+	                                  new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	    
+	    QueryNode virtTrans = new QueryNode("SELECT * FROM MultiModel.Phys");         //$NON-NLS-1$ //$NON-NLS-2$
+	    Table virtGroup = createVirtualGroup("view", virtModel, virtTrans); //$NON-NLS-1$
+	    createElements(virtGroup,
+	                                       new String[] { "a", "b" }, //$NON-NLS-1$ //$NON-NLS-2$ 
+	                                       new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	    
+	    ColumnSet<Procedure> rs2 = createResultSet("Virt.rs1", new String[] { "a", "b" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	    ProcedureParameter rs2p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+	    rs2p2.setNullType(org.teiid.metadata.BaseColumn.NullType.Nullable);
+	    QueryNode sq2n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN\n" //$NON-NLS-1$ //$NON-NLS-2$
+	                                    + "execute string 'SELECT a, b FROM MultiModel.Phys where SOURCE_NAME = Virt.sq1.in'; END"); //$NON-NLS-1$ 
+	    Procedure sq1 = createVirtualProcedure("sq1", virtModel, Arrays.asList(rs2p2), sq2n1);  //$NON-NLS-1$
+	    sq1.setResultSet(rs2);
+	
+	    ColumnSet<Procedure> rs3 = createResultSet("MultiModel.rs1", new String[] { "a", "b" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	    ProcedureParameter rs3p2 = createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+	    ProcedureParameter rs3p3 = createParameter("source_name", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+	    rs3p3.setNullType(org.teiid.metadata.BaseColumn.NullType.Nullable);
+	    Procedure sq2 = createStoredProcedure("proc", physModel, Arrays.asList(rs3p2, rs3p3));
+	    sq2.setResultSet(rs3);
+	    return createTransformationMetadata(metadataStore, "multiBinding");
+	}
+
+	/**
+	 * set up metadata for virtual doc model of this basic structure:
+	 * <pre>
+	 * 
+	 * items
+	 *   --suppliers (many-to-many relationship between items and suppliers)
+	 *       --orders
+	 *       --employees (an employees works for a supplier and "specializes" in an item)
+	 * 
+	 * </pre> 
+	 * @return
+	 */
+	public static TransformationMetadata exampleCase3225() {
+		MetadataStore metadataStore = new MetadataStore();
+	    
+	    // Create models
+	    Schema stock = createPhysicalModel("stock", metadataStore); //$NON-NLS-1$
+	    Schema xmltest = createVirtualModel("xmltest", metadataStore);     //$NON-NLS-1$
+	
+	    // Create physical groups
+	    Table items = createPhysicalGroup("items", stock); //$NON-NLS-1$
+	    Table item_supplier = createPhysicalGroup("item_supplier", stock); //$NON-NLS-1$
+	    Table suppliers = createPhysicalGroup("suppliers", stock); //$NON-NLS-1$
+	    Table orders = createPhysicalGroup("orders", stock); //$NON-NLS-1$
+	    Table employees = createPhysicalGroup("employees", stock); //$NON-NLS-1$
+	         
+	    // Create physical elements
+	    createElements(items, 
+	        new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });
+	
+	    //many-to-many join table
+	    createElements(item_supplier, 
+	        new String[] { "itemNum", "supplierNum" }, //$NON-NLS-1$ //$NON-NLS-2$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	
+	    createElements(suppliers, 
+	        new String[] { "supplierNum", "supplierName", "supplierZipCode" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	
+	    createElements(orders, 
+	        new String[] { "orderNum", "itemFK", "supplierFK", "orderDate", "orderQty", "orderStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    createElements(employees, 
+	        new String[] { "employeeNum", "supplierNumFK", "specializesInItemNum", "supervisorNum", "firstName", "lastName" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    // Create mapping classes - items doc
+	    QueryNode rsQuery = new QueryNode("SELECT itemNum, itemName, itemQuantity, itemStatus FROM stock.items"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table rsItems = createVirtualGroup("items", xmltest, rsQuery); //$NON-NLS-1$
+	
+	    QueryNode rsQuery2 = new QueryNode("SELECT stock.suppliers.supplierNum, supplierName, supplierZipCode, stock.item_supplier.itemNum FROM stock.suppliers, stock.item_supplier WHERE stock.suppliers.supplierNum = stock.item_supplier.supplierNum AND stock.item_supplier.itemNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+	    rsQuery2.addBinding("xmltest.items.itemNum"); //$NON-NLS-1$
+	    Table rsSuppliers = createVirtualGroup("suppliers", xmltest, rsQuery2); //$NON-NLS-1$
+	
+	    QueryNode rsQuery3 = new QueryNode("SELECT orderNum, orderDate, orderQty, orderStatus, itemFK, supplierFK FROM stock.orders WHERE itemFK = ? AND supplierFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+	    rsQuery3.addBinding("xmltest.suppliers.itemNum"); //$NON-NLS-1$
+	    rsQuery3.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
+	    Table rsOrders = createVirtualGroup("orders", xmltest, rsQuery3); //$NON-NLS-1$
+	
+	    QueryNode rsQuery4 = new QueryNode("SELECT employeeNum, firstName, lastName, supervisorNum, specializesInItemNum, supplierNumFK FROM stock.employees WHERE specializesInItemNum = ? AND supplierNumFK = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+	    rsQuery4.addBinding("xmltest.suppliers.itemNum"); //$NON-NLS-1$
+	    rsQuery4.addBinding("xmltest.suppliers.supplierNum"); //$NON-NLS-1$
+	    Table rsEmployees = createVirtualGroup("employees", xmltest, rsQuery4); //$NON-NLS-1$
+	
+	    // Create mapping classes elements - items doc
+	    createElements(rsItems, 
+	        new String[] { "itemNum", "itemName", "itemQuantity", "itemStatus" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING });        
+	
+	    createElements(rsSuppliers, 
+	        new String[] { "supplierNum", "supplierName", "supplierZipCode", "itemNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	
+	    createElements(rsOrders, 
+	        new String[] { "orderNum", "orderDate", "orderQty", "orderStatus", "itemFK", "supplierFK" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    createElements(rsEmployees, 
+	        new String[] { "employeeNum", "firstName", "lastName", "supervisorNum", "specializesInItemNum", "supplierNumFK" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    // MAPPING DOC ======================================================================
+	    MappingDocument doc = new MappingDocument(true);
+	    MappingElement root = doc.addChildElement(new MappingElement("Catalogs")); //$NON-NLS-1$
+	    
+	    MappingElement cats = root.addChildElement(new MappingElement("Catalog")); //$NON-NLS-1$
+	    MappingElement itemsA = cats.addChildElement(new MappingElement("Items")); //$NON-NLS-1$
+	
+	    MappingElement item = itemsA.addChildElement(new MappingElement("Item")); //$NON-NLS-1$
+	    item.setSource("xmltest.items");//$NON-NLS-1$
+	    item.setMaxOccurrs(-1);
+	    item.addAttribute(new MappingAttribute("ItemID", "xmltest.items.itemNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    item.addChildElement(new MappingElement("Name", "xmltest.items.itemName")); //$NON-NLS-1$ //$NON-NLS-2$
+	    item.addChildElement(new MappingElement("Quantity", "xmltest.items.itemQuantity")); //$NON-NLS-1$ //$NON-NLS-2$
+	    
+	    //NESTED STUFF======================================================================
+	    MappingElement nestedWrapper = item.addChildElement(new MappingElement("Suppliers")); //$NON-NLS-1$
+	    MappingElement supplier = nestedWrapper.addChildElement(new MappingElement("Supplier")); //$NON-NLS-1$
+	    supplier.setSource("xmltest.suppliers");//$NON-NLS-1$
+	    supplier.setMaxOccurrs(-1);
+	    supplier.addAttribute(new MappingAttribute("SupplierID", "xmltest.suppliers.supplierNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    supplier.addChildElement(new MappingElement("Name","xmltest.suppliers.supplierName")); //$NON-NLS-1$ //$NON-NLS-2$
+	    supplier.addChildElement(new MappingElement("Zip", "xmltest.suppliers.supplierZipCode")); //$NON-NLS-1$ //$NON-NLS-2$
+	    
+	    MappingElement ordersWrapper = supplier.addChildElement(new MappingElement("Orders")); //$NON-NLS-1$
+	    MappingElement order = ordersWrapper.addChildElement(new MappingElement("Order")); //$NON-NLS-1$
+	    order.setSource("xmltest.orders"); //$NON-NLS-1$
+	    order.setMaxOccurrs(-1);
+	    order.addAttribute(new MappingAttribute("OrderID", "xmltest.orders.orderNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    order.addChildElement(new MappingElement("OrderDate", "xmltest.orders.orderDate")); //$NON-NLS-1$ //$NON-NLS-2$
+	    order.addChildElement(new MappingElement("OrderQuantity", "xmltest.orders.orderQty")); //$NON-NLS-1$ //$NON-NLS-2$
+	
+	    order.addChildElement(new MappingElement("OrderStatus", "xmltest.orders.orderStatus")) //$NON-NLS-1$ //$NON-NLS-2$
+	        .setMinOccurrs(0);                
+	    //NESTED STUFF======================================================================
+	    
+	    MappingElement employeesWrapper = supplier.addChildElement(new MappingElement("Employees")); //$NON-NLS-1$
+	    MappingElement employee = employeesWrapper.addChildElement(new MappingElement("Employee")); //$NON-NLS-1$
+	    employee.setSource("xmltest.employees"); //$NON-NLS-1$
+	    employee.setMaxOccurrs(-1);
+	    employee.addAttribute(new MappingAttribute("EmployeeID", "xmltest.employees.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    employee.addChildElement(new MappingElement("FirstName", "xmltest.employees.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+	    employee.addChildElement(new MappingElement("LastName", "xmltest.employees.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+	    employee.addAttribute(new MappingAttribute("SupervisorID", "xmltest.employees.supervisorNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    
+	    // END MAPPING DOC ======================================================================
+	    
+	    // Create virtual docs and doc elements
+	    Table itemsDoc = createXmlDocument("itemsDoc", xmltest, doc); //$NON-NLS-1$
+	    createElements(itemsDoc, 
+	        new String[] { "Catalogs",  //$NON-NLS-1$
+	                       "Catalogs.Catalog",  //$NON-NLS-1$
+	                       "Catalogs.Catalog.items",  //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item",  //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item. at ItemID",  //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Name",  //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Quantity", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier. at SupplierID", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Name", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Zip", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order. at OrderID", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order.OrderDate", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order.OrderQuantity", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Orders.Order.OrderStatus", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee. at EmployeeID", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee.FirstName", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee.LastName", //$NON-NLS-1$
+	                       "Catalogs.Catalog.items.item.Suppliers.Supplier.Employees.Employee. at SupervisorID", //$NON-NLS-1$
+	    
+	        }, 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.INTEGER, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       });
+	        
+	    // Create mapping classes - baseball players employees doc
+	    QueryNode playersNode = new QueryNode("SELECT stock.employees.employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE specializesInItemNum is not null"); //$NON-NLS-1$ //$NON-NLS-2$
+	    Table rsPlayers = createVirtualGroup("player", xmltest, playersNode); //$NON-NLS-1$
+	
+	    QueryNode managersNode = new QueryNode("SELECT stock.employees.employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE stock.employees.employeeNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$
+	    managersNode.addBinding("xmltest.player.supervisorNum"); //$NON-NLS-1$
+	    Table rsManagers = createVirtualGroup("managers", xmltest, managersNode); //$NON-NLS-1$
+	
+	        // TODO what if elements in criteria weren't fully qualified? see defect 19541
+	    QueryNode ownersNode = new QueryNode("SELECT stock.employees.employeeNum, firstName, lastName, supervisorNum FROM stock.employees WHERE stock.employees.employeeNum = ?"); //$NON-NLS-1$ //$NON-NLS-2$ 
+	    ownersNode.addBinding("xmltest.managers.supervisorNum"); //$NON-NLS-1$
+	    Table rsOwners = createVirtualGroup("owners", xmltest, ownersNode); //$NON-NLS-1$
+	
+	    // Create mapping classes elements - items doc
+	    createElements(rsPlayers, 
+	        new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    createElements(rsManagers, 
+	         new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	         new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	    createElements(rsOwners, 
+	       new String[] { "employeeNum", "firstName", "lastName", "supervisorNum" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	       new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING});
+	
+	
+	    
+	    // MAPPING DOC - baseball players ======================================================================
+	    MappingDocument doc2 = new MappingDocument(true);
+	    MappingElement root2 = doc2.addChildElement(new MappingElement("BaseballPlayers")); //$NON-NLS-1$
+	    
+	    MappingElement player = root2.addChildElement(new MappingElement("Player")); //$NON-NLS-1$
+	    player.setSource("xmltest.player"); //$NON-NLS-1$
+	    player.setMaxOccurrs(-1);
+	    player.addAttribute(new MappingAttribute("PlayerID", "xmltest.player.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    player.addChildElement(new MappingElement("FirstName", "xmltest.player.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+	    player.addChildElement(new MappingElement("LastName", "xmltest.player.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+	
+	    MappingElement manager = player.addChildElement(new MappingElement("Manager")); //$NON-NLS-1$
+	    manager.setSource("xmltest.managers");//$NON-NLS-1$
+	    manager.setMaxOccurrs(-1);
+	    manager.addAttribute(new MappingAttribute("ManagerID", "xmltest.managers.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    manager.addChildElement(new MappingElement("FirstName", "xmltest.managers.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+	    manager.addChildElement(new MappingElement("LastName", "xmltest.managers.lastName")); //$NON-NLS-1$ //$NON-NLS-2$
+	            
+	    MappingElement owner = manager.addChildElement(new MappingElement("Owner")); //$NON-NLS-1$
+	    owner.setSource("xmltest.owners"); //$NON-NLS-1$
+	    owner.setMaxOccurrs(-1);
+	    owner.addAttribute(new MappingAttribute("OwnerID", "xmltest.owners.employeeNum")); //$NON-NLS-1$ //$NON-NLS-2$
+	    owner.addChildElement(new MappingElement("FirstName", "xmltest.owners.firstName")); //$NON-NLS-1$ //$NON-NLS-2$
+	    owner.addChildElement(new MappingElement("LastName", "xmltest.owners.lastName")); //$NON-NLS-1$ //$NON-NLS-2$       
+	    // END MAPPING DOC ======================================================================
+	    
+	    // Create virtual docs and doc elements
+	    Table playersDoc = createXmlDocument("playersDoc", xmltest, doc2); //$NON-NLS-1$
+	    createElements(playersDoc, 
+	        new String[] { "BaseballPlayers",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player. at PlayerID",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.FirstName",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.LastName",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager. at ManagerID",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager.FirstName",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager.LastName",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager.Owner",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager.Owner. at OwnerID",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager.Owner.FirstName",  //$NON-NLS-1$
+	                       "BaseballPlayers.Player.Manager.Owner.LastName",  //$NON-NLS-1$
+	    
+	        }, 
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	                       DataTypeManager.DefaultDataTypes.STRING, 
+	        });        
+	    return createTransformationMetadata(metadataStore, "case3225");
+	}
+
+	/**
+	 * This example is for testing static costing using cardinality information from
+	 * metadata, as well as key information and maybe access patterns
+	 */
+	public static TransformationMetadata example4() {
+		MetadataStore metadataStore = new MetadataStore();
+		// Create models - physical ones will support joins
+		Schema pm1 = createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+		Schema pm2 = createPhysicalModel("pm2", metadataStore); //$NON-NLS-1$
+		Schema pm3 = createPhysicalModel("pm3", metadataStore); //$NON-NLS-1$
+	    Schema pm4 = createPhysicalModel("pm4", metadataStore); //$NON-NLS-1$
+		Schema vm1 = createVirtualModel("vm1", metadataStore);	 //$NON-NLS-1$
+	
+		// Create physical groups
+		Table pm1g1 = createPhysicalGroup("g1", pm1); //$NON-NLS-1$
+		Table pm1g2 = createPhysicalGroup("g2", pm1); //$NON-NLS-1$
+		Table pm1g3 = createPhysicalGroup("g3", pm1); //$NON-NLS-1$
+		Table pm2g1 = createPhysicalGroup("g1", pm2); //$NON-NLS-1$
+		Table pm2g2 = createPhysicalGroup("g2", pm2); //$NON-NLS-1$
+		Table pm2g3 = createPhysicalGroup("g3", pm2); //$NON-NLS-1$
+		Table pm3g1 = createPhysicalGroup("g1", pm3); //$NON-NLS-1$
+		Table pm3g2 = createPhysicalGroup("g2", pm3); //$NON-NLS-1$
+		Table pm3g3 = createPhysicalGroup("g3", pm3); //$NON-NLS-1$
+	    Table pm4g1 = createPhysicalGroup("g1", pm4); //$NON-NLS-1$
+	    Table pm4g2 = createPhysicalGroup("g2", pm4); //$NON-NLS-1$
+		// Add group cardinality metadata
+		pm1g1.setCardinality(10);
+		pm1g2.setCardinality(10);
+		pm1g3.setCardinality(10);
+		pm2g1.setCardinality(1000);
+		pm2g2.setCardinality(1000);
+		pm3g1.setCardinality(100000);
+		pm3g2.setCardinality(100000);
+	    pm3g3.setCardinality(100000);
+	    // leave pm4.g1 as unknown
+				
+		// Create physical elements
+		List<Column> pm1g1e = createElements(pm1g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm1g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		List<Column> pm1g3e = createElements(pm1g3, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		List<Column> pm2g1e = createElements(pm2g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm2g3, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		List<Column> pm3g1e = createElements(pm3g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(pm3g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		List<Column> pm3g3e = createElements(pm3g3, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		List<Column> pm4g1e = createElements(pm4g1, 
+	        new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	        new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		List<Column> pm4g2e = createElements(pm4g2, 
+	            new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+	            new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+	
+		// Add key metadata
+		createKey(KeyRecord.Type.Primary, "pm1.g1.key1", pm1g1, pm1g1e.subList(0, 1)); //e1 //$NON-NLS-1$
+		createKey(KeyRecord.Type.Primary, "pm3.g1.key1", pm3g1, pm3g1e.subList(0, 1)); //e1 //$NON-NLS-1$
+		createKey(KeyRecord.Type.Primary, "pm3.g3.key1", pm3g3, pm3g3e.subList(0, 1)); //e1 //$NON-NLS-1$
+	    KeyRecord pm4g1key1= createKey(KeyRecord.Type.Primary, "pm4.g1.key1", pm4g1, pm4g1e.subList(0, 2)); //e1, e2 //$NON-NLS-1$
+	    createForeignKey("pm4.g2.fk", pm4g2, pm4g2e.subList(0, 2), pm4g1key1); //$NON-NLS-1$
+		// Add access pattern metadata
+		// Create access patterns - pm1
+		List<Column> elements = new ArrayList<Column>(1);
+		elements.add(pm1g1e.iterator().next());       
+		createAccessPattern("pm1.g1.ap1", pm1g1, elements); //e1 //$NON-NLS-1$
+		elements = new ArrayList<Column>(2);
+		Iterator<Column> iter = pm1g3e.iterator();
+		elements.add(iter.next());       
+		elements.add(iter.next());       
+		createAccessPattern("pm1.g3.ap1", pm1g3, elements); //e1,e2 //$NON-NLS-1$
+		// Create access patterns - pm2
+		elements = new ArrayList<Column>(1);
+		elements.add(pm2g1e.iterator().next());
+		createAccessPattern("pm2.g1.ap1", pm2g1, elements); //e1 //$NON-NLS-1$
+	
+		// Create virtual groups
+		QueryNode vm1g1n1 = new QueryNode("SELECT * FROM pm1.g1"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g1 = createUpdatableVirtualGroup("g1", vm1, vm1g1n1); //$NON-NLS-1$
+	
+		QueryNode vm1g2n1 = new QueryNode("SELECT pm1.g2.e1, pm1.g2.e2, pm1.g2.e3 FROM pm1.g2"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g2 = createUpdatableVirtualGroup("g2", vm1, vm1g2n1); //$NON-NLS-1$
+	
+		QueryNode vm1g3n1 = new QueryNode("SELECT pm1.g3.e1 AS x, pm1.g3.e2 AS y from pm1.g3"); //$NON-NLS-1$ //$NON-NLS-2$
+		Table vm1g3 = createUpdatableVirtualGroup("g3", vm1, vm1g3n1); //$NON-NLS-1$
+	
+	    QueryNode vm1g4n1 = new QueryNode("SELECT distinct pm1.g2.e1 as ve1, pm1.g1.e1 as ve2 FROM pm1.g2 LEFT OUTER JOIN /* optional */ pm1.g1 on pm1.g1.e1 = pm1.g2.e1");         //$NON-NLS-1$ //$NON-NLS-2$
+	    Table vm1g4 = createVirtualGroup("g4", vm1, vm1g4n1); //$NON-NLS-1$
+	    createElements(vm1g4,
+	              new String[] { "ve1", "ve2" }, //$NON-NLS-1$ //$NON-NLS-2$
+	              new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
+	
+		// Create virtual elements
+		createElements(vm1g1, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(vm1g2, 
+			new String[] { "e1", "e2", "e3", "e4" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.BOOLEAN, DataTypeManager.DefaultDataTypes.DOUBLE });
+		createElements(vm1g3,
+			new String[] { "e1", "e2","x", "y" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+			new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER });
+			
+		return createTransformationMetadata(metadataStore, "example4");
+	}
+
 }

Modified: branches/as7/engine/src/test/java/org/teiid/query/validator/TestAlterValidation.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/validator/TestAlterValidation.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/validator/TestAlterValidation.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -41,7 +41,7 @@
 	}
 	
 	@Test public void testValidateAlterTrigger() {
-		TestValidator.helpValidate("alter trigger on SmallA_2589 instead of insert as for each row select 1;", new String[] {"SmallA_2589"}, RealMetadataFactory.exampleBQTCached());
+		TestValidator.helpValidate("alter trigger on SmallA_2589 instead of insert as for each row begin atomic select 1; end", new String[] {"SmallA_2589"}, RealMetadataFactory.exampleBQTCached());
 	}
 	
 	@Test public void testValidateAlterProcedure() {

Modified: branches/as7/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/validator/TestUpdateValidator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -180,7 +180,7 @@
         // Stored queries
         ColumnSet<Procedure> rs1 = RealMetadataFactory.createResultSet("rs1", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
         QueryNode sq1n1 = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN SELECT e1, e2 FROM pm1.g1; END"); //$NON-NLS-1$ //$NON-NLS-2$
-        Procedure sq1 = RealMetadataFactory.createVirtualProcedure("pm1.sq1", pm1, Collections.EMPTY_LIST, sq1n1);  //$NON-NLS-1$
+        Procedure sq1 = RealMetadataFactory.createVirtualProcedure("sq1", pm1, Collections.EMPTY_LIST, sq1n1);  //$NON-NLS-1$
         sq1.setResultSet(rs1);
 		// Create the facade from the store
 		return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");

Modified: branches/as7/engine/src/test/java/org/teiid/query/validator/TestValidator.java
===================================================================
--- branches/as7/engine/src/test/java/org/teiid/query/validator/TestValidator.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/engine/src/test/java/org/teiid/query/validator/TestValidator.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,7 +28,6 @@
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
 
@@ -43,11 +42,21 @@
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.types.DataTypeManager;
 import org.teiid.dqp.internal.process.multisource.MultiSourceMetadataWrapper;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.ColumnSet;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.ProcedureParameter;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.BaseColumn.NullType;
+import org.teiid.metadata.Column.SearchType;
 import org.teiid.query.analysis.AnalysisRecord;
 import org.teiid.query.mapping.relational.QueryNode;
 import org.teiid.query.mapping.xml.MappingDocument;
 import org.teiid.query.mapping.xml.MappingElement;
 import org.teiid.query.metadata.QueryMetadataInterface;
+import org.teiid.query.metadata.TransformationMetadata;
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.LanguageObject;
@@ -55,58 +64,55 @@
 import org.teiid.query.sql.lang.ProcedureContainer;
 import org.teiid.query.sql.symbol.GroupSymbol;
 import org.teiid.query.sql.visitor.SQLStringVisitor;
-import org.teiid.query.unittest.FakeMetadataFacade;
-import org.teiid.query.unittest.FakeMetadataFactory;
-import org.teiid.query.unittest.FakeMetadataObject;
-import org.teiid.query.unittest.FakeMetadataStore;
 import org.teiid.query.unittest.RealMetadataFactory;
 
 @SuppressWarnings("nls")
 public class TestValidator {
 
-    public static FakeMetadataFacade exampleMetadata() {
+    public static TransformationMetadata exampleMetadata() {
+    	MetadataStore metadataStore = new MetadataStore();
         // Create metadata objects        
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject vModelObj2 = FakeMetadataFactory.createVirtualModel("vTest");  //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        elemObj0.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        elemObj1.putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        elemObj2.putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
-        FakeMetadataObject elemObj3 = FakeMetadataFactory.createElement("test.group.e3", groupObj, DataTypeManager.DefaultDataTypes.STRING, 3); //$NON-NLS-1$
-        elemObj3.putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
+        Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
+        Schema vModelObj2 = RealMetadataFactory.createVirtualModel("vTest", metadataStore);  //$NON-NLS-1$
+        Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj);         //$NON-NLS-1$
+        Column elemObj0 = RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        elemObj0.setNullType(NullType.No_Nulls);
+        Column elemObj1 = RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        elemObj1.setSelectable(false);
+        Column elemObj2 = RealMetadataFactory.createElement("e2", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        elemObj2.setSearchType(SearchType.Like_Only);
+        Column elemObj3 = RealMetadataFactory.createElement("e3", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        elemObj3.setSearchType(SearchType.All_Except_Like);
     
-        FakeMetadataObject group2Obj = FakeMetadataFactory.createPhysicalGroup("test.group2", modelObj);         //$NON-NLS-1$
-        FakeMetadataObject elemObj2_0 = FakeMetadataFactory.createElement("test.group2.e0", group2Obj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        elemObj2_0.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
-        FakeMetadataObject elemObj2_1 = FakeMetadataFactory.createElement("test.group2.e1", group2Obj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj2_2 = FakeMetadataFactory.createElement("test.group2.e2", group2Obj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        elemObj2_2.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
+        Table group2Obj = RealMetadataFactory.createPhysicalGroup("group2", modelObj);         //$NON-NLS-1$
+        Column elemObj2_0 = RealMetadataFactory.createElement("e0", group2Obj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        elemObj2_0.setUpdatable(false);
+        RealMetadataFactory.createElement("e1", group2Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        Column elemObj2_2 = RealMetadataFactory.createElement("e2", group2Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        elemObj2_2.setUpdatable(false);
     
-        FakeMetadataObject group3Obj = FakeMetadataFactory.createPhysicalGroup("test.group3", modelObj);         //$NON-NLS-1$
-        group3Obj.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE); 
-        FakeMetadataObject elemObj3_0 = FakeMetadataFactory.createElement("test.group3.e0", group3Obj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj3_1 = FakeMetadataFactory.createElement("test.group3.e1", group3Obj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj3_2 = FakeMetadataFactory.createElement("test.group3.e2", group3Obj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
+        Table group3Obj = RealMetadataFactory.createPhysicalGroup("group3", modelObj);         //$NON-NLS-1$
+        group3Obj.setSupportsUpdate(false); 
+        RealMetadataFactory.createElement("e0", group3Obj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e1", group3Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e2", group3Obj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
     
         // Create virtual group & elements.
         QueryNode vNode = new QueryNode("SELECT * FROM test.group WHERE e2 = 'x'"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vGroup = FakeMetadataFactory.createVirtualGroup("vTest.vGroup", vModelObj2, vNode);         //$NON-NLS-1$
-        List vGroupE = FakeMetadataFactory.createElements(vGroup, 
+        Table vGroup = RealMetadataFactory.createVirtualGroup("vGroup", vModelObj2, vNode);         //$NON-NLS-1$
+        RealMetadataFactory.createElements(vGroup, 
             new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
 
         QueryNode vNode2 = new QueryNode("SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject vGroup2 = FakeMetadataFactory.createVirtualGroup("vTest.vMap", vModelObj2, vNode2);         //$NON-NLS-1$
-        List vGroupE2 = FakeMetadataFactory.createElements(vGroup2, 
+        Table vGroup2 = RealMetadataFactory.createVirtualGroup("vMap", vModelObj2, vNode2);         //$NON-NLS-1$
+        List<Column> vGroupE2 = RealMetadataFactory.createElements(vGroup2, 
             new String[] { "e0", "e1", "e2", "e3" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
             new String[] { DataTypeManager.DefaultDataTypes.INTEGER, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
-        ((FakeMetadataObject)vGroupE2.get(0)).putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        ((FakeMetadataObject)vGroupE2.get(1)).putProperty(FakeMetadataObject.Props.SELECT, Boolean.FALSE);
-        ((FakeMetadataObject)vGroupE2.get(2)).putProperty(FakeMetadataObject.Props.SEARCHABLE_COMPARE, Boolean.FALSE);
-        ((FakeMetadataObject)vGroupE2.get(3)).putProperty(FakeMetadataObject.Props.SEARCHABLE_LIKE, Boolean.FALSE);
+        vGroupE2.get(0).setNullType(NullType.No_Nulls);
+        vGroupE2.get(1).setSelectable(false);
+        vGroupE2.get(2).setSearchType(SearchType.Like_Only);
+        vGroupE2.get(3).setSearchType(SearchType.All_Except_Like);
     
         // Create virtual documents
         MappingDocument doc = new MappingDocument(false);
@@ -118,77 +124,47 @@
         sourceNode.addChildElement(new MappingElement("b2", "test.group.e2")); //$NON-NLS-1$ //$NON-NLS-2$
         sourceNode.addChildElement(new MappingElement("c2", "test.group.e3")); //$NON-NLS-1$ //$NON-NLS-2$
         
-    	FakeMetadataObject docModel = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
-        FakeMetadataObject doc1 = FakeMetadataFactory.createVirtualGroup("vm1.doc1", docModel, doc); //$NON-NLS-1$
-    	List docE1 = FakeMetadataFactory.createElements(doc1, new String[] { "a0", "a0.a1", "a0.a1.a2", "a0.a1.b2", "a0.a1.c2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+    	Schema docModel = RealMetadataFactory.createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
+        Table doc1 = RealMetadataFactory.createXmlDocument("doc1", docModel, doc); //$NON-NLS-1$
+    	RealMetadataFactory.createElements(doc1, new String[] { "a0", "a0.a1", "a0.a1.a2", "a0.a1.b2", "a0.a1.c2" }, //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
     		new String[] {DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.STRING });
                         
-    	// set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        store.addObject(elemObj2);
-        store.addObject(elemObj3);
-        store.addObject(vGroup);
-        store.addObjects(vGroupE);
-        store.addObject(vGroup2);
-        store.addObjects(vGroupE2);
-        store.addObject(docModel);
-        store.addObject(group2Obj);
-        store.addObject(elemObj2_0);
-        store.addObject(elemObj2_1);
-        store.addObject(elemObj2_2);
-        store.addObject(group3Obj);
-        store.addObject(elemObj3_0);
-        store.addObject(elemObj3_1);
-        store.addObject(elemObj3_2);
-        store.addObject(doc1);
-        store.addObjects(docE1);
-    	return new FakeMetadataFacade(store);
+    	return RealMetadataFactory.createTransformationMetadata(metadataStore, "example");
     }
 	
-    public FakeMetadataFacade exampleMetadata1() {
+    public TransformationMetadata exampleMetadata1() {
+    	MetadataStore metadataStore = new MetadataStore();
         // Create metadata objects        
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
+        Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
+        Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj);         //$NON-NLS-1$
 
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        FakeMetadataObject elemObj3 = FakeMetadataFactory.createElement("test.group.e3", groupObj, DataTypeManager.DefaultDataTypes.STRING, 3);         //$NON-NLS-1$
+        Column elemObj0 = RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        Column elemObj1 = RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        Column elemObj2 = RealMetadataFactory.createElement("e2", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e3", groupObj, DataTypeManager.DefaultDataTypes.STRING);         //$NON-NLS-1$
 
-        elemObj0.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        elemObj0.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
+        elemObj0.setNullType(NullType.No_Nulls);
 
-        elemObj1.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        elemObj1.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.TRUE);
+        elemObj1.setNullType(NullType.Nullable);
+        elemObj1.setDefaultValue(Boolean.TRUE.toString());
         
-        elemObj2.putProperty(FakeMetadataObject.Props.NULL, Boolean.TRUE);
-        elemObj2.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
+        elemObj2.setNullType(NullType.Nullable);
+        elemObj2.setDefaultValue(Boolean.FALSE.toString());
         
-		// set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        store.addObject(elemObj2);
-        store.addObject(elemObj3);
-		return new FakeMetadataFacade(store);
+		return RealMetadataFactory.createTransformationMetadata(metadataStore, "example1");
     }
 
     /**
      * Group has element with type object
-     * @return FakeMetadataFacade
+     * @return QueryMetadataInterface
      */
-    public static FakeMetadataFacade exampleMetadata2() {
+    public static TransformationMetadata exampleMetadata2() {
+    	MetadataStore metadataStore = new MetadataStore();
         // Create metadata objects
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj); //$NON-NLS-1$
+        Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
+        Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
         
-        List elements = FakeMetadataFactory.createElements(groupObj, new String[] {
+        RealMetadataFactory.createElements(groupObj, new String[] {
             "e0", "e1", "e2", "e3", "e4", "e5" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
         }, new String[] {
             DataTypeManager.DefaultDataTypes.INTEGER,
@@ -199,83 +175,56 @@
             DataTypeManager.DefaultDataTypes.XML,
         });
 
-        // set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObjects(elements);
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example2");
     }
 
-    public static FakeMetadataFacade exampleMetadata3() {
+    public static TransformationMetadata exampleMetadata3() {
+    	MetadataStore metadataStore = new MetadataStore();
         // Create metadata objects        
-        FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test"); //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj);         //$NON-NLS-1$
+        Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore); //$NON-NLS-1$
+        Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj);         //$NON-NLS-1$
 
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        Column elemObj1 = RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
 
-        elemObj1.putProperty(FakeMetadataObject.Props.NULL, Boolean.FALSE);
-        elemObj1.putProperty(FakeMetadataObject.Props.DEFAULT_VALUE, Boolean.FALSE);
-        elemObj1.putProperty(FakeMetadataObject.Props.AUTO_INCREMENT, Boolean.TRUE);
-        elemObj1.putProperty(FakeMetadataObject.Props.NAME_IN_SOURCE, "e1:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
+        elemObj1.setNullType(NullType.No_Nulls);
+        elemObj1.setDefaultValue(Boolean.FALSE.toString());
+        elemObj1.setAutoIncremented(true);
+        elemObj1.setNameInSource("e1:SEQUENCE=MYSEQUENCE.nextVal"); //$NON-NLS-1$
         
-        // set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example3");
     }
 
-    public static FakeMetadataFacade exampleMetadata4() {
+    public static TransformationMetadata exampleMetadata4() {
+    	MetadataStore metadataStore = new MetadataStore();
         // Create metadata objects 
-    	FakeMetadataObject modelObj = FakeMetadataFactory.createPhysicalModel("test");  //$NON-NLS-1$
-        FakeMetadataObject groupObj = FakeMetadataFactory.createPhysicalGroup("test.group", modelObj); //$NON-NLS-1$
-        FakeMetadataObject elemObj0 = FakeMetadataFactory.createElement("test.group.e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject elemObj1 = FakeMetadataFactory.createElement("test.group.e1", groupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject elemObj2 = FakeMetadataFactory.createElement("test.group.e2", groupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        FakeMetadataObject vModelObj = FakeMetadataFactory.createVirtualModel("vTest");  //$NON-NLS-1$
+    	Schema modelObj = RealMetadataFactory.createPhysicalModel("test", metadataStore);  //$NON-NLS-1$
+        Table groupObj = RealMetadataFactory.createPhysicalGroup("group", modelObj); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e0", groupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e1", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e2", groupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        Schema vModelObj = RealMetadataFactory.createVirtualModel("vTest", metadataStore);  //$NON-NLS-1$
         QueryNode vNode = new QueryNode("SELECT * FROM test.group"); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vGroupObj = FakeMetadataFactory.createVirtualGroup("vTest.vGroup", vModelObj, vNode); //$NON-NLS-1$
-        FakeMetadataObject vElemObj0 = FakeMetadataFactory.createElement("vTest.vGroup.e0", vGroupObj, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject vElemObj1 = FakeMetadataFactory.createElement("vTest.vGroup.e1", vGroupObj, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject vElemObj2 = FakeMetadataFactory.createElement("vTest.vGroup.e2", vGroupObj, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        List elements = new ArrayList(1);
+        Table vGroupObj = RealMetadataFactory.createVirtualGroup("vGroup", vModelObj, vNode); //$NON-NLS-1$
+        Column vElemObj0 = RealMetadataFactory.createElement("e0", vGroupObj, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        Column vElemObj1 = RealMetadataFactory.createElement("e1", vGroupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e2", vGroupObj, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        List<Column> elements = new ArrayList<Column>(2);
         elements.add(vElemObj0); 
         elements.add(vElemObj1);
-        FakeMetadataObject vGroupAp1 = FakeMetadataFactory.createAccessPattern("vTest.vGroup.ap1", vGroupObj, elements); //e1 //$NON-NLS-1$
+        RealMetadataFactory.createAccessPattern("ap1", vGroupObj, elements); //e1 //$NON-NLS-1$
         
         QueryNode vNode2 = new QueryNode("SELECT * FROM vTest.vGroup"); //$NON-NLS-1$ //$NON-NLS-2$ 
-        FakeMetadataObject vGroupObj2 = FakeMetadataFactory.createVirtualGroup("vTest.vGroup2", vModelObj, vNode2); //$NON-NLS-1$
-        FakeMetadataObject vElemObj20 = FakeMetadataFactory.createElement("vTest.vGroup2.e0", vGroupObj2, DataTypeManager.DefaultDataTypes.INTEGER, 0); //$NON-NLS-1$
-        FakeMetadataObject vElemObj21 = FakeMetadataFactory.createElement("vTest.vGroup2.e1", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING, 1); //$NON-NLS-1$
-        FakeMetadataObject vElemObj22 = FakeMetadataFactory.createElement("vTest.vGroup2.e2", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING, 2); //$NON-NLS-1$
-        elements = new ArrayList(1);
+        Table vGroupObj2 = RealMetadataFactory.createVirtualGroup("vGroup2", vModelObj, vNode2); //$NON-NLS-1$
+        Column vElemObj20 = RealMetadataFactory.createElement("e0", vGroupObj2, DataTypeManager.DefaultDataTypes.INTEGER); //$NON-NLS-1$
+        Column vElemObj21 = RealMetadataFactory.createElement("e1", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        RealMetadataFactory.createElement("e2", vGroupObj2, DataTypeManager.DefaultDataTypes.STRING); //$NON-NLS-1$
+        elements = new ArrayList<Column>(2);
         elements.add(vElemObj20); 
         elements.add(vElemObj21);
-        FakeMetadataObject vGroup2Ap1 = FakeMetadataFactory.createAccessPattern("vTest.vGroup2.ap1", vGroupObj2, elements); //e1 //$NON-NLS-1$
+        RealMetadataFactory.createAccessPattern("vTest.vGroup2.ap1", vGroupObj2, elements); //e1 //$NON-NLS-1$
         
-        // set up validator metadata
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(modelObj);
-        store.addObject(groupObj);
-        store.addObject(elemObj0);
-        store.addObject(elemObj1);
-        store.addObject(elemObj2);
-        store.addObject(vModelObj);
-        store.addObject(vGroupObj);
-        store.addObject(vElemObj0);
-        store.addObject(vElemObj1);
-        store.addObject(vElemObj2);
-        store.addObject(vGroupAp1);
-        store.addObject(vGroupObj2);
-        store.addObject(vElemObj20);
-        store.addObject(vElemObj21);
-        store.addObject(vElemObj22);
-        store.addObject(vGroup2Ap1);
-        return new FakeMetadataFacade(store);
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "example4");
     }
     
 	// ################################## TEST HELPERS ################################
@@ -326,15 +275,13 @@
 	private static void examineReport(Object command,
 			String[] expectedStringArray, ValidatorReport report) {
 		// Get invalid objects from report
-		Collection actualObjs = new ArrayList();
+		Collection<LanguageObject> actualObjs = new ArrayList<LanguageObject>();
 		report.collectInvalidObjects(actualObjs);
 
 		// Compare expected and actual objects
-		Set<String> expectedStrings = new HashSet(Arrays.asList(expectedStringArray));
+		Set<String> expectedStrings = new HashSet<String>(Arrays.asList(expectedStringArray));
 		Set<String> actualStrings = new HashSet<String>();
-		Iterator objIter = actualObjs.iterator();
-		while(objIter.hasNext()) {
-		    LanguageObject obj = (LanguageObject) objIter.next();
+		for (LanguageObject obj : actualObjs) {
 		    actualStrings.add(SQLStringVisitor.getSQLString(obj));
 		}
 
@@ -347,9 +294,9 @@
 		}
 	}
 
-	private void helpValidateProcedure(String procedure, String userUpdateStr, String procedureType) {
+	private void helpValidateProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
 
         try {
         	validateProcedure(userUpdateStr, metadata);
@@ -377,9 +324,9 @@
 		}
 	}
 	
-	private void helpFailProcedure(String procedure, String userUpdateStr, String procedureType) {
+	private void helpFailProcedure(String procedure, String userUpdateStr, Table.TriggerEvent procedureType) {
 
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleUpdateProc(procedureType, procedure);
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleUpdateProc(procedureType, procedure);
 
         try {
         	validateProcedure(userUpdateStr, metadata);
@@ -394,7 +341,7 @@
 	
 	
     @Test public void testSelectStarWhereNoElementsAreNotSelectable() {
-        helpValidate("SELECT * FROM pm1.g5", new String[] {"SELECT * FROM pm1.g5"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT * FROM pm1.g5", new String[] {"SELECT * FROM pm1.g5"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
 	@Test public void testValidateSelect1() {        
@@ -450,45 +397,58 @@
 	}
     
     @Test public void testInvalidAggregate5() {
-        helpValidate("SELECT e1 || 'x' frOM pm1.g1 GROUP BY e2 + 1", new String[] {"e1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT e1 || 'x' frOM pm1.g1 GROUP BY e2 + 1", new String[] {"e1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testInvalidAggregate6() {
-        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1 HAVING e1 || 'x' > 0", new String[] {"e1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1 HAVING e1 || 'x' > 0", new String[] {"e1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testInvalidAggregate7() {
         helpValidate("SELECT StringKey, SUM(length(StringKey || 'x')) + 1 AS x FROM BQT1.SmallA GROUP BY StringKey || 'x' HAVING space(MAX(length((StringKey || 'x') || 'y'))) = '   '", //$NON-NLS-1$
-                     new String[] {"StringKey"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
+                     new String[] {"StringKey"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
     }
     
     @Test public void testInvalidAggregate8() {
         helpValidate("SELECT max(ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
-                     new String[] {"MAX(ObjectValue)"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
+                     new String[] {"MAX(ObjectValue)"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
     }
     
     @Test public void testInvalidAggregate9() {
         helpValidate("SELECT count(distinct ObjectValue) FROM BQT1.SmallA GROUP BY StringKey", //$NON-NLS-1$
-                     new String[] {"COUNT(DISTINCT ObjectValue)"}, FakeMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
+                     new String[] {"COUNT(DISTINCT ObjectValue)"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
     }
     
+    /**
+     * previously failed on stringkey, which is not entirely correct
+     */
+    @Test public void testInvalidAggregate10() {
+        helpValidate("SELECT xmlparse(document stringkey) FROM BQT1.SmallA GROUP BY xmlparse(document stringkey)", //$NON-NLS-1$
+                     new String[] {"XMLPARSE(DOCUMENT stringkey)"}, RealMetadataFactory.exampleBQTCached() ); //$NON-NLS-1$
+    }
+    
     @Test public void testInvalidAggregateIssue190644() {
-        helpValidate("SELECT e3 + 1 from pm1.g1 GROUP BY e2 + 1 HAVING e2 + 1 = 5", new String[] {"e3"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT e3 + 1 from pm1.g1 GROUP BY e2 + 1 HAVING e2 + 1 = 5", new String[] {"e3"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testValidAggregate1() {
-        helpValidate("SELECT (e2 + 1) * 2 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+        helpValidate("SELECT (e2 + 1) * 2 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ 
     }
 
     @Test public void testValidAggregate2() {
-        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+        helpValidate("SELECT e2 + 1 frOM pm1.g1 GROUP BY e2 + 1", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ 
     }
 
     @Test public void testValidAggregate3() {
         helpValidate("SELECT sum (IntKey), case when IntKey>=5000 then '5000 +' else '0-999' end " + //$NON-NLS-1$
             "FROM BQT1.SmallA GROUP BY case when IntKey>=5000 then '5000 +' else '0-999' end", //$NON-NLS-1$
-            new String[] {}, FakeMetadataFactory.exampleBQTCached());
+            new String[] {}, RealMetadataFactory.exampleBQTCached());
     }
+    
+    @Test public void testValidAggregate4() {
+        helpValidate("SELECT max(e1), e2 is null from pm1.g1 GROUP BY e2 is null", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+    }
+
 	@Test public void testInvalidHaving1() {        
         helpValidate("SELECT e3 FROM test.group HAVING e3 > 0", new String[] {"e3"}, exampleMetadata()); //$NON-NLS-1$ //$NON-NLS-2$
 	}
@@ -506,23 +466,23 @@
     }
     
     @Test public void testValidateCaseInGroupBy() {        
-        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE e2 WHEN 0 THEN 1 ELSE 2 END", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY CASE e2 WHEN 0 THEN 1 ELSE 2 END", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ 
     }
     
     @Test public void testValidateFunctionInGroupBy() {        
-        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ 
+        helpValidate("SELECT SUM(e2) FROM pm1.g1 GROUP BY (e2 + 1)", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ 
     }
 
     @Test public void testInvalidScalarSubqueryInGroupBy() {        
-        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY (SELECT 1)", new String[] { "(SELECT 1)" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY (SELECT 1)", new String[] { "(SELECT 1)" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testInvalidConstantInGroupBy() {        
-        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY 1", new String[] { "1" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY 1", new String[] { "1" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testInvalidReferenceInGroupBy() {        
-        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY ?", new String[] { "?" }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT COUNT(*) FROM pm1.g1 GROUP BY ?", new String[] { "?" }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testValidateObjectType1() {
@@ -558,11 +518,11 @@
     }
     
     @Test public void testValidateIntersectAll() {
-        helpValidate("SELECT e3 FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT e3 FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testValidateSetSelectInto() {
-        helpValidate("SELECT e3 into #temp FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 INTO #temp FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT e3 into #temp FROM pm1.g1 intersect all SELECT e3 FROM pm1.g1", new String[] {"SELECT e3 INTO #temp FROM pm1.g1 INTERSECT ALL SELECT e3 FROM pm1.g1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testInsert1() {
@@ -912,7 +872,7 @@
     }
     
     @Test public void testValidateSubquery3() {        
-        helpValidate("SELECT * FROM pm1.g1, (EXEC pm1.sq1( )) AS alias", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpValidate("SELECT * FROM pm1.g1, (EXEC pm1.sq1( )) AS alias", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
 
     @Test public void testValidateUnionWithSubquery() {        
@@ -948,7 +908,7 @@
     }
 
     @Test public void testValidateExec1() {
-        helpValidate("EXEC pm1.sq1()", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpValidate("EXEC pm1.sq1()", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
     
 	// valid variable declared
@@ -962,7 +922,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// validating criteria selector(on HAS CRITERIA), elements on it should be virtual group elements
@@ -979,7 +939,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// validating Translate CRITERIA, elements on it should be virtual group elements
@@ -994,7 +954,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// ROWS_UPDATED not assigned
@@ -1008,7 +968,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
 
 	// validating AssignmentStatement, more than one project symbol on the
@@ -1024,7 +984,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// validating AssignmentStatement, more than one project symbol on the
@@ -1040,7 +1000,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// TranslateCriteria on criteria of the if statement
@@ -1058,7 +1018,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// INPUT ised in command
@@ -1073,7 +1033,7 @@
         String userUpdateStr = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpValidateProcedure(procedure, userUpdateStr,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
@@ -1089,7 +1049,7 @@
         String userQuery = "UPDATE vm1.g1 SET e1='x'"; //$NON-NLS-1$
         
 		helpFailProcedure(procedure, userQuery,
-									 FakeMetadataObject.Props.UPDATE_PROCEDURE);
+									 Table.TriggerEvent.UPDATE);
     }
     
 	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
@@ -1106,7 +1066,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where e3= 1"; //$NON-NLS-1$
 
 		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
     
 	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
@@ -1123,7 +1083,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y like '%a' and e3= 1"; //$NON-NLS-1$
 
 		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 
 	
@@ -1140,7 +1100,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
 
 		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 	
 	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
@@ -1155,7 +1115,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y= 1"; //$NON-NLS-1$
 
 		helpValidateProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 
 	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
@@ -1170,7 +1130,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y > 1"; //$NON-NLS-1$
 
 		helpFailProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 
 	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
@@ -1185,7 +1145,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where e3 > 1"; //$NON-NLS-1$
 
 		helpValidateProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 
 	// virtual group elements used in procedure in if statement(TRANSLATE CRITERIA)
@@ -1200,7 +1160,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
 		helpValidateProcedure(procedure, userQuery, 
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
 
     // using aggregate function within a procedure - defect #8394
@@ -1215,7 +1175,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
 	// assigning null values to known datatype variable
@@ -1230,7 +1190,7 @@
 		String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
 		helpValidateProcedure(procedure, userQuery,
-				FakeMetadataObject.Props.UPDATE_PROCEDURE);
+				Table.TriggerEvent.UPDATE);
 	}
     
     @Test public void testDefect13643() {
@@ -1247,7 +1207,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpFailProcedure(procedure, userQuery, 
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testValidHaving() {
@@ -1256,17 +1216,17 @@
             "FROM bqt1.smalla " + //$NON-NLS-1$
             "GROUP BY intnum " + //$NON-NLS-1$
             "HAVING SUM(floatnum) > 1",  //$NON-NLS-1$
-            new String[] { }, FakeMetadataFactory.exampleBQTCached());
+            new String[] { }, RealMetadataFactory.exampleBQTCached());
     } 
     
     @Test public void testValidHaving2() {
         String sql =  "SELECT intkey FROM bqt1.smalla WHERE intkey = 1 " + //$NON-NLS-1$
             "GROUP BY intkey HAVING intkey = 1";         //$NON-NLS-1$
-        helpValidate(sql, new String[] {}, FakeMetadataFactory.exampleBQTCached());
+        helpValidate(sql, new String[] {}, RealMetadataFactory.exampleBQTCached());
     } 
     
     @Test public void testVirtualProcedure(){
-          helpValidate("EXEC pm1.vsp1()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+          helpValidate("EXEC pm1.vsp1()", new String[] { }, RealMetadataFactory.example1Cached());  //$NON-NLS-1$
     }
         
     @Test public void testSelectWithNoFrom() {        
@@ -1283,7 +1243,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     /**
@@ -1300,7 +1260,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     /**
@@ -1317,12 +1277,12 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
 
     
     @Test public void testSelectIntoPhysicalGroup() {
-        helpValidate("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] { }, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpValidate("SELECT e1, e2, e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] { }, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
@@ -1333,7 +1293,7 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testSelectIntoPhysicalGroupNotUpdateable_Defect16857() {
@@ -1345,7 +1305,7 @@
     }
     
     @Test public void testInvalidSelectIntoTooManyElements() {
-    	helpValidate("SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpValidate("SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3, e4, 'val' INTO pm1.g1 FROM pm1.g2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
         
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
@@ -1356,11 +1316,11 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testInvalidSelectIntoTooFewElements() {
-    	helpValidate("SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpValidate("SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, e2, e3 INTO pm1.g1 FROM pm1.g2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
         
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
@@ -1371,11 +1331,11 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testInvalidSelectIntoIncorrectTypes() {
-        helpValidate("SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2", new String[] {"SELECT e1, convert(e2, string), e3, e4 INTO pm1.g1 FROM pm1.g2"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
         
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
@@ -1386,15 +1346,15 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testSelectIntoWithStar() {
-        helpResolve("SELECT * INTO pm1.g1 FROM pm1.g2", FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpResolve("SELECT * INTO pm1.g1 FROM pm1.g2", RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
     
     @Test public void testInvalidSelectIntoWithStar() {
-        helpValidate("SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1", new String[] {"SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1", new String[] {"SELECT * INTO pm1.g1 FROM pm1.g2, pm1.g1"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
         
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
@@ -1405,11 +1365,11 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpFailProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testSelectIntoVirtualGroup() {
-        helpValidate("SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpValidate("SELECT e1, e2, e3, e4 INTO vm1.g1 FROM pm1.g2", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
         
         String procedure = "CREATE PROCEDURE  "; //$NON-NLS-1$
         procedure = procedure + "BEGIN\n"; //$NON-NLS-1$
@@ -1420,16 +1380,16 @@
         String userQuery = "UPDATE vm1.g3 SET x='x' where y = 1"; //$NON-NLS-1$
 
         helpValidateProcedure(procedure, userQuery,
-                FakeMetadataObject.Props.UPDATE_PROCEDURE);
+                Table.TriggerEvent.UPDATE);
     }
     
     @Test public void testVirtualProcedure2(){
-          helpValidate("EXEC pm1.vsp13()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+          helpValidate("EXEC pm1.vsp13()", new String[] { }, RealMetadataFactory.example1Cached());  //$NON-NLS-1$
     }
 
     //procedure that has another procedure in the transformation
     @Test public void testVirtualProcedure3(){
-        helpValidate("EXEC pm1.vsp27()", new String[] { }, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+        helpValidate("EXEC pm1.vsp27()", new String[] { }, RealMetadataFactory.example1Cached());  //$NON-NLS-1$
     }
     
     @Test public void testNonEmbeddedSubcommand_defect11000() {        
@@ -1438,13 +1398,13 @@
     
     @Test public void testValidateObjectInComparison() throws Exception {
         String sql = "SELECT IntKey FROM BQT1.SmallA WHERE ObjectValue = 5";   //$NON-NLS-1$
-        ValidatorReport report = helpValidate(sql, new String[] {"ObjectValue = 5"}, FakeMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
+        ValidatorReport report = helpValidate(sql, new String[] {"ObjectValue = 5"}, RealMetadataFactory.exampleBQTCached()); //$NON-NLS-1$
         assertEquals("Expressions of type OBJECT, CLOB, BLOB, or XML cannot be used in comparison: ObjectValue = 5.", report.toString()); //$NON-NLS-1$
     }
 
     @Test public void testValidateAssignmentWithFunctionOnParameter_InServer() throws Exception{
         String sql = "EXEC pm1.vsp36(5)";  //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         Command command = new QueryParser().parseCommand(sql);
         QueryResolver.resolveCommand(command, metadata);
@@ -1455,7 +1415,7 @@
     }
 
     @Test public void testDefect9917() throws Exception{
-    	QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         String sql = "SELECT lookup('pm1.g1', 'e1a', 'e2', e2) AS x, lookup('pm1.g1', 'e4', 'e3', e3) AS y FROM pm1.g1"; //$NON-NLS-1$
         Command command = new QueryParser().parseCommand(sql);
         try{
@@ -1486,7 +1446,7 @@
     }
     
     @Test public void testDefect12107() throws Exception{
-    	QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+    	QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         String sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e2', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
         Command command = helpResolve(sql, metadata);
         sql = "SELECT SUM(DISTINCT lookup('pm1.g1', 'e3', 'e2', e2)) FROM pm1.g1"; //$NON-NLS-1$
@@ -1508,7 +1468,7 @@
     @Test public void testValidateDynamicCommandWithNonTempGroup_InModeler() throws Exception{
         // SQL is same as pm1.vsp36() in example1 
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into pm1.g3; END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         // Validate
         ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
@@ -1518,7 +1478,7 @@
     
     @Test public void testDynamicDupUsing() throws Exception {
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN execute string 'select ' || '1' as X integer into #temp using id=1, id=2; END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         // Validate
         ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
@@ -1529,7 +1489,7 @@
     @Test public void testValidateAssignmentWithFunctionOnParameter_InModeler() throws Exception{
         // SQL is same as pm1.vsp36() in example1 
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN DECLARE integer x; x = pm1.vsp36.param1 * 2; SELECT x; END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         // Validate
         ValidatorReport report = helpValidateInModeler("pm1.vsp36", sql, metadata);  //$NON-NLS-1$
@@ -1540,7 +1500,7 @@
         String sql = "SELECT BQT1.SmallA.DateValue, BQT2.SmallB.ObjectValue FROM BQT1.SmallA, BQT2.SmallB " +  //$NON-NLS-1$
             "WHERE BQT1.SmallA.DateValue = BQT2.SmallB.DateValue AND BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue " + //$NON-NLS-1$
             "AND BQT1.SmallA.IntKey < 30 AND BQT2.SmallB.IntKey < 30 ORDER BY BQT1.SmallA.DateValue"; //$NON-NLS-1$
-        QueryMetadataInterface metadata = FakeMetadataFactory.exampleBQTCached();
+        QueryMetadataInterface metadata = RealMetadataFactory.exampleBQTCached();
         
         // Validate
         helpValidate(sql, new String[] {"BQT1.SmallA.ObjectValue = BQT2.SmallB.ObjectValue"}, metadata);  //$NON-NLS-1$ 
@@ -1549,16 +1509,56 @@
     @Test public void testDefect16772() throws Exception{
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"; //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         // Validate
         ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata);  //$NON-NLS-1$ 
         assertEquals("Expected report to have no validation failures", false, report.hasItems()); //$NON-NLS-1$
     }
+    
+    @Test public void testDupLabel() throws Exception{
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) x : begin SELECT 1 AS x; x: begin atomic select 2 as x; end end END"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata);  //$NON-NLS-1$ 
+        examineReport(sql, new String[] {"x : BEGIN ATOMIC\nSELECT 2 AS x;\nEND"}, report);
+    }
+    
+    @Test public void testInvalidContinue() throws Exception{
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN continue; END"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata);  //$NON-NLS-1$ 
+        examineReport(sql, new String[] {"CONTINUE;"}, report);
+    }
+    
+    @Test public void testInvalidLabel() throws Exception{
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (pm1.vsp42.param1 > 0) x : begin continue y; end END"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata);  //$NON-NLS-1$ 
+        examineReport(sql, new String[] {"CONTINUE y;"}, report);
+    }
+    
+    @Test public void testNonQueryAgg() throws Exception{
+        String sql = "CREATE VIRTUAL PROCEDURE BEGIN IF (max(pm1.vsp42.param1) > 0) SELECT 1 AS x; ELSE SELECT 0 AS x; END"; //$NON-NLS-1$
+        
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
+        
+        // Validate
+        ValidatorReport report = helpValidateInModeler("pm1.vsp42", sql, metadata);  //$NON-NLS-1$ 
+        examineReport(sql, new String[] {"MAX(pm1.vsp42.param1)"}, report);
+    }
 	
 	@Test public void testDefect14886() throws Exception{        
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN END";  //$NON-NLS-1$        
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         Command command = new QueryParser().parseCommand(sql);
         QueryResolver.resolveCommand(command, metadata);
@@ -1571,9 +1571,9 @@
 	
     @Test public void testDefect21389() throws Exception{        
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * INTO #temptable FROM pm1.g1; INSERT INTO #temptable (e1) VALUES ('a'); END"; //$NON-NLS-1$      
-        FakeMetadataFacade metadata = FakeMetadataFactory.example1();
-        FakeMetadataObject e1 = metadata.getStore().findObject("pm1.g1.e1", FakeMetadataObject.ELEMENT); //$NON-NLS-1$
-        e1.putProperty(FakeMetadataObject.Props.UPDATE, Boolean.FALSE);
+        TransformationMetadata metadata = RealMetadataFactory.example1();
+        Column c = metadata.getElementID("pm1.g1.e1"); //$NON-NLS-1$
+        c.setUpdatable(false);
         
         Command command = new QueryParser().parseCommand(sql);
         QueryResolver.resolveCommand(command, metadata);
@@ -1592,11 +1592,11 @@
     }
     
     @Test public void testInvalidLimit() {
-        helpValidate("SELECT * FROM pm1.g1 LIMIT -5", new String[] {"LIMIT -5"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT * FROM pm1.g1 LIMIT -5", new String[] {"LIMIT -5"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testInvalidLimit_Offset() {
-    	helpValidate("SELECT * FROM pm1.g1 LIMIT -1, 100", new String[] {"LIMIT -1, 100"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpValidate("SELECT * FROM pm1.g1 LIMIT -1, 100", new String[] {"LIMIT -1, 100"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     /**
@@ -1609,7 +1609,7 @@
      */
     @Test public void testCase4237() {
 
-        FakeMetadataFacade metadata = helpCreateCase4237VirtualProcedureMetadata();
+        QueryMetadataInterface metadata = helpCreateCase4237VirtualProcedureMetadata();
         
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"; //$NON-NLS-1$ 
         Command command = helpResolve(sql, new GroupSymbol("vm1.sp"), Command.TYPE_STORED_PROCEDURE, metadata);
@@ -1622,7 +1622,7 @@
      */
     @Test public void testCase4237InlineView() {
 
-        FakeMetadataFacade metadata = helpCreateCase4237VirtualProcedureMetadata();
+        QueryMetadataInterface metadata = helpCreateCase4237VirtualProcedureMetadata();
         
         String sql = "CREATE VIRTUAL PROCEDURE BEGIN SELECT * FROM (EXEC pm1.sp(vm1.sp.in1)) AS FOO; END"; //$NON-NLS-1$ 
         Command command = helpResolve(sql, new GroupSymbol("vm1.sp"), Command.TYPE_STORED_PROCEDURE, metadata);
@@ -1634,44 +1634,38 @@
      * a virtual stored procedure which calls the physical one. 
      * @return
      */
-    private FakeMetadataFacade helpCreateCase4237VirtualProcedureMetadata() {
-        FakeMetadataObject physicalModel = FakeMetadataFactory.createPhysicalModel("pm1"); //$NON-NLS-1$
-        FakeMetadataObject resultSet = FakeMetadataFactory.createResultSet("pm1.rs", physicalModel, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject returnParam = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, resultSet);  //$NON-NLS-1$
-        FakeMetadataObject inParam = FakeMetadataFactory.createParameter("in", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
-        FakeMetadataObject storedProcedure = FakeMetadataFactory.createStoredProcedure("pm1.sp", physicalModel, Arrays.asList(new FakeMetadataObject[] { returnParam, inParam }));  //$NON-NLS-1$ //$NON-NLS-2$
+    private TransformationMetadata helpCreateCase4237VirtualProcedureMetadata() {
+    	MetadataStore metadataStore = new MetadataStore();
+        Schema physicalModel = RealMetadataFactory.createPhysicalModel("pm1", metadataStore); //$NON-NLS-1$
+        ColumnSet<Procedure> resultSet = RealMetadataFactory.createResultSet("pm1.rs", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter inParam = RealMetadataFactory.createParameter("in", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
+        Procedure storedProcedure = RealMetadataFactory.createStoredProcedure("sp", physicalModel, Arrays.asList(inParam));  //$NON-NLS-1$ //$NON-NLS-2$
+        storedProcedure.setResultSet(resultSet);
         
-        FakeMetadataObject virtualModel = FakeMetadataFactory.createVirtualModel("vm1"); //$NON-NLS-1$
-        FakeMetadataObject virtualResultSet = FakeMetadataFactory.createResultSet("vm1.rs", physicalModel, new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-        FakeMetadataObject virtualReturnParam = FakeMetadataFactory.createParameter("ret", 1, ParameterInfo.RESULT_SET, DataTypeManager.DefaultDataTypes.OBJECT, virtualResultSet);  //$NON-NLS-1$
-        FakeMetadataObject virtualInParam = FakeMetadataFactory.createParameter("in1", 2, ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING, null);  //$NON-NLS-1$
+        Schema virtualModel = RealMetadataFactory.createVirtualModel("vm1", metadataStore); //$NON-NLS-1$
+        ColumnSet<Procedure> virtualResultSet = RealMetadataFactory.createResultSet("vm1.rs", new String[] { "e1", "e2" }, new String[] { DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.INTEGER }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        ProcedureParameter virtualInParam = RealMetadataFactory.createParameter("in1", ParameterInfo.IN, DataTypeManager.DefaultDataTypes.STRING);  //$NON-NLS-1$
         QueryNode queryNode = new QueryNode("CREATE VIRTUAL PROCEDURE BEGIN EXEC pm1.sp(vm1.sp.in1); END"); //$NON-NLS-1$ //$NON-NLS-2$
-        FakeMetadataObject virtualStoredProcedure = FakeMetadataFactory.createVirtualProcedure("vm1.sp", physicalModel, Arrays.asList(new FakeMetadataObject[] { virtualReturnParam, virtualInParam }), queryNode);  //$NON-NLS-1$
-                
-        FakeMetadataStore store = new FakeMetadataStore();
-        store.addObject(physicalModel);
-        store.addObject(resultSet);
-        store.addObject(storedProcedure);
-        store.addObject(virtualModel);
-        store.addObject(virtualResultSet);
-        store.addObject(virtualStoredProcedure);
-        return new FakeMetadataFacade(store);
+        Procedure virtualStoredProcedure = RealMetadataFactory.createVirtualProcedure("sp", virtualModel, Arrays.asList(virtualInParam), queryNode);  //$NON-NLS-1$
+        virtualStoredProcedure.setResultSet(virtualResultSet);        
+        
+        return RealMetadataFactory.createTransformationMetadata(metadataStore, "case4237");
     }       
     
     @Test public void testSelectIntoWithNull() {
-        helpValidate("SELECT null, null, null, null INTO pm1.g1 FROM pm1.g2", new String[] {}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$
+        helpValidate("SELECT null, null, null, null INTO pm1.g1 FROM pm1.g2", new String[] {}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$
     }
     
     @Test public void testCreateWithNonSortablePrimaryKey() {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         Command command = helpResolve("create local temporary table x (column1 string, column2 clob, primary key (column2))", metadata); //$NON-NLS-1$
-        helpRunValidator(command, new String[] {"column2"}, FakeMetadataFactory.example1Cached()); 
+        helpRunValidator(command, new String[] {"column2"}, RealMetadataFactory.example1Cached()); 
     }
         
     @Test public void testDropNonTemporary() {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         Command command = helpResolve("drop table pm1.g1", metadata); //$NON-NLS-1$
-        helpRunValidator(command, new String[] {command.toString()}, FakeMetadataFactory.example1Cached()); 
+        helpRunValidator(command, new String[] {command.toString()}, RealMetadataFactory.example1Cached()); 
     }
     
     @Test public void testNestedContexts() {
@@ -1683,7 +1677,7 @@
     }
     
     @Test public void testInsertIntoVirtualWithQuery() throws Exception {
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         Command command = helpResolve("insert into vm1.g1 select 1, 2, true, 3", metadata); //$NON-NLS-1$
         ValidatorReport report = Validator.validate(command, metadata);
         assertTrue(report.getItems().isEmpty());
@@ -1697,7 +1691,7 @@
                                 .append("select column1 from x;\n") //$NON-NLS-1$
                                 .append("END\n"); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         // Validate
         ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata);  //$NON-NLS-1$
@@ -1711,7 +1705,7 @@
         procedure += "select * from variables;\n"; //$NON-NLS-1$
         procedure += "END\n"; //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         Command command = helpResolve(procedure, metadata);
         helpRunValidator(command, new String[] {"variables"}, metadata); //$NON-NLS-1$
@@ -1758,12 +1752,12 @@
 	
     @Test public void testXpathValueValid_defect15088() {
         String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', 'a/b/c')"; //$NON-NLS-1$
-        helpValidate(userSql, new String[] {}, FakeMetadataFactory.exampleBQTCached());        
+        helpValidate(userSql, new String[] {}, RealMetadataFactory.exampleBQTCached());        
     }
 
     @Test public void testXpathValueInvalid_defect15088() throws Exception {
         String userSql = "SELECT xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"; //$NON-NLS-1$
-        helpValidate(userSql, new String[] {"xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"}, FakeMetadataFactory.exampleBQTCached());
+        helpValidate(userSql, new String[] {"xpathValue('<?xml version=\"1.0\" encoding=\"utf-8\" ?><a><b><c>test</c></b></a>', '//*[local-name()=''bookName\"]')"}, RealMetadataFactory.exampleBQTCached());
     }
     
     @Test public void testTextTableNegativeWidth() {        
@@ -1778,85 +1772,89 @@
         helpValidate("SELECT * from texttable(null columns x string width 1 DELIMITER 'z') as x", new String[] {"TEXTTABLE(null COLUMNS x string WIDTH 1 DELIMITER 'z') AS x"}, RealMetadataFactory.exampleBQTCached()); 
 	}
     
+    @Test public void testTextTableNoRowDelimiter() {        
+        helpValidate("SELECT * from texttable(null columns x string NO ROW DELIMITER) as x", new String[] {"TEXTTABLE(null COLUMNS x string NO ROW DELIMITER) AS x"}, RealMetadataFactory.exampleBQTCached()); 
+	}
+    
     @Test public void testXMLNamespaces() {
-    	helpValidate("select xmlforest(xmlnamespaces(no default, default 'http://foo'), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES(NO DEFAULT, DEFAULT 'http://foo')"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select xmlforest(xmlnamespaces(no default, default 'http://foo'), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES(NO DEFAULT, DEFAULT 'http://foo')"}, RealMetadataFactory.example1Cached());
     }
 
     @Test public void testXMLNamespacesReserved() {
-    	helpValidate("select xmlforest(xmlnamespaces('http://foo' as xmlns), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES('http://foo' AS xmlns)"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select xmlforest(xmlnamespaces('http://foo' as xmlns), e1 as \"table\") from pm1.g1", new String[] {"XMLNAMESPACES('http://foo' AS xmlns)"}, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testXMLTablePassingMultipleContext() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing xmlparse(DOCUMENT '<a/>'), xmlparse(DOCUMENT '<b/>')) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>'), XMLPARSE(DOCUMENT '<b/>')) AS x"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select * from pm1.g1, xmltable('/' passing xmlparse(DOCUMENT '<a/>'), xmlparse(DOCUMENT '<b/>')) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>'), XMLPARSE(DOCUMENT '<b/>')) AS x"}, RealMetadataFactory.example1Cached());
     }
 
     @Ignore("this is actually handled by saxon and will show up during resolving")
     @Test public void testXMLTablePassingSameName() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing {x '<a/>'} as a, {x '<b/>'} as a) as x", new String[] {"xmltable('/' passing e1, e1 || 'x') as x"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select * from pm1.g1, xmltable('/' passing {x '<a/>'} as a, {x '<b/>'} as a) as x", new String[] {"xmltable('/' passing e1, e1 || 'x') as x"}, RealMetadataFactory.example1Cached());
     }
 
     @Test public void testXMLTablePassingContextType() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing 2) as x", new String[] {"XMLTABLE('/' PASSING 2) AS x"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select * from pm1.g1, xmltable('/' passing 2) as x", new String[] {"XMLTABLE('/' PASSING 2) AS x"}, RealMetadataFactory.example1Cached());
     }
 
     @Test public void testXMLTableMultipleOrdinals() {
-    	helpValidate("select * from pm1.g1, xmltable('/' passing XMLPARSE(DOCUMENT '<a/>') columns x for ordinality, y for ordinality) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>') COLUMNS x FOR ORDINALITY, y FOR ORDINALITY) AS x"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select * from pm1.g1, xmltable('/' passing XMLPARSE(DOCUMENT '<a/>') columns x for ordinality, y for ordinality) as x", new String[] {"XMLTABLE('/' PASSING XMLPARSE(DOCUMENT '<a/>') COLUMNS x FOR ORDINALITY, y FOR ORDINALITY) AS x"}, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testXMLTableContextRequired() {
-    	helpValidate("select * from xmltable('/a/b' passing convert('<a/>', xml) as a columns x for ordinality, c integer path '.') as x", new String[] {"XMLTABLE('/a/b' PASSING convert('<a/>', xml) AS a COLUMNS x FOR ORDINALITY, c integer PATH '.') AS x"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select * from xmltable('/a/b' passing convert('<a/>', xml) as a columns x for ordinality, c integer path '.') as x", new String[] {"XMLTABLE('/a/b' PASSING convert('<a/>', xml) AS a COLUMNS x FOR ORDINALITY, c integer PATH '.') AS x"}, RealMetadataFactory.example1Cached());
     }
 
     @Test public void testXMLQueryPassingContextType() {
-    	helpValidate("select xmlquery('/' passing 2)", new String[] {"XMLQUERY('/' PASSING 2)"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select xmlquery('/' passing 2)", new String[] {"XMLQUERY('/' PASSING 2)"}, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testQueryString() {
-    	helpValidate("select querystring('/', '1')", new String[] {"QUERYSTRING('/', '1')"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select querystring('/', '1')", new String[] {"QUERYSTRING('/', '1')"}, RealMetadataFactory.example1Cached());
     }
 
     @Test public void testXmlNameValidation() throws Exception {
-    	helpValidate("select xmlelement(\":\")", new String[] {"XMLELEMENT(NAME \":\")"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select xmlelement(\":\")", new String[] {"XMLELEMENT(NAME \":\")"}, RealMetadataFactory.example1Cached());
     }
 
     @Test public void testXmlParse() throws Exception {
-    	helpValidate("select xmlparse(content e2) from pm1.g1", new String[] {"XMLPARSE(CONTENT e2)"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select xmlparse(content e2) from pm1.g1", new String[] {"XMLPARSE(CONTENT e2)"}, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testDecode() throws Exception {
-    	helpValidate("select to_bytes(e1, '?') from pm1.g1", new String[] {"to_bytes(e1, '?')"}, FakeMetadataFactory.example1Cached());
+    	helpValidate("select to_bytes(e1, '?') from pm1.g1", new String[] {"to_bytes(e1, '?')"}, RealMetadataFactory.example1Cached());
     }
     
     @Test public void testValidateXMLAGG() {        
-        helpValidate("SELECT XMLAGG(e1) from pm1.g1", new String[] {"XMLAGG(e1)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT XMLAGG(e1) from pm1.g1", new String[] {"XMLAGG(e1)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
 	}
     
     @Test public void testValidateBooleanAgg() {        
-        helpValidate("SELECT EVERY(e1) from pm1.g1", new String[] {"EVERY(e1)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT EVERY(e1) from pm1.g1", new String[] {"EVERY(e1)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
 	}
     
     @Test public void testValidateStatAgg() {        
-        helpValidate("SELECT stddev_pop(distinct e2) from pm1.g1", new String[] {"STDDEV_POP(DISTINCT e2)"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT stddev_pop(distinct e2) from pm1.g1", new String[] {"STDDEV_POP(DISTINCT e2)"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
 	}
     
     @Test public void testValidateScalarSubqueryTooManyColumns() {        
-        helpValidate("SELECT e2, (SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+        helpValidate("SELECT e2, (SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testInvalidIntoSubquery() {
-    	helpValidate("SELECT e2, (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpValidate("SELECT e2, (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') FROM pm1.g2", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testInvalidIntoSubquery1() {
-    	helpValidate("SELECT e2 FROM pm1.g2 WHERE EXISTS (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpValidate("SELECT e2 FROM pm1.g2 WHERE EXISTS (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testInvalidIntoSubquery2() {
-    	helpValidate("SELECT * FROM (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') x", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpValidate("SELECT * FROM (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') x", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
     @Test public void testInvalidIntoSubquery3() {
-    	helpValidate("SELECT e2 FROM pm1.g2 WHERE e2 in (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, FakeMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
+    	helpValidate("SELECT e2 FROM pm1.g2 WHERE e2 in (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3')", new String[] {"SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3'"}, RealMetadataFactory.example1Cached()); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
     @Test public void testInvalidIntoSubquery4() throws Exception {
@@ -1865,7 +1863,7 @@
                                 .append("loop on (SELECT e1, e2 INTO #x FROM pm1.g1 WHERE e2 = '3') as x\n") //$NON-NLS-1$
                                 .append("BEGIN\nSELECT 1;\nEND\nSELECT 1\n;END\n"); //$NON-NLS-1$
         
-        QueryMetadataInterface metadata = FakeMetadataFactory.example1Cached();
+        QueryMetadataInterface metadata = RealMetadataFactory.example1Cached();
         
         // Validate
         ValidatorReport report = helpValidateInModeler("pm1.vsp36", procedure.toString(), metadata);  //$NON-NLS-1$
@@ -1875,28 +1873,76 @@
     @Test public void testDisallowUpdateOnMultisourceElement() throws Exception {  
     	Set<String> models = new HashSet<String>();
     	models.add("pm1");
-        ValidatorReport report = helpValidateInModeler("pm1.vsp36", "UPDATE PM1.G1 set SOURCE_NAME='blah'", new MultiSourceMetadataWrapper(FakeMetadataFactory.example1(), models));  //$NON-NLS-1$
+        ValidatorReport report = helpValidateInModeler("pm1.vsp36", "UPDATE PM1.G1 set SOURCE_NAME='blah'", new MultiSourceMetadataWrapper(RealMetadataFactory.example1(), models));  //$NON-NLS-1$
         assertEquals(report.toString(), 1, report.getItems().size());
     }
     
     @Test public void testDisallowProjectIntoMultiSource() throws Exception {  
     	Set<String> models = new HashSet<String>();
     	models.add("pm1");
-        helpValidate("insert into pm1.g1 select * from pm1.g1", new String[] {"pm1.g1"}, new MultiSourceMetadataWrapper(FakeMetadataFactory.example1(), models));  //$NON-NLS-1$
+        helpValidate("insert into pm1.g1 select * from pm1.g1", new String[] {"pm1.g1"}, new MultiSourceMetadataWrapper(RealMetadataFactory.example1(), models));  //$NON-NLS-1$
     }
     
     @Test public void testTextAggEncoding() throws Exception {
-    	helpValidate("select textagg(for e1 encoding abc) from pm1.g1", new String[] {"TEXTAGG(FOR e1 ENCODING abc)"}, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+    	helpValidate("select textagg(for e1 encoding abc) from pm1.g1", new String[] {"TEXTAGG(FOR e1 ENCODING abc)"}, RealMetadataFactory.example1Cached());  //$NON-NLS-1$
     }
     
     @Test public void testTextAggHeader() throws Exception {
-    	helpValidate("select textagg(for e1 || 1 HEADER) from pm1.g1", new String[] {"TEXTAGG(FOR (e1 || 1) HEADER)"}, FakeMetadataFactory.example1Cached());  //$NON-NLS-1$
+    	helpValidate("select textagg(for e1 || 1 HEADER) from pm1.g1", new String[] {"TEXTAGG(FOR (e1 || 1) HEADER)"}, RealMetadataFactory.example1Cached());  //$NON-NLS-1$
     }
     
     @Test public void testMultiSourceProcValue() throws Exception {  
     	Set<String> models = new HashSet<String>();
     	models.add("MultiModel");
-        helpValidate("exec MultiModel.proc('a', (select 1))", new String[] {"MultiModel.proc.source_name"}, new MultiSourceMetadataWrapper(FakeMetadataFactory.exampleMultiBinding(), models));  //$NON-NLS-1$
+        helpValidate("exec MultiModel.proc('a', (select 1))", new String[] {"MultiModel.proc.source_name"}, new MultiSourceMetadataWrapper(RealMetadataFactory.exampleMultiBinding(), models));  //$NON-NLS-1$
     }
+    
+	@Test public void testFailAggregateInGroupBy() {
+		helpValidate("SELECT max(e1) FROM pm1.g1 GROUP BY count(e2)", new String[] {"COUNT(e2)"}, RealMetadataFactory.example1Cached());		
+	}
+	
+	@Test public void testFailAggregateInWhere() {
+		helpValidate("SELECT e1 FROM pm1.g1 where count(e2) = 1", new String[] {"COUNT(e2)"}, RealMetadataFactory.example1Cached());		
+	}
 
+	@Test public void testFailAggregateInFrom() {
+		helpValidate("SELECT g2.e1 FROM pm1.g1 inner join pm1.g2 on (avg(g1.e2) = g2.e2)", new String[] {"AVG(g1.e2)"}, RealMetadataFactory.example1Cached());		
+	}
+	
+	@Test public void testFailAggregateFilterSubquery() {
+		helpValidate("SELECT min(g1.e1) filter (where (select 1) = 1) from pm1.g1", new String[] {"(SELECT 1) = 1"}, RealMetadataFactory.example1Cached());		
+	}
+
+	@Test public void testNestedAgg() {
+		helpValidate("SELECT min(g1.e1) filter (where max(e2) = 1) from pm1.g1", new String[] {"MAX(e2)"}, RealMetadataFactory.example1Cached());		
+	}
+	
+	@Test public void testWindowFunction() {
+		helpValidate("SELECT e1 from pm1.g1 where row_number() over (order by e2) = 1", new String[] {"ROW_NUMBER() OVER (ORDER BY e2)"}, RealMetadataFactory.example1Cached());		
+	}
+	
+	@Test public void testWindowFunction1() {
+		helpValidate("SELECT 1 from pm1.g1 having row_number() over (order by e2) = 1", new String[] {"e2", "ROW_NUMBER() OVER (ORDER BY e2)"}, RealMetadataFactory.example1Cached());		
+	}
+	
+	@Test public void testWindowFunctionWithoutOrdering() {
+		helpValidate("SELECT row_number() over () from pm1.g1", new String[] {"ROW_NUMBER() OVER ()"}, RealMetadataFactory.example1Cached());		
+	}
+
+	@Test public void testWindowFunctionWithNestedOrdering() {
+		helpValidate("SELECT xmlagg(xmlelement(name x, e1) order by e2) over () from pm1.g1", new String[] {"XMLAGG(XMLELEMENT(NAME x, e1) ORDER BY e2) OVER ()"}, RealMetadataFactory.example1Cached());		
+	}
+	
+	@Test public void testWindowFunctionWithNestedaggAllowed() {
+		helpValidate("SELECT max(e1) over (order by max(e2)) from pm1.g1 group by e1", new String[] {}, RealMetadataFactory.example1Cached());		
+	}
+
+	@Test public void testWindowFunctionWithNestedaggAllowed1() {
+		helpValidate("SELECT max(min(e1)) over (order by max(e2)) from pm1.g1 group by e1", new String[] {"MIN(e1)"}, RealMetadataFactory.example1Cached());		
+	}
+	
+	@Test public void testWindowFunctionWithoutFrom() {
+		helpValidate("select count(*) over () as y", new String[] {"COUNT(*) OVER ()"}, RealMetadataFactory.example1Cached());
+	}
+	
 }

Copied: branches/as7/engine/src/test/resources/TestXMLPlanningEnhancements-testThreeWayOrWithNestedSiblings.xml (from rev 3382, trunk/engine/src/test/resources/TestXMLPlanningEnhancements-testThreeWayOrWithNestedSiblings.xml)
===================================================================
--- branches/as7/engine/src/test/resources/TestXMLPlanningEnhancements-testThreeWayOrWithNestedSiblings.xml	                        (rev 0)
+++ branches/as7/engine/src/test/resources/TestXMLPlanningEnhancements-testThreeWayOrWithNestedSiblings.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Catalogs>
+   <Catalog>
+      <Items>
+         <Item ItemID="001">
+            <Name>Lamp</Name>
+            <Quantity>5</Quantity>
+            <Suppliers>
+               <Supplier SupplierID="51">
+                  <Name>Chucky</Name>
+                  <Zip>11111</Zip>
+               </Supplier>
+               <Supplier SupplierID="52">
+                  <Name>Biff's Stuff</Name>
+                  <Zip>22222</Zip>
+               </Supplier>
+               <Supplier SupplierID="53">
+                  <Name>AAAA</Name>
+                  <Zip>33333</Zip>
+               </Supplier>
+               <Supplier SupplierID="56">
+                  <Name>Microsoft</Name>
+                  <Zip>66666</Zip>
+               </Supplier>
+            </Suppliers>
+            <Orders>
+               <Order OrderID="1">
+                  <Name>KMart</Name>
+                  <Zip>12345</Zip>
+               </Order>
+               <Order OrderID="2">
+                  <Name>Sun</Name>
+                  <Zip>94040</Zip>
+               </Order>
+               <Order OrderID="3">
+                  <Name>Cisco</Name>
+                  <Zip>94041</Zip>
+               </Order>
+               <Order OrderID="4">
+                  <Name>Doc</Name>
+                  <Zip>94042</Zip>
+               </Order>
+            </Orders>
+         </Item>
+         <Item ItemID="003">
+            <Name>Goat</Name>
+            <Quantity>4</Quantity>
+            <Suppliers>
+               <Supplier SupplierID="56">
+                  <Name>Microsoft</Name>
+                  <Zip>66666</Zip>
+               </Supplier>
+            </Suppliers>
+            <Orders>
+               <Order OrderID="7">
+                  <Name>Inktomi</Name>
+                  <Zip>94044</Zip>
+               </Order>
+            </Orders>
+         </Item>
+      </Items>
+   </Catalog>
+</Catalogs>
\ No newline at end of file


Property changes on: branches/as7/engine/src/test/resources/text/cdm_dos_win.txt
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/7.4.x/engine/src/test/resources/text/cdm_dos_win.txt:3149-3171
   + /branches/7.4.x/engine/src/test/resources/text/cdm_dos_win.txt:3149-3164,3172-3217
/trunk/engine/src/test/resources/text/cdm_dos_win.txt:3188-3382

Modified: branches/as7/hibernate-dialect/pom.xml
===================================================================
--- branches/as7/hibernate-dialect/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/hibernate-dialect/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>teiid-hibernate-dialect</artifactId>

Modified: branches/as7/jboss-integration/pom.xml
===================================================================
--- branches/as7/jboss-integration/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,7 +2,7 @@
   <parent>
     <artifactId>teiid-parent</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.jboss.teiid</groupId>

Copied: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/AssosiateCallerIdentityLoginModule.java (from rev 3382, trunk/jboss-integration/src/main/java/org/teiid/jboss/AssosiateCallerIdentityLoginModule.java)
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/AssosiateCallerIdentityLoginModule.java	                        (rev 0)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/AssosiateCallerIdentityLoginModule.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,87 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2007, JBoss Inc., and individual contributors as indicated
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This 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 software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.teiid.jboss;
+
+import java.security.Principal;
+import java.security.acl.Group;
+import java.util.Map;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SubjectInfo;
+import org.jboss.security.auth.spi.AbstractServerLoginModule;
+
+/**
+ * This login modules simply takes the subject in the current context and adds
+ * its principle to shared state. This is same as CallerIdentityLoginModule,
+ * just it does not extend the AbstractPasswordCredentialLoginModule
+ */
+public class AssosiateCallerIdentityLoginModule extends AbstractServerLoginModule {
+
+	private Principal principal;
+	
+	public void initialize(Subject subject, CallbackHandler handler,
+			Map sharedState, Map options) {
+		super.initialize(subject, handler, sharedState, options);
+	}
+
+	/**
+	 * Performs the login association between the caller and the resource for a
+	 * 1 to 1 mapping. This acts as a login propagation strategy and is useful
+	 * for single-sign on requirements
+	 * 
+	 * @return True if authentication succeeds
+	 * @throws LoginException
+	 */
+	public boolean login() throws LoginException {
+
+		SecurityContext sc = SecurityActions.getSecurityContext();
+		SubjectInfo si = sc.getSubjectInfo();
+		Subject subject = si.getAuthenticatedSubject();
+		
+		Set<Principal> principals = subject.getPrincipals();
+		this.principal = principals.iterator().next();
+
+		if (super.login() == true) {
+			return true;
+		}
+
+		// Put the principal name into the sharedState map
+		sharedState.put("javax.security.auth.login.name", principal.getName()); //$NON-NLS-1$
+		sharedState.put("javax.security.auth.login.password", ""); //$NON-NLS-1$ //$NON-NLS-2$
+		super.loginOk = true;
+
+		return true;
+	}
+	
+	protected Principal getIdentity() {
+		return principal;
+	}
+
+	protected Group[] getRoleSets() throws LoginException {
+		return new Group[] {};
+	}
+}

Modified: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Configuration.java
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Configuration.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Configuration.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,13 +40,10 @@
 	public static final String ASYNC_THREAD_GROUP = "async-thread-group";//$NON-NLS-1$
 	public static final String MAX_THREADS = "max-threads";//$NON-NLS-1$
 	public static final String MAX_ACTIVE_PLANS = "max-active-plans";//$NON-NLS-1$
-	public static final String USER_REQUEST_SOURCE_CONCURRENCY = "userRequestSourceConcurrency";//$NON-NLS-1$
+	public static final String USER_REQUEST_SOURCE_CONCURRENCY = "thread-count-for-source-concurrency";//$NON-NLS-1$
 	public static final String TIME_SLICE_IN_MILLI = "time-slice-in-millseconds";//$NON-NLS-1$
 	public static final String MAX_ROWS_FETCH_SIZE = "max-row-fetch-size";//$NON-NLS-1$
 	public static final String LOB_CHUNK_SIZE_IN_KB = "lob-chunk-size-in-kb";//$NON-NLS-1$
-	public static final String USE_DATA_ROLES = "use-dataroles";//$NON-NLS-1$
-	public static final String ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT = "allow-creation-of-temporary-tables";//$NON-NLS-1$
-	public static final String ALLOW_FUNCTION_CALLS_BY_DEFAULT = "allow-function-calls";//$NON-NLS-1$
 	public static final String QUERY_THRESHOLD_IN_SECS = "query-threshold-in-seconds";//$NON-NLS-1$
 	public static final String MAX_SOURCE_ROWS = "max-source-rows-allowed";//$NON-NLS-1$
 	public static final String EXCEPTION_ON_MAX_SOURCE_ROWS = "exception-on-max-source-rows";//$NON-NLS-1$
@@ -57,16 +54,20 @@
 	public static final String MAX_SESSIONS_ALLOWED = "max-sessions-allowed";//$NON-NLS-1$
 	public static final String SESSION_EXPIRATION_TIME_LIMIT = "sessions-expiration-timelimit";//$NON-NLS-1$
 	public static final String ALLOW_ENV_FUNCTION = "allow-env-function";//$NON-NLS-1$
+	public static final String AUTHORIZATION_VALIDATOR_MODULE = "authorization-validator-module"; //$NON-NLS-1$
+	public static final String POLICY_DECIDER_MODULE = "policy-decider-module"; //$NON-NLS-1$
 	
+	
+	// Buffer Manager
 	public static final String USE_DISK = "use-disk";//$NON-NLS-1$
 	public static final String PROCESSOR_BATCH_SIZE = "processor-batch-size";//$NON-NLS-1$
 	public static final String CONNECTOR_BATCH_SIZE = "connector-batch-size";//$NON-NLS-1$
-	public static final String MAX_RESERVE_BATCH_COLUMNS = "maxReserveBatchColumns";//$NON-NLS-1$
-	public static final String MAX_PROCESSING_BATCH_COLUMNS = "maxProcessingBatchesColumns";//$NON-NLS-1$
-	public static final String MAX_FILE_SIZE = "maxFileSize";//$NON-NLS-1$
-	public static final String MAX_BUFFER_SPACE = "maxBufferSpace";//$NON-NLS-1$
-	public static final String MAX_OPEN_FILES = "maxOpenFiles";//$NON-NLS-1$
-		
+	public static final String MAX_PROCESSING_KB = "max-processing-kb";//$NON-NLS-1$
+	public static final String MAX_RESERVED_KB = "max-reserve-kb";//$NON-NLS-1$
+	public static final String MAX_FILE_SIZE = "max-file-size";//$NON-NLS-1$
+	public static final String MAX_BUFFER_SPACE = "max-buffer-space";//$NON-NLS-1$
+	public static final String MAX_OPEN_FILES = "max-open-files";//$NON-NLS-1$
+	
 	//cache-config
 	public static final String MAX_ENTRIES = "maxEntries";//$NON-NLS-1$
 	public static final String MAX_AGE_IN_SECS = "maxAgeInSeconds";//$NON-NLS-1$
@@ -112,6 +113,9 @@
         	else if (ModelType.BOOLEAN.equals(dataType)) {
         		node.get(type, name, DEFAULT).set(Boolean.parseBoolean(defaultValue));
         	}
+        	else if (ModelType.LONG.equals(dataType)) {
+        		node.get(type, name, DEFAULT).set(Long.parseLong(defaultValue));
+        	}        	
         	else {
         		node.get(type, name, DEFAULT).set(defaultValue);
         	}

Modified: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Element.java
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Element.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/Element.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -39,9 +39,8 @@
 	TIME_SLICE_IN_MILLI_ELEMENT(TIME_SLICE_IN_MILLI),
 	MAX_ROWS_FETCH_SIZE_ELEMENT(MAX_ROWS_FETCH_SIZE),
 	LOB_CHUNK_SIZE_IN_KB_ELEMENT(LOB_CHUNK_SIZE_IN_KB),
-	USE_DATA_ROLES_ELEMENT(USE_DATA_ROLES),
-	ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT_ELEMENT(ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT),
-	ALLOW_FUNCTION_CALLS_BY_DEFAULT_ELEMENT(ALLOW_FUNCTION_CALLS_BY_DEFAULT),
+	AUTHORIZATION_VALIDATOR_MODULE_ELEMENT(AUTHORIZATION_VALIDATOR_MODULE),
+	POLICY_DECIDER_MODULE_ELEMENT(POLICY_DECIDER_MODULE),
 	QUERY_THRESHOLD_IN_SECS_ELEMENT(QUERY_THRESHOLD_IN_SECS),
 	MAX_SOURCE_ROWS_ELEMENT(MAX_SOURCE_ROWS),
 	EXCEPTION_ON_MAX_SOURCE_ROWS_ELEMENT(EXCEPTION_ON_MAX_SOURCE_ROWS),
@@ -65,8 +64,8 @@
 	USE_DISK_ELEMENT(USE_DISK),
 	PROCESSOR_BATCH_SIZE_ELEMENT(PROCESSOR_BATCH_SIZE),
 	CONNECTOR_BATCH_SIZE_ELEMENT(CONNECTOR_BATCH_SIZE),
-	MAX_RESERVE_BATCH_COLUMNS_ELEMENT(MAX_RESERVE_BATCH_COLUMNS),
-	MAX_PROCESSING_BATCH_COLUMNS_ELEMENT(MAX_PROCESSING_BATCH_COLUMNS),
+	MAX_PROCESSING_KB_ELEMENT(MAX_PROCESSING_KB),
+	MAX_RESERVED_KB_ELEMENT(MAX_RESERVED_KB),
 	MAX_FILE_SIZE_ELEMENT(MAX_FILE_SIZE),
 	MAX_BUFFER_SPACE_ELEMENT(MAX_BUFFER_SPACE),
 	MAX_OPEN_FILES_ELEMENT(MAX_OPEN_FILES),

Modified: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/JBossLifeCycleListener.java
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/JBossLifeCycleListener.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/JBossLifeCycleListener.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,12 +21,17 @@
  */
 package org.teiid.jboss;
 
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
 import org.jboss.msc.service.ServiceContainer.TerminateListener;
 import org.teiid.deployers.ContainerLifeCycleListener;
 
 class JBossLifeCycleListener implements TerminateListener, ContainerLifeCycleListener{
 
 	private boolean shutdownInProgress = false;
+	private List<ContainerLifeCycleListener.LifeCycleEventListener> listeners = Collections.synchronizedList(new ArrayList<ContainerLifeCycleListener.LifeCycleEventListener>());
 	
 	@Override
 	public boolean isShutdownInProgress() {
@@ -39,4 +44,9 @@
 			this.shutdownInProgress = true;
 		}
 	}
+
+	@Override
+	public void addListener(LifeCycleEventListener listener) {
+		listeners.add(listener);
+	}
 }

Modified: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineAdd.java
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineAdd.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineAdd.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,6 +22,7 @@
 package org.teiid.jboss;
 
 import java.util.List;
+import java.util.ServiceLoader;
 import java.util.concurrent.Executor;
 
 import javax.resource.spi.XATerminator;
@@ -43,14 +44,32 @@
 import org.jboss.as.server.deployment.Phase;
 import org.jboss.as.server.services.path.RelativePathService;
 import org.jboss.dmr.ModelNode;
+import org.jboss.modules.Module;
+import org.jboss.modules.ModuleIdentifier;
+import org.jboss.modules.ModuleLoadException;
 import org.jboss.msc.inject.ConcurrentMapInjector;
-import org.jboss.msc.service.*;
+import org.jboss.msc.service.AbstractServiceListener;
+import org.jboss.msc.service.ServiceBuilder;
+import org.jboss.msc.service.ServiceContainer;
+import org.jboss.msc.service.ServiceController;
+import org.jboss.msc.service.ServiceName;
+import org.jboss.msc.service.ServiceTarget;
 import org.jboss.msc.value.InjectedValue;
+import org.teiid.PolicyDecider;
 import org.teiid.cache.CacheConfiguration;
 import org.teiid.cache.CacheFactory;
 import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.deployers.*;
+import org.teiid.deployers.ObjectSerializer;
+import org.teiid.deployers.SystemVDBDeployer;
+import org.teiid.deployers.VDBDependencyProcessor;
+import org.teiid.deployers.VDBDeployer;
+import org.teiid.deployers.VDBParserDeployer;
+import org.teiid.deployers.VDBRepository;
+import org.teiid.deployers.VDBStructure;
 import org.teiid.dqp.internal.datamgr.TranslatorRepository;
+import org.teiid.dqp.internal.process.AuthorizationValidator;
+import org.teiid.dqp.internal.process.DataRolePolicyDecider;
+import org.teiid.dqp.internal.process.DefaultAuthorizationValidator;
 import org.teiid.jboss.deployers.RuntimeEngineDeployer;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
@@ -101,6 +120,29 @@
     	bufferServiceBuilder.addDependency(TeiidServiceNames.BUFFER_DIR, String.class, bufferService.pathInjector);
     	newControllers.add(bufferServiceBuilder.install());
 
+    	PolicyDecider policyDecider;
+    	if (queryEngineNode.hasDefined(Configuration.POLICY_DECIDER_MODULE)) {
+    		policyDecider = buildService(PolicyDecider.class, queryEngineNode.get(Configuration.POLICY_DECIDER_MODULE).asString());    		
+    	}
+    	else {
+    		DataRolePolicyDecider drpd = new DataRolePolicyDecider();
+    		drpd.setAllowCreateTemporaryTablesByDefault(true);
+    		drpd.setAllowFunctionCallsByDefault(true);
+    		policyDecider = drpd;
+    	}
+    	
+    	AuthorizationValidator authValidator;
+    	if (queryEngineNode.hasDefined(Configuration.AUTHORIZATION_VALIDATOR_MODULE)) {
+    		authValidator = buildService(AuthorizationValidator.class, queryEngineNode.get(Configuration.AUTHORIZATION_VALIDATOR_MODULE).asString());
+    		authValidator.setEnabled(true);
+    	}
+    	else {
+    		DefaultAuthorizationValidator dap = new DefaultAuthorizationValidator();
+    		dap.setPolicyDecider(policyDecider);
+    		dap.setEnabled(true);
+    		authValidator = dap;
+    	}    	
+
     	CacheFactory cacheFactory = getCacheFactory(queryEngineNode.get(Configuration.CACHE_FACORY));
     	CacheConfiguration resultsetCache = buildCacheConfig(queryEngineNode.get(Configuration.RESULTSET_CACHE));
     	CacheConfiguration preparePlanCache = buildCacheConfig(queryEngineNode.get(Configuration.PREPAREDPLAN_CACHE));
@@ -130,6 +172,8 @@
     	engine.setPreparedPlanCacheConfig(preparePlanCache);
     	engine.setSecurityHelper(new JBossSecurityHelper());
     	engine.setTranslatorRepository(translatorRepo);
+    	engine.setAuthorizationValidator(authValidator);
+    	engine.setContainerLifeCycleListener(shutdownListener);
     	
         
         ServiceBuilder<ClientServiceRegistry> serviceBuilder = target.addService(TeiidServiceNames.ENGINE, engine);
@@ -232,15 +276,6 @@
     	if (node.hasDefined(Configuration.LOB_CHUNK_SIZE_IN_KB)) {
     		engine.setLobChunkSizeInKB(node.get(Configuration.LOB_CHUNK_SIZE_IN_KB).asInt());
     	}
-    	if (node.hasDefined(Configuration.USE_DATA_ROLES)) {
-    		engine.setUseDataRoles(node.get(Configuration.USE_DATA_ROLES).asBoolean());
-    	}
-    	if (node.hasDefined(Configuration.ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT)) {
-    		engine.setAllowCreateTemporaryTablesByDefault(node.get(Configuration.ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT).asBoolean());
-    	}
-    	if (node.hasDefined(Configuration.ALLOW_FUNCTION_CALLS_BY_DEFAULT)) {
-    		engine.setAllowFunctionCallsByDefault(node.get(Configuration.ALLOW_FUNCTION_CALLS_BY_DEFAULT).asBoolean());
-    	}
     	if (node.hasDefined(Configuration.QUERY_THRESHOLD_IN_SECS)) {
     		engine.setQueryThresholdInSecs(node.get(Configuration.QUERY_THRESHOLD_IN_SECS).asInt());
     	}
@@ -300,17 +335,17 @@
     	if (node.hasDefined(Configuration.CONNECTOR_BATCH_SIZE)) {
     		bufferManger.setConnectorBatchSize(node.get(Configuration.CONNECTOR_BATCH_SIZE).asInt());
     	}	
-    	if (node.hasDefined(Configuration.MAX_RESERVE_BATCH_COLUMNS)) {
-    		bufferManger.setMaxReserveBatchColumns(node.get(Configuration.MAX_RESERVE_BATCH_COLUMNS).asInt());
+    	if (node.hasDefined(Configuration.MAX_PROCESSING_KB)) {
+    		bufferManger.setMaxProcessingKb(node.get(Configuration.MAX_PROCESSING_KB).asInt());
     	}
-    	if (node.hasDefined(Configuration.MAX_PROCESSING_BATCH_COLUMNS)) {
-    		bufferManger.setMaxProcessingBatchesColumns(node.get(Configuration.MAX_PROCESSING_BATCH_COLUMNS).asInt());
-    	}	
+    	if (node.hasDefined(Configuration.MAX_RESERVED_KB)) {
+    		bufferManger.setMaxReserveKb(node.get(Configuration.MAX_RESERVED_KB).asInt());
+    	}
     	if (node.hasDefined(Configuration.MAX_FILE_SIZE)) {
-    		bufferManger.setMaxFileSize(node.get(Configuration.MAX_FILE_SIZE).asInt());
+    		bufferManger.setMaxFileSize(node.get(Configuration.MAX_FILE_SIZE).asLong());
     	}
     	if (node.hasDefined(Configuration.MAX_BUFFER_SPACE)) {
-    		bufferManger.setMaxBufferSpace(node.get(Configuration.MAX_BUFFER_SPACE).asInt());
+    		bufferManger.setMaxBufferSpace(node.get(Configuration.MAX_BUFFER_SPACE).asLong());
     	}
     	if (node.hasDefined(Configuration.MAX_OPEN_FILES)) {
     		bufferManger.setMaxOpenFiles(node.get(Configuration.MAX_OPEN_FILES).asInt());
@@ -318,6 +353,19 @@
     	return bufferManger;
     }
     
+    private <T> T buildService(Class<T> type, String moduleName) throws OperationFailedException {
+        final ModuleIdentifier moduleId;
+        final Module module;
+        try {
+            moduleId = ModuleIdentifier.create(moduleName);
+            module = Module.getCallerModuleLoader().loadModule(moduleId);
+        } catch (ModuleLoadException e) {
+            throw new OperationFailedException(e, new ModelNode().set(IntegrationPlugin.Util.getString("failed_load_module", moduleName))); //$NON-NLS-1$
+        }
+        ServiceLoader<T> services = module.loadService(type);
+        return services.iterator().next();
+    }
+    
     private CacheFactory getCacheFactory(ModelNode node) {
     	CacheFactory cacheFactory = new DefaultCacheFactory();	
     	/*

Modified: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineDescription.java
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineDescription.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/QueryEngineDescription.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -54,9 +54,6 @@
 		addAttribute(node, Configuration.TIME_SLICE_IN_MILLI, type, bundle.getString(Configuration.TIME_SLICE_IN_MILLI+DESC), ModelType.INT, false, "2000"); //$NON-NLS-1$		
 		addAttribute(node, Configuration.MAX_ROWS_FETCH_SIZE, type, bundle.getString(Configuration.MAX_ROWS_FETCH_SIZE+DESC), ModelType.INT, false, "20480"); //$NON-NLS-1$
 		addAttribute(node, Configuration.LOB_CHUNK_SIZE_IN_KB, type, bundle.getString(Configuration.LOB_CHUNK_SIZE_IN_KB+DESC), ModelType.INT, false, "100"); //$NON-NLS-1$
-		addAttribute(node, Configuration.USE_DATA_ROLES, type, bundle.getString(Configuration.USE_DATA_ROLES+DESC), ModelType.BOOLEAN, false, "true"); //$NON-NLS-1$
-		addAttribute(node, Configuration.ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT, type, bundle.getString(Configuration.ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT+DESC), ModelType.BOOLEAN, false, "true"); //$NON-NLS-1$
-		addAttribute(node, Configuration.ALLOW_FUNCTION_CALLS_BY_DEFAULT, type, bundle.getString(Configuration.ALLOW_FUNCTION_CALLS_BY_DEFAULT+DESC), ModelType.BOOLEAN, false, "true"); //$NON-NLS-1$
 		addAttribute(node, Configuration.QUERY_THRESHOLD_IN_SECS, type, bundle.getString(Configuration.QUERY_THRESHOLD_IN_SECS+DESC), ModelType.INT, false, "600"); //$NON-NLS-1$		
 		addAttribute(node, Configuration.MAX_SOURCE_ROWS, type, bundle.getString(Configuration.MAX_SOURCE_ROWS+DESC), ModelType.INT, false, "-1"); //$NON-NLS-1$
 		addAttribute(node, Configuration.EXCEPTION_ON_MAX_SOURCE_ROWS, type, bundle.getString(Configuration.EXCEPTION_ON_MAX_SOURCE_ROWS+DESC), ModelType.BOOLEAN, false, "true"); //$NON-NLS-1$
@@ -135,10 +132,10 @@
 		addAttribute(node, Configuration.USE_DISK, type, bundle.getString(Configuration.USE_DISK+DESC), ModelType.BOOLEAN, false, "true"); //$NON-NLS-1$
 		addAttribute(node, Configuration.PROCESSOR_BATCH_SIZE, type, bundle.getString(Configuration.PROCESSOR_BATCH_SIZE+DESC), ModelType.INT, false, "512"); //$NON-NLS-1$
 		addAttribute(node, Configuration.CONNECTOR_BATCH_SIZE, type, bundle.getString(Configuration.CONNECTOR_BATCH_SIZE+DESC), ModelType.INT, false, "1024"); //$NON-NLS-1$
-		addAttribute(node, Configuration.MAX_RESERVE_BATCH_COLUMNS, type, bundle.getString(Configuration.MAX_RESERVE_BATCH_COLUMNS+DESC), ModelType.INT, false, "-1"); //$NON-NLS-1$
-		addAttribute(node, Configuration.MAX_PROCESSING_BATCH_COLUMNS, type, bundle.getString(Configuration.MAX_PROCESSING_BATCH_COLUMNS+DESC), ModelType.INT, false, "-1"); //$NON-NLS-1$
-		addAttribute(node, Configuration.MAX_FILE_SIZE, type, bundle.getString(Configuration.MAX_FILE_SIZE+DESC), ModelType.INT, false, "2048"); //$NON-NLS-1$
-		addAttribute(node, Configuration.MAX_BUFFER_SPACE, type, bundle.getString(Configuration.MAX_BUFFER_SPACE+DESC), ModelType.INT, false, "51200"); //$NON-NLS-1$
+		addAttribute(node, Configuration.MAX_PROCESSING_KB, type, bundle.getString(Configuration.MAX_PROCESSING_KB+DESC), ModelType.INT, false, "-1"); //$NON-NLS-1$
+		addAttribute(node, Configuration.MAX_RESERVED_KB, type, bundle.getString(Configuration.MAX_RESERVED_KB+DESC), ModelType.INT, false, "-1"); //$NON-NLS-1$
+		addAttribute(node, Configuration.MAX_FILE_SIZE, type, bundle.getString(Configuration.MAX_FILE_SIZE+DESC), ModelType.LONG, false, "2048"); //$NON-NLS-1$
+		addAttribute(node, Configuration.MAX_BUFFER_SPACE, type, bundle.getString(Configuration.MAX_BUFFER_SPACE+DESC), ModelType.LONG, false, "51200"); //$NON-NLS-1$
 		addAttribute(node, Configuration.MAX_OPEN_FILES, type, bundle.getString(Configuration.MAX_OPEN_FILES+DESC), ModelType.INT, false, "64"); //$NON-NLS-1$
 	}	
 

Modified: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/TeiidSubsystemParser.java
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/TeiidSubsystemParser.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/TeiidSubsystemParser.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -64,9 +64,8 @@
     	writeElement(writer, Element.TIME_SLICE_IN_MILLI_ELEMENT, node);
     	writeElement(writer, Element.MAX_ROWS_FETCH_SIZE_ELEMENT, node);
     	writeElement(writer, Element.LOB_CHUNK_SIZE_IN_KB_ELEMENT, node);
-    	writeElement(writer, Element.USE_DATA_ROLES_ELEMENT, node);
-    	writeElement(writer, Element.ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT_ELEMENT, node);
-    	writeElement(writer, Element.ALLOW_FUNCTION_CALLS_BY_DEFAULT_ELEMENT, node);
+    	writeElement(writer, Element.AUTHORIZATION_VALIDATOR_MODULE_ELEMENT, node);
+    	writeElement(writer, Element.POLICY_DECIDER_MODULE_ELEMENT, node);
     	writeElement(writer, Element.QUERY_THRESHOLD_IN_SECS_ELEMENT, node);
     	writeElement(writer, Element.MAX_SOURCE_ROWS_ELEMENT, node);
     	writeElement(writer, Element.EXCEPTION_ON_MAX_SOURCE_ROWS_ELEMENT, node);
@@ -146,8 +145,8 @@
 		writeElement(writer, Element.USE_DISK_ELEMENT, node);
 		writeElement(writer, Element.PROCESSOR_BATCH_SIZE_ELEMENT, node);
 		writeElement(writer, Element.CONNECTOR_BATCH_SIZE_ELEMENT, node);
-		writeElement(writer, Element.MAX_RESERVE_BATCH_COLUMNS_ELEMENT, node);
-		writeElement(writer, Element.MAX_PROCESSING_BATCH_COLUMNS_ELEMENT, node);
+		writeElement(writer, Element.MAX_PROCESSING_KB_ELEMENT, node);
+		writeElement(writer, Element.MAX_RESERVED_KB_ELEMENT, node);
 		writeElement(writer, Element.MAX_FILE_SIZE_ELEMENT, node);
 		writeElement(writer, Element.MAX_BUFFER_SPACE_ELEMENT, node);
 		writeElement(writer, Element.MAX_OPEN_FILES_ELEMENT, node);
@@ -246,9 +245,6 @@
 					break;
 	
 				// booleans
-				case USE_DATA_ROLES_ELEMENT:
-				case ALLOW_CREATE_TEMPORY_TABLES_BY_DEFAULT_ELEMENT:
-				case ALLOW_FUNCTION_CALLS_BY_DEFAULT_ELEMENT:
 				case EXCEPTION_ON_MAX_SOURCE_ROWS_ELEMENT:
 				case DETECTING_CHANGE_EVENTS_ELEMENT:
 				case ALLOW_ENV_FUNCTION_ELEMENT:
@@ -259,6 +255,8 @@
 				case EVENT_DISTRIBUTOR_NAME_ELEMENT:
 				case JDBC_SECURITY_DOMAIN_ELEMENT:
 				case ASYNC_THREAD_GROUP_ELEMENT:
+				case AUTHORIZATION_VALIDATOR_MODULE_ELEMENT:
+				case POLICY_DECIDER_MODULE_ELEMENT:
 					node.get(reader.getLocalName()).set(reader.getElementText());
 					break;
 	
@@ -299,13 +297,15 @@
 				break;
 			case PROCESSOR_BATCH_SIZE_ELEMENT:
 			case CONNECTOR_BATCH_SIZE_ELEMENT:
-			case MAX_RESERVE_BATCH_COLUMNS_ELEMENT:
-			case MAX_PROCESSING_BATCH_COLUMNS_ELEMENT:
-			case MAX_FILE_SIZE_ELEMENT:
-			case MAX_BUFFER_SPACE_ELEMENT:
+			case MAX_PROCESSING_KB_ELEMENT:
+			case MAX_RESERVED_KB_ELEMENT:
 			case MAX_OPEN_FILES_ELEMENT:
 				node.get(reader.getLocalName()).set(Integer.parseInt(reader.getElementText()));
 				break;
+			case MAX_FILE_SIZE_ELEMENT:				
+			case MAX_BUFFER_SPACE_ELEMENT:
+				node.get(reader.getLocalName()).set(Long.parseLong(reader.getElementText()));
+				break;
 			default:
 				throw ParseUtils.unexpectedElement(reader);
 			}

Modified: branches/as7/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java
===================================================================
--- branches/as7/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/java/org/teiid/jboss/deployers/RuntimeEngineDeployer.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,6 +22,7 @@
 package org.teiid.jboss.deployers;
 
 import java.io.Serializable;
+import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
@@ -29,8 +30,20 @@
 import java.sql.Clob;
 import java.sql.SQLException;
 import java.sql.SQLXML;
-import java.util.*;
-import java.util.concurrent.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
 
 import javax.naming.InitialContext;
 import javax.naming.NamingException;
@@ -47,12 +60,18 @@
 import org.jboss.msc.service.StopContext;
 import org.jboss.msc.value.InjectedValue;
 import org.jboss.netty.util.internal.ConcurrentHashMap;
-import org.jboss.util.naming.Util;
+import org.teiid.adminapi.Admin.Cache;
 import org.teiid.adminapi.AdminComponentException;
 import org.teiid.adminapi.AdminException;
 import org.teiid.adminapi.AdminProcessingException;
-import org.teiid.adminapi.Admin.Cache;
-import org.teiid.adminapi.impl.*;
+import org.teiid.adminapi.impl.CacheStatisticsMetadata;
+import org.teiid.adminapi.impl.DQPManagement;
+import org.teiid.adminapi.impl.RequestMetadata;
+import org.teiid.adminapi.impl.SessionMetadata;
+import org.teiid.adminapi.impl.TransactionMetadata;
+import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.adminapi.impl.VDBTranslatorMetaData;
+import org.teiid.adminapi.impl.WorkerPoolStatisticsMetadata;
 import org.teiid.cache.CacheFactory;
 import org.teiid.client.DQP;
 import org.teiid.client.RequestMessage;
@@ -63,14 +82,18 @@
 import org.teiid.client.util.ResultsFuture;
 import org.teiid.core.ComponentNotFoundException;
 import org.teiid.core.TeiidComponentException;
-import org.teiid.core.TeiidException;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.util.ApplicationInfo;
 import org.teiid.core.util.LRUCache;
+import org.teiid.deployers.ContainerLifeCycleListener;
 import org.teiid.deployers.VDBLifeCycleListener;
 import org.teiid.deployers.VDBRepository;
 import org.teiid.dqp.internal.datamgr.TranslatorRepository;
-import org.teiid.dqp.internal.process.*;
+import org.teiid.dqp.internal.process.DQPConfiguration;
+import org.teiid.dqp.internal.process.DQPCore;
+import org.teiid.dqp.internal.process.DQPWorkContext;
+import org.teiid.dqp.internal.process.DataTierManagerImpl;
+import org.teiid.dqp.internal.process.TransactionServerImpl;
 import org.teiid.dqp.service.BufferService;
 import org.teiid.dqp.service.SessionService;
 import org.teiid.dqp.service.SessionServiceException;
@@ -82,18 +105,26 @@
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.logging.MessageLevel;
-import org.teiid.metadata.*;
+import org.teiid.metadata.AbstractMetadataRecord;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.ColumnStats;
+import org.teiid.metadata.Procedure;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
 import org.teiid.metadata.Table.TriggerEvent;
+import org.teiid.metadata.TableStats;
 import org.teiid.net.TeiidURL;
-import org.teiid.query.QueryPlugin;
 import org.teiid.query.metadata.TransformationMetadata;
-import org.teiid.query.optimizer.relational.RelationalPlanner;
 import org.teiid.query.processor.DdlPlan;
-import org.teiid.query.tempdata.TempTableStore;
 import org.teiid.security.SecurityHelper;
 import org.teiid.services.BufferServiceImpl;
 import org.teiid.services.SessionServiceImpl;
-import org.teiid.transport.*;
+import org.teiid.transport.ClientServiceRegistry;
+import org.teiid.transport.ClientServiceRegistryImpl;
+import org.teiid.transport.LogonImpl;
+import org.teiid.transport.ODBCSocketListener;
+import org.teiid.transport.SocketConfiguration;
+import org.teiid.transport.SocketListener;
 import org.teiid.vdb.runtime.VDBKey;
 
 
@@ -113,11 +144,14 @@
 	private transient VDBRepository vdbRepository;
 	private transient TranslatorRepository translatorRepository;
 
-	private String eventDistributorName;
-	private transient EventDistributor eventDistributor;
     private long sessionMaxLimit = SessionService.DEFAULT_MAX_SESSIONS;
 	private long sessionExpirationTimeLimit = SessionService.DEFAULT_SESSION_EXPIRATION;
 
+	private String eventDistributorName;
+	private transient EventDistributor eventDistributor;	
+	private transient EventDistributor eventDistributorProxy;
+	private transient ContainerLifeCycleListener lifecycleListener;
+
 	// TODO: remove public?
 	public final InjectedValue<WorkManager> workManagerInjector = new InjectedValue<WorkManager>();
 	public final InjectedValue<XATerminator> xaTerminatorInjector = new InjectedValue<XATerminator>();
@@ -128,8 +162,8 @@
 	public final InjectedValue<SocketBinding> odbcSocketBindingInjector = new InjectedValue<SocketBinding>();
 	public final ConcurrentMap<String, SecurityDomainContext> securityDomains = new ConcurrentHashMap<String, SecurityDomainContext>();
 	private LinkedList<String> securityDomainNames = new LinkedList<String>();
+
 	
-	
     public RuntimeEngineDeployer() {
 		// TODO: this does not belong here
 		LogManager.setLogListener(new Log4jListener());
@@ -185,8 +219,21 @@
 				LogManager.logDetail(LogConstants.CTX_RUNTIME, ne, IntegrationPlugin.Util.getString("jndi_failed", new Date(System.currentTimeMillis()).toString())); //$NON-NLS-1$
 			}
 		}
+		this.dqpCore.setMetadataRepository(this.vdbRepository.getMetadataRepository());
+		this.dqpCore.setEventDistributor(this.eventDistributor);
 		this.dqpCore.start(this);
-		this.dqpCore.getDataTierManager().setEventDistributor(this.eventDistributor);		
+		this.eventDistributorProxy = (EventDistributor)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[] {EventDistributor.class}, new InvocationHandler() {
+			
+			@Override
+			public Object invoke(Object proxy, Method method, Object[] args)
+					throws Throwable {
+				method.invoke(RuntimeEngineDeployer.this, args);
+				if (eventDistributor != null) {
+					method.invoke(eventDistributor, args);
+				}
+				return null;
+			}
+		});
     	// create the necessary services
     	createClientServices();
     	
@@ -222,7 +269,9 @@
     	
     	if (this.odbcSocketConfiguration != null) {
     		this.vdbRepository.odbcEnabled();
-	    	this.odbcSocket = new ODBCSocketListener(this.odbcSocketConfiguration, this.dqpCore.getBufferManager(), offset, getMaxODBCLobSizeAllowed());
+    		ODBCSocketListener odbc = new ODBCSocketListener(this.odbcSocketConfiguration, this.dqpCore.getBufferManager(), offset, getMaxODBCLobSizeAllowed(), this.logon);
+    		odbc.setAuthenticationType(sessionService.getAuthType());
+	    	this.odbcSocket = odbc;
 	    	LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("odbc_enabled","Teiid ODBC - SSL=", (this.odbcSocketConfiguration.getSSLConfiguration().isSslEnabled()?"ON":"OFF")+" Host = "+this.odbcSocketConfiguration.getHostAddress().getHostName()+" Port = "+(this.odbcSocketConfiguration.getPortNumber()+offset))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
     	} else {
     		LogManager.logInfo(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("odbc_not_enabled")); //$NON-NLS-1$
@@ -261,7 +310,9 @@
 				dqpCore.clearCache(Cache.PREPARED_PLAN_CACHE.toString(), name, version);
 				dqpCore.clearCache(Cache.QUERY_SERVICE_RESULT_SET_CACHE.toString(), name, version);
 			}			
-		});    	
+		});
+		
+		synchronizeMaterializeViews();
 	}	
 	
 	@Override
@@ -462,21 +513,11 @@
 	
 	@Override
 	public List<List> executeQuery(final String vdbName, final int version, final String command, final long timoutInMilli) throws AdminException {
-		Properties properties = new Properties();
-		properties.setProperty(TeiidURL.JDBC.VDB_NAME, vdbName);
-		properties.setProperty(TeiidURL.JDBC.VDB_VERSION, String.valueOf(version));
 		
 		String user = "JOPR ADMIN"; //$NON-NLS-1$
 		LogManager.logDetail(LogConstants.CTX_RUNTIME, IntegrationPlugin.Util.getString("admin_executing", user, command)); //$NON-NLS-1$
 		
-		SessionMetadata session = null;
-		try {
-			session = this.sessionService.createSession(user, null, "JOPR", properties, false); //$NON-NLS-1$
-		} catch (SessionServiceException e1) {
-			throw new AdminProcessingException(e1);
-		} catch (LoginException e1) {
-			throw new AdminProcessingException(e1);
-		}
+		SessionMetadata session = createTemporarySession(vdbName, version, user);
 
 		final long requestID =  0L;
 		
@@ -494,8 +535,12 @@
 					request.setExecutionId(0L);
 					request.setRowLimit(getMaxRowsFetchSize()); // this would limit the number of rows that are returned.
 					Future<ResultsMessage> message = dqpCore.executeRequest(requestID, request);
-					ResultsMessage rm = message.get(timoutInMilli, TimeUnit.MILLISECONDS);
-					
+					ResultsMessage rm = null;
+					if (timoutInMilli < 0) {
+						rm = message.get();
+					} else {
+						rm = message.get(timoutInMilli, TimeUnit.MILLISECONDS);
+					}
 			        if (rm.getException() != null) {
 			            throw new AdminProcessingException(rm.getException());
 			        }
@@ -530,6 +575,23 @@
 			} catch (InvalidSessionException e) { //ignore
 			}			
 		}
+	}
+
+	private SessionMetadata createTemporarySession(final String vdbName, final int version, final String user)
+			throws AdminProcessingException {
+		Properties properties = new Properties();
+		properties.setProperty(TeiidURL.JDBC.VDB_NAME, vdbName);
+		properties.setProperty(TeiidURL.JDBC.VDB_VERSION, String.valueOf(version));
+		
+		SessionMetadata session = null;
+		try {
+			session = this.sessionService.createSession(user, null, "JOPR", properties, false); //$NON-NLS-1$
+		} catch (SessionServiceException e1) {
+			throw new AdminProcessingException(e1);
+		} catch (LoginException e1) {
+			throw new AdminProcessingException(e1);
+		}
+		return session;
 	}	
 	
 	/**
@@ -583,22 +645,15 @@
 	@Override
 	public void updateMatViewRow(String vdbName, int vdbVersion, String schema,
 			String viewName, List<?> tuple, boolean delete) {
-		VDBMetaData vdb = this.vdbRepository.getVDB(vdbName, vdbVersion);
-		if (vdb == null) {
-			return;
-		}
-		TempTableStore globalStore = vdb.getAttachment(TempTableStore.class);
-		if (globalStore == null) {
-			return;
-		}
-		try {
-			this.dqpCore.getDataTierManager().updateMatViewRow(globalStore, RelationalPlanner.MAT_PREFIX + (schema + '.' + viewName).toUpperCase(), tuple, delete);
-		} catch (TeiidException e) {
-			LogManager.logError(LogConstants.CTX_DQP, e, QueryPlugin.Util.getString("DQPCore.unable_to_process_event")); //$NON-NLS-1$
-		}
+		this.dqpCore.updateMatViewRow(getcontextProvider(), vdbName, vdbVersion, schema, viewName, tuple, delete);
 	}
 	
 	@Override
+	public void refreshMatView(final String vdbName, final int vdbVersion, final String viewName) {
+		this.dqpCore.refreshMatView(getcontextProvider(), vdbName, vdbVersion, viewName);
+	}
+	
+	@Override
 	public void dataModification(String vdbName, int vdbVersion, String schema,
 			String... tableNames) {
 		updateModified(true, vdbName, vdbVersion, schema, tableNames);
@@ -612,7 +667,7 @@
 		}
 		long ts = System.currentTimeMillis();
 		for (String name:objectNames) {
-			Table table = s.getTables().get(name);
+			Table table = s.getTables().get(name.toUpperCase());
 			if (table == null) {
 				continue;
 			}
@@ -727,15 +782,19 @@
 	
 	@Override
 	public EventDistributor getEventDistributor() {
-		if (this.eventDistributor != null) { 
-			return eventDistributor;
-		}
-		return this;
+		return this.eventDistributorProxy;
 	}
 	
-	@Override
-	public MetadataRepository getMetadataRepository() {
-		return this.vdbRepository.getMetadataRepository();
+	private void synchronizeMaterializeViews() {
+		this.lifecycleListener.addListener(new ContainerLifeCycleListener.LifeCycleEventListener() {
+			@Override
+			public void onStartupFinish() {
+				dqpCore.synchronizeInternalMaterializedViews(getcontextProvider());
+			}
+			@Override
+			public void onShutdownStart() {
+			}
+		});
 	}
 	
 	public String getRuntimeVersion() {
@@ -773,4 +832,27 @@
 	public void setTranslatorRepository(TranslatorRepository translatorRepo) {
 		this.translatorRepository = translatorRepo;
 	}
+
+	private DQPCore.ContextProvider getcontextProvider() {
+		return new DQPCore.ContextProvider() {
+			@Override
+			public DQPWorkContext getContext(final String vdbName, final int vdbVersion) {
+				return new DQPWorkContext() {
+					public VDBMetaData getVDB() {
+						return vdbRepository.getVDB(vdbName, vdbVersion);
+					}
+				    public String getVdbName() {
+				        return vdbName;
+				    }
+				    public int getVdbVersion() {
+				        return vdbVersion;
+				    }					
+				};
+			}
+		};
+	}
+	
+	public void setContainerLifeCycleListener(ContainerLifeCycleListener listener) {
+		this.lifecycleListener = listener;
+	}	
 }

Modified: branches/as7/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties
===================================================================
--- branches/as7/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/resources/org/teiid/jboss/i18n.properties	2011-08-18 16:17:24 UTC (rev 3394)
@@ -66,25 +66,23 @@
 	
 #Query-ENGINE
 jndi-name.describe=JNDI name of the Teiid Query Engine
-thread-group-async.describe=Thread Pool to be used with Asynchronous operations in Teiid
-maxThreads.describe=Process pool maximum thread count. (default 64)
-maxActivePlans.describe=Max active plans (default 20).  Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.
-userRequestSourceConcurrency.describe=Max source query concurrency per user request (default 0).  \
+async-thread-group.describe=Thread Pool to be used with Asynchronous operations in Teiid
+max-threads.describe=Process pool maximum thread count. (default 64)
+max-active-plans.describe=Max active plans (default 20).  Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.
+thread-count-for-source-concurrency.describe=Max source query concurrency per user request (default 0).  \
 			 0 indicates use the default calculated value based on max active plans and max threads - approximately 2*(max threads)/(max active plans). \  
 			 1 forces serial execution in the processing thread, just as is done for a transactional request.  \
 			 Any number greater than 1 limits the maximum number of concurrently executing source requests accordingly.
-timeSliceInMilli.describe=Query processor time slice, in milliseconds. (default 2000)
-maxRowsFetchSize.describe=Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)
-lobChunkSizeInKB.describe=The max lob chunk size in KB transferred each time when processing blobs, clobs (100KB default)
-useDataRoles.describe=Turn on role checking based upon the data roles defined in VDBs. (default true)
-allowCreateTemporaryTablesByDefault.describe=Sets whether temporary table usage is allowed by default with data roles enabled. If false, the user must have a role that grants creates temporary table rights to use temporary tables. (default true)
-allowFunctionCallsByDefault.describe=Sets whether functions may be called by default with data roles enabled. If false, a specific permission must exist to call the function. (default true)
-queryThresholdInSecs.describe=Long running query threshold, after which a alert can be generated by tooling if configured
-maxSourceRows.describe=Maximum rows allowed from a source query. -1 indicates no limit. (default -1)
-exceptionOnMaxSourceRows.describe=Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed. (default true)
-maxODBCLobSizeAllowed.describe=Maximum size of lob allowed through ODBC connection in bytes (default 5MB)
-eventDistributorName.describe=The JNDI name of the Teiid Event Distributor
-detectingChangeEvents.describe=Set to true for the engine to detect local change events. Should be disabled if using external change data capture tools. (default true)
+time-slice-in-millseconds.describe=Query processor time slice, in milliseconds. (default 2000)
+max-row-fetch-size.describe=Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)
+lob-chunk-size-in-kb.describe=The max lob chunk size in KB transferred each time when processing blobs, clobs (100KB default)
+use-dataroles.describe=Turn on role checking based upon the data roles defined in VDBs. (default true)
+query-threshold-in-seconds.describe=Long running query threshold, after which a alert can be generated by tooling if configured
+max-source-rows-allowed.describe=Maximum rows allowed from a source query. -1 indicates no limit. (default -1)
+exception-on-max-source-rows.describe=Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed. (default true)
+max-odbc-lob-size-allowed.describe=Maximum size of lob allowed through ODBC connection in bytes (default 5MB)
+event-distributor-name.describe=The JNDI name of the Teiid Event Distributor
+detect-change-events.describe=Set to true for the engine to detect local change events. Should be disabled if using external change data capture tools. (default true)
 security-domain.describe=Comma separated list of domains to be used to login into Teiid
 admin-security-domain.describe=security domain to be used with Admin API (please do not change this, as this should be same as profile service)
 max-sessions-allowed.describe=Maximum number of sessions allowed by the system (default 5000)
@@ -92,15 +90,14 @@
 allow-env-function.describe=Allow the execution of ENV function. (default false)
 	
 #buffer-manager
-useDisk.describe=Use disk for buffer management
-diskDirectory.describe=Directory location for the buffer files
-processorBatchSize.describe=The max row count of a batch sent internally within the query processor. Should be <= the connectorBatchSize. (default 512)
-connectorBatchSize.describe=The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024)
-maxReserveBatchColumns.describe=The number of batch columns to allow in buffer memory. -1 means to automatically calculate a value (default -1). See the admin guide for more.
-maxProcessingBatchesColumns.describe=The number of batch columns guaranteed to a processing operation. -1 means to automatically calculate a value (default -1). See the admin guide for more.
-maxFileSize.describe= Max File size in MB (default 2GB)
-maxBufferSpace.describe=Max storage space, in MB, to be used for buffer files (default 50G)
-maxOpenFiles.describe=Max open buffer files (default 64)
+use-disk.describe=Use disk for buffer management
+processor-batch-size.describe=The max row count of a batch sent internally within the query processor. Should be <= the connectorBatchSize. (default 512)
+connector-batch-size.describe=The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024)
+max-file-size.describe= Max File size in MB (default 2GB)
+max-buffer-space.describe=Max storage space, in MB, to be used for buffer files (default 50G)
+max-open-files.describe=Max open buffer files (default 64)
+max-processing-kb.describe=The approximate amount of buffer memory in kilobytes allowable for a single processing operation (sort, grouping, etc.) regardless of existing memory commitments. -1 means to automatically calculate a value (default -1)
+max-reserve-kb.describe=The approximate amount of memory in kilobytes allowed to be held by the buffer manager. -1 means to automatically calculate a value (default -1)
 	
 #cache-config
 enabled.describe=enabled
@@ -129,7 +126,7 @@
              login = only the login traffic will be encrypted at a message level \
                      using 128 bit AES with an ephemerial DH key exchange. \
                      No other config values are needed in this mode; \
-             enabled = traffic will be secured using this configuration.
+             enabled = traffic will be secured using this configuration,if the client supports SSL
 keystoreFilename.describe=Keystore File Name
 keystorePassword.describe=Keystore password
 keystoreType.describe=Keystore type

Modified: branches/as7/jboss-integration/src/main/resources/schema/jboss-teiid.xsd
===================================================================
--- branches/as7/jboss-integration/src/main/resources/schema/jboss-teiid.xsd	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/main/resources/schema/jboss-teiid.xsd	2011-08-18 16:17:24 UTC (rev 3394)
@@ -42,42 +42,42 @@
 
     <xs:complexType name="buffer-service-type">
         <xs:sequence>
-            <xs:element name="useDisk" type="xs:string" minOccurs="0" maxOccurs="1">
+            <xs:element name="use-disk" type="xs:string" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
                     <xs:documentation>Use disk for buffer management</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="processorBatchSize" type="xs:int" minOccurs="0" maxOccurs="1">
+            <xs:element name="processor-batch-size" type="xs:int" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
                     <xs:documentation>The max row count of a batch sent internally within the query processor. Should be &lt;= the connectorBatchSize. (default 512)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="connectorBatchSize" type="xs:int" minOccurs="0" maxOccurs="1">
+            <xs:element name="connector-batch-size" type="xs:int" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
                     <xs:documentation> The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024) </xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxReserveBatchColumns" type="xs:int" minOccurs="0" maxOccurs="1">
+            <xs:element name="max-processing-kb" type="xs:int" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
-                    <xs:documentation> The number of batch columns to allow in buffer memory. -1 means to automatically calculate a value (default -1). See the admin guide for more. </xs:documentation>
+                    <xs:documentation>The approximate amount of memory in kilobytes allowed to be held by the buffer manager. -1 means to automatically calculate a value (default -1). See the admin guide for more.</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxProcessingBatchesColumns" type="xs:int" minOccurs="0" maxOccurs="1">
+            <xs:element name="max-reserve-kb" type="xs:int" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
-                    <xs:documentation>The number of batch columns guaranteed to a processing operation. -1 means to automatically calculate a value (default -1).See the admin guide for more.</xs:documentation>
+                    <xs:documentation>The approximate amount of buffer memory in kilobytes allowable for a single processing operation (sort, grouping, etc.) regardless of existing memory commitments. -1 means to automatically calculate a value (default -1).  See the admin guide for more</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxFileSize" type="xs:int" minOccurs="0" maxOccurs="1">
+            <xs:element name="max-file-size" type="xs:int" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
                     <xs:documentation>Max File size in MB (default 2GB)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxBufferSpace" type="xs:int" minOccurs="0" maxOccurs="1">
+            <xs:element name="max-buffer-space" type="xs:int" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
                     <xs:documentation>Max storage space, in MB, to be used for buffer files (default 50G) </xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxOpenFiles" type="xs:int" minOccurs="0" maxOccurs="1">
+            <xs:element name="max-open-files" type="xs:int" minOccurs="0" maxOccurs="1">
                 <xs:annotation>
                     <xs:documentation>Max open buffer files (default 64)</xs:documentation>
                 </xs:annotation>
@@ -136,22 +136,22 @@
     </xs:complexType>
     <xs:complexType name="runtime-engine-type">
         <xs:sequence>
-            <xs:element name="thread-group-async" type="xs:string" minOccurs="0" maxOccurs="1" default="teiid-async">
+            <xs:element name="async-thread-group" type="xs:string" minOccurs="0" maxOccurs="1" default="teiid-async">
                 <xs:annotation>
                     <xs:documentation>Thread group to use for Async Processing</xs:documentation>
                 </xs:annotation>
             </xs:element>        
-            <xs:element name="maxThreads" type="xs:int" minOccurs="0" maxOccurs="1" default="64">
+            <xs:element name="max-threads" type="xs:int" minOccurs="0" maxOccurs="1" default="64">
                 <xs:annotation>
                     <xs:documentation>Process pool maximum thread count. (default 64)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxActivePlans" type="xs:int" minOccurs="0" maxOccurs="1" default="20">
+            <xs:element name="max-active-plans" type="xs:int" minOccurs="0" maxOccurs="1" default="20">
                 <xs:annotation>
                     <xs:documentation>Max active plans (default 20). Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="userRequestSourceConcurrency" type="xs:int" minOccurs="0" maxOccurs="1" default="0">
+            <xs:element name="thread-count-for-source-concurrency" type="xs:int" minOccurs="0" maxOccurs="1" default="0">
                 <xs:annotation>
                     <xs:documentation> Max source query concurrency per user request (default 0).
                         0 indicates use the default calculated value based on max active plans and max threads - approximately 2*(max threads)/(max active plans).
@@ -159,62 +159,47 @@
                         Any number greater than 1 limits the maximum number of concurrently executing source requests accordingly.</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="timeSliceInMilli" type="xs:int" minOccurs="0" maxOccurs="1" default="2000">
+            <xs:element name="time-slice-in-millseconds" type="xs:int" minOccurs="0" maxOccurs="1" default="2000">
                 <xs:annotation>
                     <xs:documentation>Query processor time slice, in milliseconds. (default 2000)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxRowsFetchSize" type="xs:int" minOccurs="0" maxOccurs="1" default="20480">
+            <xs:element name="max-row-fetch-size" type="xs:int" minOccurs="0" maxOccurs="1" default="20480">
                 <xs:annotation>
                     <xs:documentation>Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="lobChunkSizeInKB" type="xs:int" minOccurs="0" maxOccurs="1" default="100">
+            <xs:element name="lob-chunk-size-in-kb" type="xs:int" minOccurs="0" maxOccurs="1" default="100">
                 <xs:annotation>
                     <xs:documentation>The max lob chunk size in KB transferred each time when processing blobs, clobs (100KB default)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="useDataRoles" type="xs:boolean" minOccurs="0" maxOccurs="1" default="true">
+            <xs:element name="query-threshold-in-seconds" type="xs:int" minOccurs="0" maxOccurs="1" default="600">
                 <xs:annotation>
-                    <xs:documentation>Turn on role checking based upon the data roles defined in VDBs. (default true)</xs:documentation>
-                </xs:annotation>
-            </xs:element>
-            <xs:element name="allowCreateTemporaryTablesByDefault" type="xs:boolean" minOccurs="0" maxOccurs="1" default="true">
-                <xs:annotation>
-                    <xs:documentation>Sets whether temporary table usage is allowed by default with data roles enabled. If false, the user must have a role that grants creates temporary table rights to use temporary tables. (default true)</xs:documentation>
-                </xs:annotation>
-            </xs:element>
-            <xs:element name="allowFunctionCallsByDefault" type="xs:boolean" minOccurs="0" maxOccurs="1" default="true">
-                <xs:annotation>
-                    <xs:documentation>Sets whether functions may be called by default with data roles enabled. If false, a specific permission must exist to call the function. (default true)</xs:documentation>
-                </xs:annotation>
-            </xs:element>
-            <xs:element name="queryThresholdInSecs" type="xs:int" minOccurs="0" maxOccurs="1" default="600">
-                <xs:annotation>
                     <xs:documentation>Long running query threshold, after which a alert can be generated by tooling if configured (600 secs)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxSourceRows" type="xs:int" minOccurs="0" maxOccurs="1" default="-1">
+            <xs:element name="max-source-rows-allowed" type="xs:int" minOccurs="0" maxOccurs="1" default="-1">
                 <xs:annotation>
                     <xs:documentation>Maximum rows allowed from a source query. -1 indicates no limit. (default -1)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="exceptionOnMaxSourceRows" type="xs:boolean" minOccurs="0" maxOccurs="1" default="true">
+            <xs:element name="exception-on-max-source-rows" type="xs:boolean" minOccurs="0" maxOccurs="1" default="true">
                 <xs:annotation>
                     <xs:documentation>Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed. (default true)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="maxODBCLobSizeAllowed" type="xs:int" minOccurs="0" maxOccurs="1" default="5242880">
+            <xs:element name="max-odbc-lob-size-allowed" type="xs:int" minOccurs="0" maxOccurs="1" default="5242880">
                 <xs:annotation>
                     <xs:documentation>Maximum size of lob allowed through ODBC connection in bytes (default 5MB)</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="eventDistributorName" type="xs:string" minOccurs="1" maxOccurs="1">
+            <xs:element name="event-distributor-name" type="xs:string" minOccurs="1" maxOccurs="1">
                 <xs:annotation>
                     <xs:documentation>The JNDI name of the Teiid Event Distributor</xs:documentation>
                 </xs:annotation>
             </xs:element>
-            <xs:element name="detectingChangeEvents" type="xs:boolean" minOccurs="0" maxOccurs="1" default="true">
+            <xs:element name="detect-change-events" type="xs:boolean" minOccurs="0" maxOccurs="1" default="true">
                 <xs:annotation>
                     <xs:documentation>Set to true for the engine to detect local change events. Should be disabled if using external change data capture tools. (default true)</xs:documentation>
                 </xs:annotation>
@@ -245,7 +230,20 @@
                     <xs:documentation>Buffer manager information</xs:documentation>
                 </xs:annotation>
             </xs:element>
+            
+            <xs:element name="authorization-validator-module" type="xs:string" minOccurs="0" maxOccurs="1">
+                <xs:annotation>
+                    <xs:documentation>An authorization validator that by default uses data role information stored in VDBs. Provide module name.</xs:documentation>
+                </xs:annotation>
+            </xs:element>
+            
+            <xs:element name="policy-decider-module" type="xs:string" minOccurs="0" maxOccurs="1">
+                <xs:annotation>
+                    <xs:documentation>A policy decider that uses data role information stored in VDBs, Provide module name.</xs:documentation>
+                </xs:annotation>
+            </xs:element>
 
+
             <xs:element name="distributed-cache-factory" type="cache-factory-type" maxOccurs="1" minOccurs="1">
                 <xs:annotation>
                     <xs:documentation>Cache Factory</xs:documentation>
@@ -279,6 +277,19 @@
         </xs:sequence>
     </xs:complexType>
 
+    <xs:complexType name="authorization-validator-type">
+        <xs:sequence>
+            <xs:element name="maxSocketThreads" type="xs:int" minOccurs="0" maxOccurs="1">
+                <xs:annotation>
+                    <xs:documentation>Max number of threads dedicated to initial request processing.
+                        Zero indicates the system default of max available processors. (default 0)
+                        Setting this value above the max available processors is not recommended.</xs:documentation>
+                </xs:annotation>
+            </xs:element>
+        </xs:sequence>
+    </xs:complexType>
+
+
     <xs:complexType name="socket-config">
         <xs:sequence>
             <xs:element name="maxSocketThreads" type="xs:int" minOccurs="0" maxOccurs="1" default="0">

Modified: branches/as7/jboss-integration/src/test/java/org/teiid/jboss/TestTeiidConfiguration.java
===================================================================
--- branches/as7/jboss-integration/src/test/java/org/teiid/jboss/TestTeiidConfiguration.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/test/java/org/teiid/jboss/TestTeiidConfiguration.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -126,8 +126,8 @@
 
         ModelNode subsystem = model.require("profile").require("test").require("subsystem").require("teiid");
         ModelNode bufferService = subsystem.require("buffer-service");
-        assertEquals(9, bufferService.keys().size());
-        assertEquals("true", bufferService.require("useDisk").asString());
+        assertEquals(8, bufferService.keys().size());
+        assertEquals("true", bufferService.require("use-disk").asString());
     }	
     
     @Test

Modified: branches/as7/jboss-integration/src/test/resources/teiid-model-config.txt
===================================================================
--- branches/as7/jboss-integration/src/test/resources/teiid-model-config.txt	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/test/resources/teiid-model-config.txt	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,111 +1,90 @@
 {
     "attributes" => {
-        "thread-group-async" => {
+        "async-thread-group" => {
             "type" => STRING,
             "description" => "Thread Pool to be used with Asynchronous operations in Teiid",
             "required" => false,
             "max-occurs" => 1,
             "default" => "teiid-async"
         },
-        "maxThreads" => {
+        "max-threads" => {
             "type" => INT,
             "description" => "Process pool maximum thread count. (default 64)",
             "required" => false,
             "max-occurs" => 1,
             "default" => 64
         },
-        "maxActivePlans" => {
+        "max-active-plans" => {
             "type" => INT,
             "description" => "Max active plans (default 20).  Increase this value on highly concurrent systems - but ensure that the underlying pools can handle the increased load without timeouts.",
             "required" => false,
             "max-occurs" => 1,
             "default" => 20
         },
-        "userRequestSourceConcurrency" => {
+        "thread-count-for-source-concurrency" => {
             "type" => INT,
             "description" => "Max source query concurrency per user request (default 0).  0 indicates use the default calculated value based on max active plans and max threads - approximately 2*(max threads)/(max active plans).   ",
             "required" => false,
             "max-occurs" => 1,
             "default" => 0
         },
-        "timeSliceInMilli" => {
+        "time-slice-in-millseconds" => {
             "type" => INT,
             "description" => "Query processor time slice, in milliseconds. (default 2000)",
             "required" => false,
             "max-occurs" => 1,
             "default" => 2000
         },
-        "maxRowsFetchSize" => {
+        "max-row-fetch-size" => {
             "type" => INT,
             "description" => "Maximum allowed fetch size, set via JDBC. User requested value ignored above this value. (default 20480)",
             "required" => false,
             "max-occurs" => 1,
             "default" => 20480
         },
-        "lobChunkSizeInKB" => {
+        "lob-chunk-size-in-kb" => {
             "type" => INT,
             "description" => "The max lob chunk size in KB transferred each time when processing blobs, clobs (100KB default)",
             "required" => false,
             "max-occurs" => 1,
             "default" => 100
         },
-        "useDataRoles" => {
-            "type" => BOOLEAN,
-            "description" => "Turn on role checking based upon the data roles defined in VDBs. (default true)",
-            "required" => false,
-            "max-occurs" => 1,
-            "default" => true
-        },
-        "allowCreateTemporaryTablesByDefault" => {
-            "type" => BOOLEAN,
-            "description" => "Sets whether temporary table usage is allowed by default with data roles enabled. If false, the user must have a role that grants creates temporary table rights to use temporary tables. (default true)",
-            "required" => false,
-            "max-occurs" => 1,
-            "default" => true
-        },
-        "allowFunctionCallsByDefault" => {
-            "type" => BOOLEAN,
-            "description" => "Sets whether functions may be called by default with data roles enabled. If false, a specific permission must exist to call the function. (default true)",
-            "required" => false,
-            "max-occurs" => 1,
-            "default" => true
-        },
-        "queryThresholdInSecs" => {
+        "query-threshold-in-seconds" => {
             "type" => INT,
             "description" => "Long running query threshold, after which a alert can be generated by tooling if configured",
             "required" => false,
             "max-occurs" => 1,
             "default" => 600
         },
-        "maxSourceRows" => {
+        "max-source-rows-allowed" => {
             "type" => INT,
             "description" => "Maximum rows allowed from a source query. -1 indicates no limit. (default -1)",
             "required" => false,
             "max-occurs" => 1,
             "default" => -1
         },
-        "exceptionOnMaxSourceRows" => {
+        "exception-on-max-source-rows" => {
             "type" => BOOLEAN,
             "description" => "Indicates if an exception should be thrown if the specified value for Maximum Source Rows is exceeded; only up to the maximum rows will be consumed. (default true)",
             "required" => false,
             "max-occurs" => 1,
             "default" => true
         },
-        "maxODBCLobSizeAllowed" => {
+        "max-odbc-lob-size-allowed" => {
             "type" => INT,
             "description" => "Maximum size of lob allowed through ODBC connection in bytes (default 5MB)",
             "required" => false,
             "max-occurs" => 1,
             "default" => 5242880
         },
-        "eventDistributorName" => {
+        "event-distributor-name" => {
             "type" => STRING,
             "description" => "The JNDI name of the Teiid Event Distributor",
             "required" => false,
             "max-occurs" => 1,
             "default" => "teiid/event-distributor"
         },
-        "detectingChangeEvents" => {
+        "detect-change-events" => {
             "type" => BOOLEAN,
             "description" => "Set to true for the engine to detect local change events. Should be disabled if using external change data capture tools. (default true)",
             "required" => false,
@@ -148,62 +127,56 @@
             "max-occurs" => 1,
             "min-occurs" => 1,
             "attributes" => {
-                "useDisk" => {
+                "use-disk" => {
                     "type" => BOOLEAN,
                     "description" => "Use disk for buffer management",
                     "required" => false,
                     "max-occurs" => 1,
                     "default" => true
                 },
-                "diskDirectory" => {
-                    "type" => STRING,
-                    "description" => "Directory location for the buffer files",
-                    "required" => true,
-                    "max-occurs" => 1
-                },
-                "processorBatchSize" => {
+                "processor-batch-size" => {
                     "type" => INT,
                     "description" => "The max row count of a batch sent internally within the query processor. Should be <= the connectorBatchSize. (default 512)",
                     "required" => false,
                     "max-occurs" => 1,
                     "default" => 512
                 },
-                "connectorBatchSize" => {
+                "connector-batch-size" => {
                     "type" => INT,
                     "description" => "The max row count of a batch from a connector. Should be even multiple of processorBatchSize. (default 1024)",
                     "required" => false,
                     "max-occurs" => 1,
                     "default" => 1024
                 },
-                "maxReserveBatchColumns" => {
+                "max-processing-kb" => {
                     "type" => INT,
-                    "description" => "The number of batch columns to allow in buffer memory. -1 means to automatically calculate a value (default -1). See the admin guide for more.",
+                    "description" => "The approximate amount of buffer memory in kilobytes allowable for a single processing operation (sort, grouping, etc.) regardless of existing memory commitments. -1 means to automatically calculate a value (default -1)",
                     "required" => false,
                     "max-occurs" => 1,
                     "default" => -1
                 },
-                "maxProcessingBatchesColumns" => {
+                "max-reserve-kb" => {
                     "type" => INT,
-                    "description" => "The number of batch columns guaranteed to a processing operation. -1 means to automatically calculate a value (default -1). See the admin guide for more.",
+                    "description" => "The approximate amount of memory in kilobytes allowed to be held by the buffer manager. -1 means to automatically calculate a value (default -1)",
                     "required" => false,
                     "max-occurs" => 1,
                     "default" => -1
                 },
-                "maxFileSize" => {
-                    "type" => INT,
+                "max-file-size" => {
+                    "type" => LONG,
                     "description" => "Max File size in MB (default 2GB)",
                     "required" => false,
                     "max-occurs" => 1,
-                    "default" => 2048
+                    "default" => 2048L
                 },
-                "maxBufferSpace" => {
-                    "type" => INT,
+                "max-buffer-space" => {
+                    "type" => LONG,
                     "description" => "Max storage space, in MB, to be used for buffer files (default 50G)",
                     "required" => false,
                     "max-occurs" => 1,
-                    "default" => 51200
+                    "default" => 51200L
                 },
-                "maxOpenFiles" => {
+                "max-open-files" => {
                     "type" => INT,
                     "description" => "Max open buffer files (default 64)",
                     "required" => false,
@@ -364,7 +337,7 @@
                 },
                 "mode" => {
                     "type" => STRING,
-                    "description" => "can be one of disabled, login, or enabled disabled = no transport or message level security will be used; login = only the login traffic will be encrypted at a message level using 128 bit AES with an ephemerial DH key exchange. No other config values are needed in this mode; enabled = traffic will be secured using this configuration.",
+                    "description" => "can be one of disabled, login, or enabled disabled = no transport or message level security will be used; login = only the login traffic will be encrypted at a message level using 128 bit AES with an ephemerial DH key exchange. No other config values are needed in this mode; enabled = traffic will be secured using this configuration,if the client supports SSL",
                     "required" => false,
                     "max-occurs" => 1,
                     "default" => "login"
@@ -473,7 +446,7 @@
                 },
                 "mode" => {
                     "type" => STRING,
-                    "description" => "can be one of disabled, login, or enabled disabled = no transport or message level security will be used; login = only the login traffic will be encrypted at a message level using 128 bit AES with an ephemerial DH key exchange. No other config values are needed in this mode; enabled = traffic will be secured using this configuration.",
+                    "description" => "can be one of disabled, login, or enabled disabled = no transport or message level security will be used; login = only the login traffic will be encrypted at a message level using 128 bit AES with an ephemerial DH key exchange. No other config values are needed in this mode; enabled = traffic will be secured using this configuration,if the client supports SSL",
                     "required" => false,
                     "max-occurs" => 1,
                     "default" => "login"

Modified: branches/as7/jboss-integration/src/test/resources/teiid-sample-config.xml
===================================================================
--- branches/as7/jboss-integration/src/test/resources/teiid-sample-config.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/jboss-integration/src/test/resources/teiid-sample-config.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,21 +1,18 @@
 <subsystem xmlns="urn:jboss:domain:teiid:1.0">
     <query-engine>
-        <thread-group-async>teiid-async</thread-group-async>
-        <maxThreads>64</maxThreads>
-        <maxActivePlans>20</maxActivePlans>
-        <userRequestSourceConcurrency>0</userRequestSourceConcurrency>
-        <timeSliceInMilli>2000</timeSliceInMilli>
-        <maxRowsFetchSize>20480</maxRowsFetchSize>
-        <lobChunkSizeInKB>100</lobChunkSizeInKB>
-        <useDataRoles>true</useDataRoles>
-        <allowCreateTemporaryTablesByDefault>true</allowCreateTemporaryTablesByDefault>
-        <allowFunctionCallsByDefault>true</allowFunctionCallsByDefault>
-        <queryThresholdInSecs>600</queryThresholdInSecs>
-        <maxSourceRows>-1</maxSourceRows>
-        <exceptionOnMaxSourceRows>true</exceptionOnMaxSourceRows>
-        <maxODBCLobSizeAllowed>5242880</maxODBCLobSizeAllowed>
-        <eventDistributorName>teiid/event-distributor</eventDistributorName>
-        <detectingChangeEvents>true</detectingChangeEvents>
+        <async-thread-group>teiid-async</async-thread-group>
+        <max-threads>64</max-threads>
+        <max-active-plans>20</max-active-plans>
+        <thread-count-for-source-concurrency>0</thread-count-for-source-concurrency>
+        <time-slice-in-millseconds>2000</time-slice-in-millseconds>
+        <max-row-fetch-size>20480</max-row-fetch-size>
+        <lob-chunk-size-in-kb>100</lob-chunk-size-in-kb>
+        <query-threshold-in-seconds>600</query-threshold-in-seconds>
+        <max-source-rows-allowed>-1</max-source-rows-allowed>
+        <exception-on-max-source-rows>true</exception-on-max-source-rows>
+        <max-odbc-lob-size-allowed>5242880</max-odbc-lob-size-allowed>
+        <event-distributor-name>teiid/event-distributor</event-distributor-name>
+        <detect-change-events>true</detect-change-events>
 
         <security-domain>teiid-security</security-domain>
         <max-sessions-allowed>5000</max-sessions-allowed>
@@ -23,15 +20,14 @@
         <allow-env-function>false</allow-env-function>
 
         <buffer-service>
-            <useDisk>true</useDisk>
-            <diskDirectory>${jboss.server.temp.dir}/teiid</diskDirectory>
-            <processorBatchSize>512</processorBatchSize>
-            <connectorBatchSize>1024</connectorBatchSize>
-            <maxReserveBatchColumns>-1</maxReserveBatchColumns>
-            <maxProcessingBatchesColumns>-1</maxProcessingBatchesColumns>
-            <maxFileSize>2048</maxFileSize>
-            <maxBufferSpace>51200</maxBufferSpace>
-            <maxOpenFiles>64</maxOpenFiles>
+            <use-disk>true</use-disk>
+            <processor-batch-size>512</processor-batch-size>
+            <connector-batch-size>1024</connector-batch-size>
+            <max-processing-kb>-1</max-processing-kb>
+            <max-reserve-kb>-1</max-reserve-kb>
+            <max-file-size>2048</max-file-size>
+            <max-buffer-space>51200</max-buffer-space>
+            <max-open-files>64</max-open-files>
         </buffer-service>
         
         <distributed-cache-factory>


Property changes on: branches/as7/metadata
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Copied: branches/as7/metadata/DATATYPES.INDEX (from rev 3382, trunk/metadata/DATATYPES.INDEX)
===================================================================
(Binary files differ)

Modified: branches/as7/metadata/pom.xml
===================================================================
--- branches/as7/metadata/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/metadata/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
   <parent>
     <artifactId>teiid-parent</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>teiid-metadata</artifactId>
@@ -69,6 +69,12 @@
 		<artifactId>jboss-managed</artifactId>
 	</dependency>
      -->
+     
+    <dependency>
+        <groupId>org.jboss.logging</groupId>
+        <artifactId>jboss-logging</artifactId>
+        <scope>test</scope>        
+    </dependency>     
   
   </dependencies>
   

Modified: branches/as7/metadata/src/main/resources/System.vdb
===================================================================
(Binary files differ)


Property changes on: branches/as7/metadata/src/main/resources/org
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/metadata/src/main/resources/org/teiid
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/metadata/src/main/resources/org/teiid/metadata/i18n.properties
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java
===================================================================
--- branches/as7/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/metadata/src/test/java/org/teiid/cdk/api/TranslationUtility.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,7 +24,9 @@
 
 import java.io.IOException;
 import java.net.URL;
+import java.util.ArrayList;
 import java.util.Collection;
+import java.util.List;
 
 import org.teiid.cdk.CommandBuilder;
 import org.teiid.dqp.internal.datamgr.RuntimeMetadataImpl;
@@ -53,25 +55,36 @@
 public class TranslationUtility {
     
     private QueryMetadataInterface metadata;
+    private FunctionLibrary functionLibrary;
 
     /**
      * Construct a utility instance with a given vdb file.  
      * @param vdbFile The .vdb file name representing metadata for the connector
      */
     public TranslationUtility(String vdbFile) {
-        metadata = VDBMetadataFactory.getVDBMetadata(vdbFile);     
+        initWrapper(VDBMetadataFactory.getVDBMetadata(vdbFile));
     }
+
+	private void initWrapper(QueryMetadataInterface acutalMetadata) {
+		functionLibrary = acutalMetadata.getFunctionLibrary();
+		metadata = new BasicQueryMetadataWrapper(acutalMetadata) {
+        	@Override
+        	public FunctionLibrary getFunctionLibrary() {
+        		return functionLibrary;
+        	}
+        };
+	}
     
-    public TranslationUtility(URL url) {
+    public TranslationUtility(String vdbName, URL url) {
         try {
-			metadata = VDBMetadataFactory.getVDBMetadata(url, null);
+    		initWrapper(VDBMetadataFactory.getVDBMetadata(vdbName, url, null));
 		} catch (IOException e) {
 			throw new RuntimeException(e);
 		}     
     }
     
     public TranslationUtility(QueryMetadataInterface metadata) {
-    	this.metadata = metadata;
+    	initWrapper(metadata);
     }
     
     public Command parseCommand(String sql, boolean generateAliases, boolean supportsGroupAliases) {
@@ -98,14 +111,13 @@
     public RuntimeMetadata createRuntimeMetadata() {
         return new RuntimeMetadataImpl(metadata);
     }
+    
+    private List<FunctionTree> functions = new ArrayList<FunctionTree>();
+    
+    public void addUDF(String schema, Collection<FunctionMethod> methods) {
+    	this.functions.add(new FunctionTree(schema, new UDFSource(methods)));
+		SystemFunctionManager sfm = new SystemFunctionManager();
+		functionLibrary = new FunctionLibrary(sfm.getSystemFunctions(), this.functions.toArray(new FunctionTree[this.functions.size()]));
+    }
 
-	public void setUDF(final Collection<FunctionMethod> methods) {
-		this.metadata = new BasicQueryMetadataWrapper(this.metadata) {
-			@Override
-			public FunctionLibrary getFunctionLibrary() {
-				SystemFunctionManager sfm = new SystemFunctionManager();
-				return new FunctionLibrary(sfm.getSystemFunctions(), new FunctionTree("foo", new UDFSource(methods)));  //$NON-NLS-1$
-			}
-		};
-	}
 }

Modified: branches/as7/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java
===================================================================
--- branches/as7/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/metadata/src/test/java/org/teiid/cdk/unittest/FakeTranslationFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,10 +22,18 @@
 
 package org.teiid.cdk.unittest;
 
+import java.util.List;
+
 import org.teiid.cdk.api.TranslationUtility;
-import org.teiid.query.unittest.FakeMetadataFactory;
+import org.teiid.core.types.DataTypeManager;
+import org.teiid.metadata.Column;
+import org.teiid.metadata.MetadataStore;
+import org.teiid.metadata.Schema;
+import org.teiid.metadata.Table;
+import org.teiid.metadata.Column.SearchType;
+import org.teiid.query.unittest.RealMetadataFactory;
 
-
+ at SuppressWarnings("nls")
 public class FakeTranslationFactory {
 	
 	private static FakeTranslationFactory instance = new FakeTranslationFactory();
@@ -35,15 +43,52 @@
 	}
 
 	public TranslationUtility getBQTTranslationUtility() {
-		return new TranslationUtility(FakeMetadataFactory.exampleBQTCached());
+		return new TranslationUtility(RealMetadataFactory.exampleBQTCached());
 	}
 	
 	public TranslationUtility getYahooTranslationUtility() {
-		return new TranslationUtility(FakeMetadataFactory.exampleYahoo());
+		MetadataStore metadataStore = new MetadataStore();
+        // Create models
+        Schema yahoo = RealMetadataFactory.createPhysicalModel("Yahoo", metadataStore); //$NON-NLS-1$
+        
+        // Create physical groups
+        Table quotes = RealMetadataFactory.createPhysicalGroup("Yahoo.QuoteServer", yahoo); //$NON-NLS-1$
+                
+        // Create physical elements
+        String[] elemNames = new String[] {
+            "TickerSymbol", "LastTrade",  //$NON-NLS-1$ //$NON-NLS-2$
+            "LastTradeDate", "LastTradeTime", //$NON-NLS-1$ //$NON-NLS-2$
+            "PercentageChange", "TickerSymbol2",  //$NON-NLS-1$ //$NON-NLS-2$
+            "DaysHigh", "DaysLow",  //$NON-NLS-1$ //$NON-NLS-2$
+            "TotalVolume"             //$NON-NLS-1$
+        };
+        String[] elemTypes = new String[] {  
+            DataTypeManager.DefaultDataTypes.STRING, DataTypeManager.DefaultDataTypes.DOUBLE,
+            DataTypeManager.DefaultDataTypes.DATE, DataTypeManager.DefaultDataTypes.TIME,
+            DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.STRING,
+            DataTypeManager.DefaultDataTypes.DOUBLE, DataTypeManager.DefaultDataTypes.DOUBLE,
+            DataTypeManager.DefaultDataTypes.BIG_INTEGER            
+        };
+        
+        List<Column> cols = RealMetadataFactory.createElements(quotes, elemNames, elemTypes);
+        
+        // Set name in source on each column
+        String[] nameInSource = new String[] {
+           "Symbol", "Last", "Date", "Time", "Change", "Symbol2", "High", "Low", "Volume"        
+        };
+        for(int i=0; i<nameInSource.length; i++) {
+            cols.get(i).setNameInSource(nameInSource[i]);
+        }
+        
+        // Set column-specific properties
+        cols.get(0).setSelectable(false);
+        cols.get(0).setSearchType(SearchType.Unsearchable);
+        
+		return new TranslationUtility(RealMetadataFactory.createTransformationMetadata(metadataStore, "yahoo"));
 	}
 	
 	public TranslationUtility getExampleTranslationUtility() {
-		return new TranslationUtility(FakeMetadataFactory.example1Cached());
+		return new TranslationUtility(RealMetadataFactory.example1Cached());
 	}
 	
 }

Copied: branches/as7/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java (from rev 3382, trunk/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java)
===================================================================
--- branches/as7/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java	                        (rev 0)
+++ branches/as7/metadata/src/test/java/org/teiid/metadata/index/TestStagingTable.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,40 @@
+/*
+ * 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 org.teiid.metadata.index;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.query.metadata.TransformationMetadata;
+
+ at SuppressWarnings("nls")
+public class TestStagingTable {
+
+	@Test public void testStagingTables() throws Exception {
+		TransformationMetadata tm = VDBMetadataFactory.getVDBMetadata(UnitTestUtil.getTestDataPath() + "/other/test.vdb");
+		
+		assertEquals(1, tm.getXMLTempGroups(tm.getGroupID("doc.newxmldocument")).size());
+	}
+	
+}

Modified: branches/as7/metadata/src/test/java/org/teiid/metadata/index/VDBMetadataFactory.java
===================================================================
--- branches/as7/metadata/src/test/java/org/teiid/metadata/index/VDBMetadataFactory.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/metadata/src/test/java/org/teiid/metadata/index/VDBMetadataFactory.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,20 +24,22 @@
 
 import java.io.File;
 import java.io.IOException;
-import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URISyntaxException;
 import java.net.URL;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.concurrent.Executors;
 
 import javax.xml.bind.JAXBException;
 
+import org.jboss.vfs.TempFileProvider;
+import org.jboss.vfs.VFS;
+import org.jboss.vfs.VirtualFile;
 import org.teiid.core.CoreConstants;
 import org.teiid.core.TeiidRuntimeException;
 import org.teiid.core.util.FileUtils;
 import org.teiid.core.util.LRUCache;
-import org.teiid.core.util.UnitTestUtil;
 import org.teiid.metadata.FunctionMethod;
 import org.teiid.metadata.MetadataStore;
 import org.teiid.query.function.FunctionTree;
@@ -56,7 +58,8 @@
 	
 	public static TransformationMetadata getVDBMetadata(String vdbFile) {
 		try {
-			return getVDBMetadata(new File(vdbFile).toURI().toURL(), null);
+			File f = new File(vdbFile);
+			return getVDBMetadata(f.getName(), f.toURI().toURL(), null);
 		} catch (IOException e) {
 			throw new TeiidRuntimeException(e);
 		}
@@ -65,7 +68,7 @@
 	public static MetadataStore getSystem() {
 		try {
 			if (system == null) {
-				system = loadMetadata(Thread.currentThread().getContextClassLoader().getResource(CoreConstants.SYSTEM_VDB)).getMetadataStore(null);
+				system = loadMetadata( CoreConstants.SYSTEM_VDB, Thread.currentThread().getContextClassLoader().getResource(CoreConstants.SYSTEM_VDB)).getMetadataStore(null);
 			}
 			return system;
 		} catch (Exception e) {
@@ -73,14 +76,14 @@
 		}
     }
 	
-	public static TransformationMetadata getVDBMetadata(URL vdbURL, URL udfFile) throws IOException {
+	public static TransformationMetadata getVDBMetadata(String vdbName, URL vdbURL, URL udfFile) throws IOException {
 		TransformationMetadata vdbmetadata = VDB_CACHE.get(vdbURL);
 		if (vdbmetadata != null) {
 			return vdbmetadata;
 		}
 
 		try {
-			IndexMetadataFactory imf = loadMetadata(vdbURL);
+			IndexMetadataFactory imf = loadMetadata(vdbName, vdbURL);
 			
 			Collection <FunctionMethod> methods = null;
 			Collection<FunctionTree> trees = null;
@@ -100,17 +103,14 @@
 		}
     }
 
-	public static IndexMetadataFactory loadMetadata(URL vdbURL)
-			throws IOException, MalformedURLException, URISyntaxException {
-		//vfs has a problem with vdbs embedded in jars in the classpath, so we'll create a temp version
-		if (vdbURL.getProtocol().equals("jar")) {
-			InputStream is = vdbURL.openStream();
-			File temp = File.createTempFile("temp", ".vdb", new File(UnitTestUtil.getTestScratchPath()));
-			temp.deleteOnExit();
-			FileUtils.write(is, temp);
-			vdbURL = temp.toURI().toURL();
-		}
-		return new IndexMetadataFactory(vdbURL);
+	public static IndexMetadataFactory loadMetadata(String vdbName, URL url) throws IOException, MalformedURLException, URISyntaxException {
+    	VirtualFile root = VFS.getChild(vdbName);
+    	if (!root.exists()) {
+    		VFS.mountZip(url.openStream(), vdbName, root, TempFileProvider.create("vdbs", Executors.newScheduledThreadPool(2)));
+    		// once done this mount should be closed, since this class is only used testing
+    		// it is hard to event when the test is done, otherwise we need to elevate the VFS to top
+    	}
+    	return new IndexMetadataFactory(root);
 	}
 
 }

Deleted: branches/as7/metadata/src/test/resources/other/test.vdb
===================================================================
(Binary files differ)

Copied: branches/as7/metadata/src/test/resources/other/test.vdb (from rev 3382, trunk/metadata/src/test/resources/other/test.vdb)
===================================================================
(Binary files differ)

Modified: branches/as7/pom.xml
===================================================================
--- branches/as7/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -5,12 +5,12 @@
 	<artifactId>teiid-parent</artifactId>
 	<packaging>pom</packaging>
 	<name>Teiid</name>
-	<version>7.5.0.Alpha1-SNAPSHOT</version>
+	<version>7.6.0.Alpha1-SNAPSHOT</version>
 	<description>Federated SQL and XML query engine.</description>
 	<properties>
 		<ant.version>1.7.0</ant.version>
 		<site.url>http://www.jboss.org/teiid</site.url>
-        <jbossas-version>7.0.0.CR1</jbossas-version>
+        <jbossas-version>7.0.1.Final</jbossas-version>
 	</properties>
 	<scm>
         <connection>scm:svn:https://anonsvn.jboss.org/repos/teiid/trunk</connection>
@@ -377,19 +377,19 @@
             <dependency>
                 <groupId>org.jboss</groupId>
                 <artifactId>staxmapper</artifactId>
-                <version>1.0.0.Beta4</version>
+                <version>1.0.0.Final</version>
             </dependency>
     
             <dependency>
                 <groupId>org.jboss</groupId>
                 <artifactId>jboss-dmr</artifactId>
-                <version>1.0.0.Beta6</version>
+                <version>1.0.0.Final</version>
             </dependency>
             
             <dependency>
                 <groupId>org.jboss.msc</groupId>
                 <artifactId>jboss-msc</artifactId>
-                <version>1.0.0.CR2</version>
+                <version>1.0.0.GA</version>
             </dependency> 
             <dependency>
                 <groupId>org.jboss</groupId>
@@ -409,7 +409,7 @@
             <dependency>
                 <groupId>org.picketbox</groupId>
                 <artifactId>picketbox</artifactId>
-                <version>4.0.0.CR1</version>
+                <version>4.0.1</version>
             </dependency>           
             <dependency>
                 <groupId>org.jboss.as</groupId>
@@ -435,7 +435,12 @@
                 <groupId>org.jboss.as</groupId>
                 <artifactId>jboss-as-cli</artifactId>  
                 <version>${jbossas-version}</version>          
-            </dependency>      
+            </dependency>   
+            <dependency>
+                <groupId>org.jboss.logging</groupId>
+                <artifactId>jboss-logging</artifactId>
+                <version>3.0.0.CR1</version>
+            </dependency>               
                      
             <!-- 
 			<dependency>
@@ -473,19 +478,13 @@
              -->    
 			<dependency>
 				<groupId>net.sourceforge.saxon</groupId>
-				<artifactId>saxon</artifactId>
-				<version>9.1.0.8</version>
+				<artifactId>saxonhe</artifactId>
+				<version>9.2.1.5</version>
 			</dependency>
 			<dependency>
-				<groupId>net.sourceforge.saxon</groupId>
-				<artifactId>saxon</artifactId>
-				<classifier>dom</classifier>
-				<version>9.1.0.8</version>
-			</dependency>
-			<dependency>
 				<groupId>org.jboss.netty</groupId>
 				<artifactId>netty</artifactId>
-				<version>3.2.1.Final</version>
+				<version>3.2.3.Final</version>
 			</dependency>
 			<dependency>
 				<groupId>org.apache.ant</groupId>
@@ -542,4 +541,4 @@
             <url>https://repository.jboss.org/nexus/content/repositories/snapshots/</url>
         </snapshotRepository>
     </distributionManagement>
-</project>
\ No newline at end of file
+</project>

Modified: branches/as7/runtime/pom.xml
===================================================================
--- branches/as7/runtime/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
   <parent>
     <artifactId>teiid-parent</artifactId>
     <groupId>org.jboss.teiid</groupId>
-    <version>7.5.0.Alpha1-SNAPSHOT</version>
+    <version>7.6.0.Alpha1-SNAPSHOT</version>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <groupId>org.jboss.teiid</groupId>

Modified: branches/as7/runtime/src/main/java/org/teiid/deployers/CompositeVDB.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/deployers/CompositeVDB.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/deployers/CompositeVDB.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -146,17 +146,19 @@
 		newMergedVDB.setConnectionType(this.vdb.getConnectionType());
 		ConnectorManagerRepository mergedRepo = new ConnectorManagerRepository();
 		mergedRepo.getConnectorManagers().putAll(this.cmr.getConnectorManagers());
-		for (CompositeVDB child:this.children.values()) {
-			
-			// add models
-			for (Model m:child.getVDB().getModels()) {
-				newMergedVDB.addModel((ModelMetaData)m);
+		if (this.children != null) {
+			for (CompositeVDB child:this.children.values()) {
+				
+				// add models
+				for (Model m:child.getVDB().getModels()) {
+					newMergedVDB.addModel((ModelMetaData)m);
+				}
+				
+				for (DataPolicy p:child.getVDB().getDataPolicies()) {
+					newMergedVDB.addDataPolicy((DataPolicyMetadata)p);
+				}
+				mergedRepo.getConnectorManagers().putAll(child.cmr.getConnectorManagers());
 			}
-			
-			for (DataPolicy p:child.getVDB().getDataPolicies()) {
-				newMergedVDB.addDataPolicy((DataPolicyMetadata)p);
-			}
-			mergedRepo.getConnectorManagers().putAll(child.cmr.getConnectorManagers());
 		}
 		newMergedVDB.addAttchment(ConnectorManagerRepository.class, mergedRepo);
 		return newMergedVDB;

Modified: branches/as7/runtime/src/main/java/org/teiid/deployers/ContainerLifeCycleListener.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/deployers/ContainerLifeCycleListener.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/deployers/ContainerLifeCycleListener.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,4 +23,10 @@
 
 public interface ContainerLifeCycleListener {
 	boolean isShutdownInProgress();
+	void addListener(LifeCycleEventListener listener);
+	
+	public static interface LifeCycleEventListener{
+		void onStartupFinish();
+		void onShutdownStart();
+	}
 }

Modified: branches/as7/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/deployers/PgCatalogMetadataStore.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -160,7 +160,8 @@
 				"pt.oid as atttypid," + //$NON-NLS-1$
 				"pt.typlen as attlen, " + //$NON-NLS-1$
 				"convert(t1.Position, short) as attnum, " + //$NON-NLS-1$
-				"t1.Length as atttypmod, " + //$NON-NLS-1$
+				"(CASE WHEN (t1.DataType = 'bigdecimal' OR t1.DataType = 'biginteger' OR t1.DataType = 'float' OR t1.DataType='double') THEN (4+(65536*t1.Precision)+t1.Scale) " + //$NON-NLS-1$
+				"ELSE (4+t1.Length) END) as atttypmod, " + //$NON-NLS-1$
 				"CASE WHEN (t1.NullType = 'No Nulls') THEN true ELSE false END as attnotnull, " + //$NON-NLS-1$
 				"false as attisdropped, " + //$NON-NLS-1$
 				"false as atthasdef " + //$NON-NLS-1$
@@ -312,10 +313,10 @@
 		String transformation = "SELECT t1.OID as oid, t1.Name as proname, (SELECT (CASE WHEN count(pp.Type)>0 THEN true else false END) as x FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName and pp.Type='ResultSet') as proretset, " + //$NON-NLS-1$
 		"CASE WHEN (SELECT count(dt.oid) FROM ProcedureParams pp, matpg_datatype dt WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type IN ('ReturnValue', 'ResultSet') AND dt.Name = pp.DataType) IS NULL THEN (select oid from pg_type WHERE typname = 'void') WHEN (SELECT count(dt.oid) FROM ProcedureParams pp, matpg_datatype dt WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type = 'ResultSet' AND dt.Name = pp.DataType) IS NOT NULL THEN (select oid from pg_type WHERE typname = 'record') ELSE (SELECT dt.oid FROM ProcedureParams pp, matpg_datatype dt WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type = 'ReturnValue' AND dt.Name = pp.DataType) END as prorettype,  " + //$NON-NLS-1$
 		"convert((SELECT count(*) FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type IN ('In', 'InOut')), short) as pronargs, " + //$NON-NLS-1$
-		"(select "+textAggStmt("y.oid","y.type, y.position" )+" FROM ("+paramTable("'ResultSet','ReturnValue', 'Out'")+") as y) as proargtypes, " +//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		"(select "+textAggStmt("y.name", "y.type, y.position")+" FROM (SELECT pp.Name as name, pp.position as position, pp.Type as type FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type NOT IN ('ReturnValue' )) as y) as proargnames, " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		"(select case WHEN count(distinct(y.type)) = 1 THEN null ELSE "+textAggStmt("CASE WHEN (y.type ='In') THEN 'i' WHEN (y.type = 'Out') THEN 'o' WHEN (y.type = 'InOut') THEN 'b' WHEN (y.type = 'ResultSet') THEN 't' END", "y.type,y.position")+" END FROM (SELECT pp.Type as type, pp.Position as position FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type NOT IN ('ReturnValue')) as y) as proargmodes, " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-		"(select case WHEN count(distinct(y.oid)) = 1 THEN null ELSE "+textAggStmt("y.oid", "y.type, y.position")+" END FROM ("+paramTable("'ReturnValue'")+") as y) as proallargtypes, " +  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+		"(select "+arrayAgg("y.oid","y.type, y.position" )+" FROM ("+paramTable("'ResultSet','ReturnValue', 'Out'")+") as y) as proargtypes, " +//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
+		"(select "+arrayAgg("y.name", "y.type, y.position")+" FROM (SELECT pp.Name as name, pp.position as position, pp.Type as type FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type NOT IN ('ReturnValue' )) as y) as proargnames, " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		"(select case WHEN count(distinct(y.type)) = 1 THEN null ELSE "+arrayAgg("CASE WHEN (y.type ='In') THEN 'i' WHEN (y.type = 'Out') THEN 'o' WHEN (y.type = 'InOut') THEN 'b' WHEN (y.type = 'ResultSet') THEN 't' END", "y.type,y.position")+" END FROM (SELECT pp.Type as type, pp.Position as position FROM ProcedureParams pp WHERE pp.ProcedureName = t1.Name AND pp.SchemaName = t1.SchemaName AND pp.Type NOT IN ('ReturnValue')) as y) as proargmodes, " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+		"(select case WHEN count(distinct(y.oid)) = 1 THEN null ELSE "+arrayAgg("y.oid", "y.type, y.position")+" END FROM ("+paramTable("'ReturnValue'")+") as y) as proallargtypes, " +  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
 		"(SELECT OID FROM SYS.Schemas WHERE Name = t1.SchemaName) as pronamespace " + //$NON-NLS-1$
 		"FROM SYS.Procedures as t1";//$NON-NLS-1$			
 		
@@ -330,7 +331,7 @@
 	}
 	
 	
-	private String textAggStmt(String select, String orderby) {
+	private String arrayAgg(String select, String orderby) {
 		return "array_agg("+select+" ORDER BY "+orderby+")";  //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
 	}
 


Property changes on: branches/as7/runtime/src/main/java/org/teiid/deployers/VirtualDatabaseException.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCClientRemote.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,13 +21,14 @@
  */
 package org.teiid.odbc;
 
+import java.io.IOException;
 import java.sql.ParameterMetaData;
-import java.sql.ResultSetMetaData;
-import java.sql.Statement;
+import java.util.List;
 import java.util.Properties;
 
 import org.teiid.client.util.ResultsFuture;
 import org.teiid.jdbc.ResultSetImpl;
+import org.teiid.odbc.PGUtil.PgColInfo;
 
 public interface ODBCClientRemote {
 	
@@ -38,6 +39,12 @@
 	//	AuthenticationCleartextPassword (B)
 	void useClearTextAuthentication();
 
+	// AuthenticationGSS (B)
+	void useAuthenticationGSS();
+	
+	// AuthenticationGSSContinue (B)
+	void authenticationGSSContinue(byte[] serviceToken);
+	
 	//	AuthenticationOk (B)
 	//	BackendKeyData (B)
 	//	ParameterStatus (B)
@@ -62,11 +69,19 @@
 
 	//	RowDescription (B)
 	//	NoData (B)
-	void sendResultSetDescription(ResultSetMetaData metaData, Statement stmt);
+	void sendResultSetDescription(List<PgColInfo> cols);
 	
 	//	DataRow (B)
 	//	CommandComplete (B)
-	void sendResults(String sql, ResultSetImpl rs, ResultsFuture<Void> result, boolean describeRows);
+	void sendResults(String sql, ResultSetImpl rs, List<PgColInfo> cols, ResultsFuture<Integer> result, boolean describeRows);
+	
+	void sendCursorResults(ResultSetImpl rs, List<PgColInfo> cols, ResultsFuture<Integer> result, int rowCount);
+	
+	void sendPortalResults(String sql, ResultSetImpl rs, List<PgColInfo> cols, ResultsFuture<Integer> result, int rowCount, boolean portal);
+	
+	void sendMoveCursor(ResultSetImpl rs, int rowCount, ResultsFuture<Integer> results);
+	
+	void sendCommandComplete(String sql, int updateCount) throws IOException;	
 
 	//	CommandComplete (B)
 	void sendUpdateCount(String sql, int updateCount);
@@ -85,16 +100,14 @@
 	void functionCallResponse(byte[] data);
 	void functionCallResponse(int data);
 	
-	void sslDenied();
+	void sendSslResponse();
 	
 	// unimplemented backend messages
 	
 	//	AuthenticationKerberosV5 (B)
 	//	AuthenticationMD5Password (B)
 	//	AuthenticationSCMCredential (B)
-	//	AuthenticationGSS (B)
 	//	AuthenticationSSPI (B)
-	//	AuthenticationGSSContinue (B)
 	
 	//	CloseComplete (B)
 
@@ -106,8 +119,5 @@
 	//	NoticeResponse (B)
 	//	NotificationResponse (B)
 	
-	//	PortalSuspended (B)
-	
-		
-
+	void sendPortalSuspended();
 }

Modified: branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemote.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemote.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemote.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,12 +23,13 @@
 
 import java.util.Properties;
 
+import org.teiid.transport.PgFrontendProtocol.NullTerminatedStringDataInputStream;
+
 public interface ODBCServerRemote {
-	enum AuthenticationType {CLEARTEXT, MD5};
 	
 	void initialize(Properties props);
 	
-	void logon(String databaseName, String userid, String password);
+	void logon(String databaseName, String userid, NullTerminatedStringDataInputStream data);
 	
 	void prepare(String prepareName, String sql, int[] paramType);
 

Modified: branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/odbc/ODBCServerRemoteImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,31 +21,43 @@
  */
 package org.teiid.odbc;
 
+import static org.teiid.odbc.PGUtil.convertType;
+
 import java.io.IOException;
 import java.io.StringReader;
 import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
 import java.sql.Statement;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.Properties;
 import java.util.concurrent.ExecutionException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import org.teiid.client.security.ILogon;
+import org.teiid.client.security.LogonException;
+import org.teiid.client.security.LogonResult;
 import org.teiid.client.util.ResultsFuture;
 import org.teiid.core.util.ApplicationInfo;
 import org.teiid.core.util.StringUtil;
 import org.teiid.jdbc.ConnectionImpl;
 import org.teiid.jdbc.PreparedStatementImpl;
+import org.teiid.jdbc.ResultSetImpl;
 import org.teiid.jdbc.StatementImpl;
 import org.teiid.jdbc.TeiidDriver;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
+import org.teiid.odbc.PGUtil.PgColInfo;
 import org.teiid.runtime.RuntimePlugin;
 import org.teiid.transport.ODBCClientInstance;
+import org.teiid.transport.PgFrontendProtocol.NullTerminatedStringDataInputStream;
 
 /**
  * While executing the multiple prepared statements I see this bug currently
@@ -133,11 +145,17 @@
 	private static Pattern preparedAutoIncrement = Pattern.compile("select 1 \\s*from pg_catalog.pg_attrdef \\s*where adrelid = \\$1 AND adnum = \\$2 " + //$NON-NLS-1$
 			"\\s*and pg_catalog.pg_get_expr\\(adbin, adrelid\\) \\s*like '%nextval\\(%'", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
 	
-	private static Pattern deallocatePattern = Pattern.compile("DEALLOCATE \"(\\w+\\d+_*)\""); //$NON-NLS-1$
-	private static Pattern releasePattern = Pattern.compile("RELEASE (\\w+\\d+_*)"); //$NON-NLS-1$
-	private static Pattern savepointPattern = Pattern.compile("SAVEPOINT (\\w+\\d+_*)"); //$NON-NLS-1$
-	private static Pattern rollbackPattern = Pattern.compile("ROLLBACK\\s*(to)*\\s*(\\w+\\d+_*)*"); //$NON-NLS-1$
+	private static Pattern cursorSelectPattern = Pattern.compile("DECLARE \"(\\w+)\" CURSOR(\\s(WITH HOLD|SCROLL))? FOR (.*)", Pattern.CASE_INSENSITIVE|Pattern.DOTALL); //$NON-NLS-1$
+	private static Pattern fetchPattern = Pattern.compile("FETCH (\\d+) IN \"(\\w+)\".*", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
+	private static Pattern movePattern = Pattern.compile("MOVE (\\d+) IN \"(\\w+)\".*", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
+	private static Pattern closePattern = Pattern.compile("CLOSE \"(\\w+)\"", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
 	
+	private static Pattern deallocatePattern = Pattern.compile("DEALLOCATE \"(\\w+\\d+_*)\"", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
+	private static Pattern releasePattern = Pattern.compile("RELEASE (\\w+\\d?_*)", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
+	private static Pattern savepointPattern = Pattern.compile("SAVEPOINT (\\w+\\d?_*)", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
+	private static Pattern rollbackPattern = Pattern.compile("ROLLBACK\\s*(to)*\\s*(\\w+\\d+_*)*", Pattern.CASE_INSENSITIVE); //$NON-NLS-1$
+	
+	
 	private TeiidDriver driver;
 	private ODBCClientRemote client;
 	private Properties props;
@@ -151,11 +169,14 @@
 	// TODO: this is unbounded map; need to define some boundaries as to how many stmts each session can have
 	private Map<String, Prepared> preparedMap = Collections.synchronizedMap(new HashMap<String, Prepared>());
 	private Map<String, Portal> portalMap = Collections.synchronizedMap(new HashMap<String, Portal>());
+	private Map<String, Cursor> cursorMap = Collections.synchronizedMap(new HashMap<String, Cursor>());
+	private ILogon logon;
 	
-	public ODBCServerRemoteImpl(ODBCClientInstance client, AuthenticationType authType, TeiidDriver driver) {
+	public ODBCServerRemoteImpl(ODBCClientInstance client, AuthenticationType authType, TeiidDriver driver, ILogon logon) {
 		this.driver = driver;
 		this.client = client.getClient();
 		this.authType = authType;
+		this.logon = logon;
 	}
 	
 	@Override
@@ -167,18 +188,39 @@
 		if (this.authType.equals(AuthenticationType.CLEARTEXT)) {
 			this.client.useClearTextAuthentication();
 		}
-		else if (this.authType.equals(AuthenticationType.MD5)) {
-			// TODO: implement MD5 auth type
+		else if (this.authType.equals(AuthenticationType.KRB5)) {
+			this.client.useAuthenticationGSS();
 		}
 	}
 	
 	@Override
-	public void logon(String databaseName, String user, String password) {
+	public void logon(String databaseName, String user, NullTerminatedStringDataInputStream data) {
 		try {
-			 java.util.Properties info = new java.util.Properties();
-			String url = "jdbc:teiid:"+databaseName+";ApplicationName=ODBC"; //$NON-NLS-1$ //$NON-NLS-2$
+			java.util.Properties info = new java.util.Properties();
 			info.put("user", user); //$NON-NLS-1$
-			info.put("password", password); //$NON-NLS-1$
+			
+			String password = null; 
+			String passthroughAuthentication = ""; //$NON-NLS-1$
+			if (authType.equals(AuthenticationType.CLEARTEXT)) {
+				password = data.readString();
+			}
+			else if (authType.equals(AuthenticationType.KRB5)) {
+				byte[] serviceToken = data.readServiceToken();
+            	LogonResult result = this.logon.neogitiateGssLogin(this.props, serviceToken, false);
+            	if ((Boolean)result.getProperty(ILogon.KRB5_ESTABLISHED)) {
+	            	serviceToken = (byte[])result.getProperty(ILogon.KRB5TOKEN);
+	            	this.client.authenticationGSSContinue(serviceToken);
+	            	return;
+            	}
+            	passthroughAuthentication = ";PassthroughAuthentication=true"; //$NON-NLS-1$
+			}
+			
+			String url = "jdbc:teiid:"+databaseName+";ApplicationName=ODBC"+passthroughAuthentication; //$NON-NLS-1$ //$NON-NLS-2$
+
+			if (password != null) {
+				info.put("password", password); //$NON-NLS-1$
+			}
+			
 			this.connection =  (ConnectionImpl)driver.connect(url, info);
 			int hash = this.connection.getConnectionId().hashCode();
 			Enumeration keys = this.props.propertyNames();
@@ -193,9 +235,182 @@
 		} catch (SQLException e) {
 			errorOccurred(e);
 			terminate();
-		} 
+		} catch(LogonException e) {
+			errorOccurred(e);
+			terminate();
+		} catch (IOException e) {
+			errorOccurred(e);
+			terminate();			
+		}
 	}	
 	
+	private void cursorExecute(final String cursorName, final String sql, final ResultsFuture<Integer> completion) {
+		if (this.connection != null) {
+			if (sql != null) {
+				try {
+					// close if the name is already used or the unnamed prepare; otherwise
+					// stmt is alive until session ends.
+					Prepared previous = this.preparedMap.remove(cursorName);
+					if (previous != null) {
+						previous.stmt.close();
+					}
+					
+					final PreparedStatementImpl stmt = this.connection.prepareStatement(sql);
+	                this.executionFuture = stmt.submitExecute();
+	                this.executionFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {
+		        		@Override
+		        		public void onCompletion(ResultsFuture<Boolean> future) {
+		        			executionFuture = null;
+	                        try {
+				                if (future.get()) {
+				                	List<PgColInfo> cols = getPgColInfo(stmt.getResultSet().getMetaData());
+		                            cursorMap.put(cursorName, new Cursor(cursorName, sql, stmt, null, stmt.getResultSet(), cols));
+		        					client.sendCommandComplete("DECLARE CURSOR", 0); //$NON-NLS-1$		                            
+				                }
+				                else {
+				                	errorOccurred(RuntimePlugin.Util.getString("execution_failed")); //$NON-NLS-1$
+				                }
+	                        } catch (Throwable e) {
+	                            errorOccurred(e);
+	                        }
+			                completion.getResultsReceiver().receiveResults(1);			                	                        
+		        		}
+					});					
+				} catch (SQLException e) {
+					errorOccurred(e);
+					completion.getResultsReceiver().receiveResults(1);
+				} 
+			}
+		}
+		else {
+			errorOccurred(RuntimePlugin.Util.getString("no_active_connection")); //$NON-NLS-1$
+			completion.getResultsReceiver().receiveResults(1);
+		}
+		
+	}
+	
+	private void cursorFetch(String cursorName, int rows, final ResultsFuture<Integer> completion) {
+		Cursor cursor = this.cursorMap.get(cursorName);
+		if (cursor != null) {
+			cursor.fetchSize = rows;
+			ResultsFuture<Integer> result = new ResultsFuture<Integer>();
+			this.client.sendCursorResults(cursor.rs, cursor.columnMetadata, result, rows);
+			result.addCompletionListener(new ResultsFuture.CompletionListener<Integer>() {
+            	public void onCompletion(ResultsFuture<Integer> future) {
+            		int rowsSent = 0;
+            		try {
+						rowsSent = future.get();
+						client.sendCommandComplete("FETCH", rowsSent); //$NON-NLS-1$						
+					} catch (InterruptedException e) {
+						throw new AssertionError(e);
+					} catch (ExecutionException e) {
+						errorOccurred(e.getCause());
+					} catch (IOException e) {
+						errorOccurred(e);
+					}
+					completion.getResultsReceiver().receiveResults(rowsSent);
+            	};
+			});
+		}
+		else {
+			errorOccurred(RuntimePlugin.Util.getString("not_bound", cursorName)); //$NON-NLS-1$
+			completion.getResultsReceiver().receiveResults(1);
+		}
+	}
+	
+	private void cursorMove(String prepareName, int rows, final ResultsFuture<Integer> completion) {
+		
+		// win odbc driver sending a move after close; and error is ending up in failure; since the below
+		// is not harmful it is ok to send empty move.
+		if (rows == 0) {
+			try {
+				client.sendCommandComplete("MOVE", 0); //$NON-NLS-1$
+			} catch (IOException e) {
+				errorOccurred(e);
+			}
+			completion.getResultsReceiver().receiveResults(0);
+			return;			
+		}
+		
+		Cursor cursor = this.cursorMap.get(prepareName);
+		if (cursor != null) {
+			ResultsFuture<Integer> result = new ResultsFuture<Integer>();
+			this.client.sendMoveCursor(cursor.rs, rows, result);
+			result.addCompletionListener(new ResultsFuture.CompletionListener<Integer>() {
+            	public void onCompletion(ResultsFuture<Integer> future) {
+            		int rowsMoved = 0;
+            		try {
+						rowsMoved = future.get();
+						client.sendCommandComplete("MOVE", rowsMoved); //$NON-NLS-1$						
+					} catch (InterruptedException e) {
+						throw new AssertionError(e);
+					} catch (ExecutionException e) {
+						errorOccurred(e.getCause());
+					} catch (IOException e) {
+						errorOccurred(e);
+					}
+					completion.getResultsReceiver().receiveResults(rowsMoved);
+            	};
+			});			
+		}
+		else {
+			errorOccurred(RuntimePlugin.Util.getString("not_bound", prepareName)); //$NON-NLS-1$
+			completion.getResultsReceiver().receiveResults(1);
+		}
+	}	
+	
+	private void cursorClose(String prepareName) throws SQLException, IOException {
+		Cursor cursor = this.cursorMap.remove(prepareName);
+		if (cursor != null) {
+			cursor.rs.close();
+			cursor.stmt.close();
+			this.client.sendCommandComplete("CLOSE CURSOR", 0); //$NON-NLS-1$
+		}
+	}	
+	
+    private void sqlExecute(final String sql, final ResultsFuture<Integer> completion) throws SQLException {
+    	String modfiedSQL = fixSQL(sql); 
+    	final StatementImpl stmt = connection.createStatement();
+        executionFuture = stmt.submitExecute(modfiedSQL);
+        executionFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {
+    		@Override
+    		public void onCompletion(ResultsFuture<Boolean> future) {
+    			executionFuture = null;
+    			try {
+    				ResultsFuture<Integer> result = new ResultsFuture<Integer>();
+	                if (future.get()) {
+	                	if (stmt.getResultSet() != null) {
+	                		List<PgColInfo> cols = getPgColInfo(stmt.getResultSet().getMetaData());
+                            client.sendResults(sql, stmt.getResultSet(), cols, result, true);
+	                	}
+	                	else {
+	                		// handles the "SET" commands.
+		                	client.sendUpdateCount(sql, 0);
+		                	result.getResultsReceiver().receiveResults(1);
+	                	}					                	
+	                } else {
+	                	client.sendUpdateCount(sql, stmt.getUpdateCount());
+	                	setEncoding();
+	                	result.getResultsReceiver().receiveResults(1);
+	                }
+	                result.addCompletionListener(new ResultsFuture.CompletionListener<Integer>() {
+	                	public void onCompletion(ResultsFuture<Integer> future) {
+							try {
+								stmt.close();
+							} catch (SQLException e) {
+								LogManager.logDetail(LogConstants.CTX_ODBC, e, "Error closing statement"); //$NON-NLS-1$
+							}
+							completion.getResultsReceiver().receiveResults(1);
+	                	}
+	                });
+    			} catch (Throwable e) {
+    				errorOccurred(e);
+    				completion.getResultsReceiver().receiveResults(1);
+    			}
+    		}
+		});    	
+    }	
+	
 	@Override
 	public void prepare(String prepareName, String sql, int[] paramType) {
 		if (this.connection != null) {
@@ -274,60 +489,96 @@
 			bindName  = UNNAMED;
 		}		
 		
+		// special case cursor execution through portal
+		final Cursor cursor = this.cursorMap.get(bindName);
+		if (cursor != null) {
+			sendCursorResults(cursor);
+			return;
+		}		
+		
 		final Portal query = this.portalMap.get(bindName);
 		if (query == null) {
 			errorOccurred(RuntimePlugin.Util.getString("not_bound", bindName)); //$NON-NLS-1$
-		}				
-		else {
-			if (query.sql.trim().isEmpty()) {
-				this.client.emptyQueryReceived();
-				return;
-			}
-			
-            final PreparedStatementImpl stmt = query.stmt;
-            try {
-            	// maxRows = 0, means unlimited.
-            	if (maxRows != 0) {
-            		stmt.setMaxRows(maxRows);
-            	}
-            	
-                this.executionFuture = stmt.submitExecute();
-                executionFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {
-	        		@Override
-	        		public void onCompletion(ResultsFuture<Boolean> future) {
-	        			executionFuture = null;
-                        try {
-                        	ResultsFuture<Void> result = null;
-			                if (future.get()) {
-			                	result = new ResultsFuture<Void>();
-	                            client.sendResults(query.sql, stmt.getResultSet(), result, true);
-			                } else {
-			                	result = ResultsFuture.NULL_FUTURE;
-			                	client.sendUpdateCount(query.sql, stmt.getUpdateCount());
-			                	setEncoding();
-			                }
-		        			result.addCompletionListener(new ResultsFuture.CompletionListener<Void>() {
-                            	public void onCompletion(ResultsFuture<Void> future) {
-                            		try {
-										future.get();
-	                            		doneExecuting();
-									} catch (InterruptedException e) {
-										throw new AssertionError(e);
-									} catch (ExecutionException e) {
-										errorOccurred(e.getCause());
-									}
-                            	};
-							});
-                        } catch (Throwable e) {
-                            errorOccurred(e);
-                        }
-	        		}
-				});
-            } catch (SQLException e) {
-            	errorOccurred(e);
-            }			
+			return;
+		}	
+		
+		if (query.sql.trim().isEmpty()) {
+			this.client.emptyQueryReceived();
+			return;
 		}
+		
+        sendPortalResults(maxRows, query);			
 	}
+
+	private void sendPortalResults(int maxRows, final Portal query) {
+		final PreparedStatementImpl stmt = query.stmt;
+        try {
+        	// maxRows = 0, means unlimited.
+        	if (maxRows != 0) {
+        		stmt.setMaxRows(maxRows);
+        	}
+        	
+            this.executionFuture = stmt.submitExecute();
+            executionFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {
+        		@Override
+        		public void onCompletion(ResultsFuture<Boolean> future) {
+        			executionFuture = null;
+                    try {
+                    	ResultsFuture<Integer> result = new ResultsFuture<Integer>();
+		                if (future.get()) {
+		                	List<PgColInfo> cols = getPgColInfo(stmt.getResultSet().getMetaData());
+                            client.sendResults(query.sql, stmt.getResultSet(), cols, result, true);
+		                } else {
+		                	// null future
+		                	client.sendUpdateCount(query.sql, stmt.getUpdateCount());
+		                	setEncoding();
+		                	result.getResultsReceiver().receiveResults(1);
+		                }
+	        			result.addCompletionListener(new ResultsFuture.CompletionListener<Integer>() {
+                        	public void onCompletion(ResultsFuture<Integer> future) {
+                        		try {
+									future.get();
+                            		doneExecuting();
+								} catch (InterruptedException e) {
+									throw new AssertionError(e);
+								} catch (ExecutionException e) {
+									errorOccurred(e.getCause());
+								}
+                        	};
+						});
+                    } catch (Throwable e) {
+                        errorOccurred(e);
+                    }
+        		}
+			});
+        } catch (SQLException e) {
+        	errorOccurred(e);
+        }
+	}
+
+	private void sendCursorResults(final Cursor cursor) {
+		ResultsFuture<Integer> result = new ResultsFuture<Integer>();
+		this.client.sendPortalResults(cursor.sql, cursor.rs, cursor.columnMetadata, result, cursor.fetchSize, true);
+		result.addCompletionListener(new ResultsFuture.CompletionListener<Integer>() {
+			public void onCompletion(ResultsFuture<Integer> future) {
+				try {
+					int rowsSent = future.get();
+					if (rowsSent < cursor.fetchSize) {
+						client.sendCommandComplete(cursor.sql, 0);
+					}
+					else {
+						client.sendPortalSuspended();
+					}
+				} catch (InterruptedException e) {
+					throw new AssertionError(e);
+				} catch (ExecutionException e) {
+					errorOccurred(e.getCause());
+				} catch (IOException e) {
+					errorOccurred(e);
+				}
+			};
+		});
+	}
 	
 	private String fixSQL(String sql) {
 		String modified = modifySQL(sql);
@@ -409,16 +660,6 @@
 			}
 			else if ((m = rollbackPattern.matcher(modified)).matches()) {
 				return "ROLLBACK"; //$NON-NLS-1$
-			}	
-			else if ((m = savepointPattern.matcher(modified)).matches()) {
-				return "SELECT 'SAVEPOINT'"; //$NON-NLS-1$
-			}
-			else if ((m = releasePattern.matcher(modified)).matches()) {
-				return "SELECT 'RELEASE'"; //$NON-NLS-1$
-			}		
-			else if ((m = deallocatePattern.matcher(modified)).matches()) {
-				closePreparedStatement(m.group(1));
-				return "SELECT 'DEALLOCATE'"; //$NON-NLS-1$
 			}					
 		}
 		modified = sql;
@@ -431,7 +672,7 @@
 	@Override
 	public void executeQuery(final String query) {
 		if (beginExecution()) {
-			this.client.errorOccurred("Awaiting asynch result"); //$NON-NLS-1$
+			errorOccurred("Awaiting asynch result"); //$NON-NLS-1$
 			ready();
 			return;
 		}
@@ -477,7 +718,13 @@
 		}
 		else {
 			try {
+				// The response is a ParameterDescription message describing the parameters needed by the statement,
 				this.client.sendParameterDescription(query.stmt.getParameterMetaData(), query.paramType);
+				
+				// followed by a RowDescription message describing the rows that will be returned when the statement  
+				// is eventually executed (or a NoData message if the statement will not return rows).
+				List<PgColInfo> cols = getPgColInfo(query.stmt.getMetaData());
+				this.client.sendResultSetDescription(cols);
 			} catch (SQLException e) {
 				errorOccurred(e);
 			}
@@ -511,7 +758,8 @@
 		}
 		else {
 			try {
-				this.client.sendResultSetDescription(query.stmt.getMetaData(), query.stmt);
+				List<PgColInfo> cols = getPgColInfo(query.stmt.getMetaData());
+				this.client.sendResultSetDescription(cols);
 			} catch (SQLException e) {
 				errorOccurred(e);
 			}
@@ -617,6 +865,9 @@
 			
 		try {			
 			if (this.connection != null) {
+				if (!this.connection.getAutoCommit()) {
+					this.connection.rollback(false);
+				}
 				this.connection.close();
 			}
 		} catch (SQLException e) {
@@ -637,7 +888,7 @@
 	
 	@Override
 	public void sslRequest() {
-		this.client.sslDenied();
+		this.client.sendSslResponse();
 	}
 	
 	private void setEncoding() {
@@ -658,90 +909,124 @@
 	
     private final class QueryWorkItem implements Runnable {
 		private final ScriptReader reader;
-		String modfiedSQL;
 		String sql;
 
 		private QueryWorkItem(String query) {
-			this.reader = new ScriptReader(new StringReader(query));
+			this.reader = new ScriptReader(new StringReader(query));		
 		}
 
 		@Override
 		public void run() {
 			try {
-				if (modfiedSQL == null) {
+				if (sql == null) {
 					sql = reader.readStatement();
-			        modfiedSQL = fixSQL(sql);
 				}
-		        while (modfiedSQL != null) {
+		        while (sql != null) {
 		            try {
-		            	final StatementImpl stmt = connection.createStatement();
-		                executionFuture = stmt.submitExecute(modfiedSQL);
-		                executionFuture.addCompletionListener(new ResultsFuture.CompletionListener<Boolean>() {
-			        		@Override
-			        		public void onCompletion(ResultsFuture<Boolean> future) {
-			        			executionFuture = null;
-			        			try {
-			        				ResultsFuture<Void> result = null;
-					                if (future.get()) {
-					                	if (stmt.getResultSet() != null) {
-						                	result = new ResultsFuture<Void>();
-				                            client.sendResults(sql, stmt.getResultSet(), result, true);
-					                	}
-					                	else {
-					                		// handles the "SET" commands.
-						                	result = ResultsFuture.NULL_FUTURE;
-						                	client.sendUpdateCount(sql, 0);
-					                	}					                	
-					                } else {
-					                	result = ResultsFuture.NULL_FUTURE;
-					                	client.sendUpdateCount(sql, stmt.getUpdateCount());
-					                	setEncoding();
-					                }
-					                result.addCompletionListener(new ResultsFuture.CompletionListener<Void>() {
-		                            	public void onCompletion(ResultsFuture<Void> future) {
-		                            		try {
-												future.get();
-								                sql = reader.readStatement();
-								                modfiedSQL = fixSQL(sql);
-											} catch (InterruptedException e) {
-												throw new AssertionError(e);
-											} catch (IOException e) {
-												client.errorOccurred(e);
-												return;
-											} catch (ExecutionException e) {
-												client.errorOccurred(e.getCause());
-												return;
-											} finally {
-												try {
-													stmt.close();
-												} catch (SQLException e) {
-													LogManager.logDetail(LogConstants.CTX_ODBC, e, "Error closing statement"); //$NON-NLS-1$
-												}
-											}
-						        			QueryWorkItem.this.run(); //continue processing
-		                            	};
-									});
-			        			} catch (Throwable e) {
-			        				client.errorOccurred(e);
-			        				return;
-			        			}
-			        		}
-						});
+		    			
+		            	ResultsFuture<Integer> results = new ResultsFuture<Integer>();
+		    			results.addCompletionListener(new ResultsFuture.CompletionListener<Integer>() {
+		                	public void onCompletion(ResultsFuture<Integer> future) {
+		                		try {		                			
+		    						future.get();
+		    		                sql = reader.readStatement();
+		    					} catch (InterruptedException e) {
+		    						throw new AssertionError(e);
+		    					} catch (IOException e) {
+		    						client.errorOccurred(e);
+		    						return;
+		    					} catch (ExecutionException e) {
+		    						client.errorOccurred(e.getCause());
+		    						return;
+		    					}
+		            			QueryWorkItem.this.run(); //continue processing
+		                	};
+		    			});	
+		    			
+		    			if (isErrorOccurred()) {
+		    				if (!connection.getAutoCommit()) {
+		    					connection.rollback(false);
+		    				}
+		    				break;
+		    			}
+		    			
+		            	Matcher m = null;
+		    	        if ((m = cursorSelectPattern.matcher(sql)).matches()){
+		    				cursorExecute(m.group(1), fixSQL(m.group(4)), results);
+		    			}
+		    			else if ((m = fetchPattern.matcher(sql)).matches()){
+		    				cursorFetch(m.group(2), Integer.parseInt(m.group(1)), results);
+		    			}
+		    			else if ((m = movePattern.matcher(sql)).matches()){
+		    				cursorMove(m.group(2), Integer.parseInt(m.group(1)), results);
+		    			}
+		    			else if ((m = closePattern.matcher(sql)).matches()){
+		    				cursorClose(m.group(1));
+		    				results.getResultsReceiver().receiveResults(1);
+		    			}
+		    			else if ((m = savepointPattern.matcher(sql)).matches()) {
+		    				client.sendCommandComplete("SAVEPOINT", 0); //$NON-NLS-1$
+		    				results.getResultsReceiver().receiveResults(1);
+		    			}
+		    			else if ((m = releasePattern.matcher(sql)).matches()) {
+		    				client.sendCommandComplete("RELEASE", 0); //$NON-NLS-1$
+		    				results.getResultsReceiver().receiveResults(1);
+		    			}		
+		    			else if ((m = deallocatePattern.matcher(sql)).matches()) { 
+		    				closePreparedStatement(m.group(1));
+		    				client.sendCommandComplete("DEALLOCATE", 0); //$NON-NLS-1$
+		    				results.getResultsReceiver().receiveResults(1);
+		    			}
+		    			else {
+		    				sqlExecute(sql, results);
+		    			}
 		                return; //wait for the execution to finish
 		            } catch (SQLException e) {
-		                client.errorOccurred(e);
+		                errorOccurred(e);
 		                break;
 		            } 
 		        }
 			} catch(IOException e) {
-				client.errorOccurred(e);
+				errorOccurred(e);
 			}
 			doneExecuting();
 			ready();
 		}
-
 	}
-
+    
+	private List<PgColInfo> getPgColInfo(ResultSetMetaData meta)
+			throws SQLException {
+		int columns = meta.getColumnCount();
+		final ArrayList<PgColInfo> result = new ArrayList<PgColInfo>(columns);
+		for (int i = 1; i < columns + 1; i++) {
+			final PgColInfo info = new PgColInfo();
+			info.name = meta.getColumnLabel(i).toLowerCase();
+			info.type = meta.getColumnType(i);
+			info.type = convertType(info.type);
+			info.precision = meta.getColumnDisplaySize(i);
+			String name = meta.getColumnName(i);
+			String table = meta.getTableName(i);
+			String schema = meta.getSchemaName(i);
+			if (schema != null) {
+				final PreparedStatementImpl ps = this.connection.prepareStatement("select attrelid, attnum, typoid from matpg_relatt where attname = ? and relname = ? and nspname = ?"); //$NON-NLS-1$
+				ps.setString(1, name);
+				ps.setString(2, table);
+				ps.setString(3, schema);	
+				ResultSet rs = ps.executeQuery();
+				if (rs.next()) {
+					info.reloid = rs.getInt(1);
+					info.attnum = rs.getShort(2);
+					int specificType = rs.getInt(3);
+					if (!rs.wasNull()) {
+						info.type = specificType;
+					}
+				}					
+			}
+			result.add(info);
+		}
+		return result;
+	}  
+    
 	/**
      * Represents a PostgreSQL Prepared object.
      */
@@ -772,7 +1057,7 @@
         /**
          * The list of parameter types (if set).
          */
-        int[] paramType;
+        int[] paramType;        
     }
 
     /**
@@ -808,7 +1093,22 @@
         /**
          * The prepared statement.
          */
-        PreparedStatementImpl stmt;
+        PreparedStatementImpl stmt;        
     }
+    
+    static class Cursor extends Prepared {
+    	ResultSetImpl rs;
+    	int fetchSize = 1000;
+        /**
+         * calculated column metadata
+         */
+        List<PgColInfo> columnMetadata;	
+    	
+    	public Cursor (String name, String sql, PreparedStatementImpl stmt, int[] paramType, ResultSetImpl rs, List<PgColInfo> colMetadata) {
+    		super(name, sql, stmt, paramType);
+    		this.rs = rs;
+    		this.columnMetadata = colMetadata;
+    	}
+    }    
 
 }

Copied: branches/as7/runtime/src/main/java/org/teiid/odbc/PGUtil.java (from rev 3382, trunk/runtime/src/main/java/org/teiid/odbc/PGUtil.java)
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/odbc/PGUtil.java	                        (rev 0)
+++ branches/as7/runtime/src/main/java/org/teiid/odbc/PGUtil.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,114 @@
+/*
+ * 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 org.teiid.odbc;
+
+import java.sql.Types;
+
+import org.teiid.deployers.PgCatalogMetadataStore;
+
+public class PGUtil {
+
+	public static final int PG_TYPE_VARCHAR = 1043;
+
+	public static final int PG_TYPE_BOOL = 16;
+	public static final int PG_TYPE_BYTEA = 17;
+	public static final int PG_TYPE_BPCHAR = 1042;
+	public static final int PG_TYPE_INT8 = 20;
+	public static final int PG_TYPE_INT2 = 21;
+	public static final int PG_TYPE_INT4 = 23;
+	public static final int PG_TYPE_TEXT = 25;
+    //private static final int PG_TYPE_OID = 26;
+	public static final int PG_TYPE_FLOAT4 = 700;
+	public static final int PG_TYPE_FLOAT8 = 701;
+	public static final int PG_TYPE_UNKNOWN = 705;
+    
+	public static final int PG_TYPE_OIDVECTOR = PgCatalogMetadataStore.PG_TYPE_OIDVECTOR;
+	public static final int PG_TYPE_OIDARRAY = PgCatalogMetadataStore.PG_TYPE_OIDARRAY;
+	public static final int PG_TYPE_CHARARRAY = PgCatalogMetadataStore.PG_TYPE_CHARARRAY;
+	public static final int PG_TYPE_TEXTARRAY = PgCatalogMetadataStore.PG_TYPE_TEXTARRAY;
+    
+	public static final int PG_TYPE_DATE = 1082;
+	public static final int PG_TYPE_TIME = 1083;
+	public static final int PG_TYPE_TIMESTAMP_NO_TMZONE = 1114;
+	public static final int PG_TYPE_NUMERIC = 1700;
+    //private static final int PG_TYPE_LO = 14939;
+    
+	public static class PgColInfo {
+		public String name;
+		public int reloid;
+		public short attnum;
+		public int type;
+		public int precision;
+	}
+		
+	/**
+	 * Types.ARRAY is not supported
+	 */
+	public static int convertType(final int type) {
+        switch (type) {
+        case Types.BIT:
+        case Types.BOOLEAN:
+            return PG_TYPE_BOOL;
+        case Types.VARCHAR:
+            return PG_TYPE_VARCHAR;        
+        case Types.CHAR:
+            return PG_TYPE_BPCHAR;
+        case Types.TINYINT:
+        case Types.SMALLINT:
+        	return PG_TYPE_INT2;
+        case Types.INTEGER:
+            return PG_TYPE_INT4;
+        case Types.BIGINT:
+            return PG_TYPE_INT8;
+        case Types.NUMERIC:
+        case Types.DECIMAL:
+            return PG_TYPE_NUMERIC;
+        case Types.FLOAT:
+        case Types.REAL:
+            return PG_TYPE_FLOAT4;
+        case Types.DOUBLE:
+            return PG_TYPE_FLOAT8;
+        case Types.TIME:
+            return PG_TYPE_TIME;
+        case Types.DATE:
+            return PG_TYPE_DATE;
+        case Types.TIMESTAMP:
+            return PG_TYPE_TIMESTAMP_NO_TMZONE;
+            
+        case Types.BLOB:            
+        case Types.BINARY:
+        case Types.VARBINARY:
+        case Types.LONGVARBINARY:
+        	return PG_TYPE_BYTEA;
+        	
+        case Types.LONGVARCHAR:
+        case Types.CLOB:            
+        	return PG_TYPE_TEXT;
+        
+        case Types.SQLXML:        	
+            return PG_TYPE_TEXT;
+            
+        default:
+            return PG_TYPE_UNKNOWN;
+        }
+	}	
+}

Modified: branches/as7/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/services/BufferServiceImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -57,8 +57,8 @@
 	private int connectorBatchSize = BufferManager.DEFAULT_CONNECTOR_BATCH_SIZE;
     private int maxOpenFiles = FileStorageManager.DEFAULT_MAX_OPEN_FILES;
     private long maxFileSize = FileStorageManager.DEFAULT_MAX_FILESIZE; // 2GB
-    private int maxProcessingBatchesColumns = BufferManager.DEFAULT_MAX_PROCESSING_BATCHES;
-    private int maxReserveBatchColumns = BufferManager.DEFAULT_RESERVE_BUFFERS;
+    private int maxProcessingKb = BufferManager.DEFAULT_MAX_PROCESSING_KB;
+    private int maxReserveKb = BufferManager.DEFAULT_RESERVE_BUFFER_KB;
     private long maxBufferSpace = FileStorageManager.DEFAULT_MAX_BUFFERSPACE;
 	private FileStorageManager fsm;
 	
@@ -81,8 +81,8 @@
             this.bufferMgr = new BufferManagerImpl();
             this.bufferMgr.setConnectorBatchSize(Integer.valueOf(connectorBatchSize));
             this.bufferMgr.setProcessorBatchSize(Integer.valueOf(processorBatchSize));
-            this.bufferMgr.setMaxReserveBatchColumns(this.maxReserveBatchColumns);
-            this.bufferMgr.setMaxProcessingBatchColumns(this.maxProcessingBatchesColumns);
+            this.bufferMgr.setMaxReserveKB(this.maxReserveKb);
+            this.bufferMgr.setMaxProcessingKB(this.maxProcessingKb);
             
             this.bufferMgr.initialize();
             
@@ -160,14 +160,6 @@
     	this.maxFileSize = maxFileSize;
 	}
     
-    public void setMaxReserveBatchColumns(int value) {
-		this.maxReserveBatchColumns = value;
-	}    
-    
-    public void setMaxProcessingBatchesColumns(int value) {
-    	this.maxProcessingBatchesColumns  = value;
-    }
-
 	public long getMaxFileSize() {
 		return maxFileSize;
 	}
@@ -176,14 +168,22 @@
 		this.maxOpenFiles = maxOpenFiles;
 	}
 
-	public int getMaxProcessingBatchesColumns() {
-		return maxProcessingBatchesColumns;
+    public int getMaxProcessingKb() {
+		return maxProcessingKb;
 	}
 
-	public int getMaxReserveBatchColumns() {
-		return maxReserveBatchColumns;
+    public int getMaxReservedKb() {
+		return maxReserveKb;
 	}
     
+    public void setMaxProcessingKb(int maxProcessingKb) {
+		this.maxProcessingKb = maxProcessingKb;
+	}
+    
+    public void setMaxReserveKb(int maxReserveKb) {
+		this.maxReserveKb = maxReserveKb;
+	}
+    
 	public long getMaxBufferSpace() {
 		return maxBufferSpace;
 	}

Modified: branches/as7/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/services/SessionServiceImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,10 +22,26 @@
 
 package org.teiid.services;
 
-import java.util.*;
+
+import java.io.IOException;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Timer;
+import java.util.TimerTask;
 import java.util.concurrent.ConcurrentHashMap;
 
 import javax.security.auth.Subject;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.security.auth.login.LoginContext;
 import javax.security.auth.login.LoginException;
 
 import org.jboss.as.security.plugins.SecurityDomainContext;
@@ -44,6 +60,7 @@
 import org.teiid.logging.LogManager;
 import org.teiid.net.ServerConnection;
 import org.teiid.net.TeiidURL;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
 import org.teiid.runtime.RuntimePlugin;
 import org.teiid.security.Credentials;
 import org.teiid.security.SecurityHelper;
@@ -58,6 +75,8 @@
 	 */
     private long sessionMaxLimit = DEFAULT_MAX_SESSIONS;
 	private long sessionExpirationTimeLimit = DEFAULT_SESSION_EXPIRATION;
+	private String authenticationType = AuthenticationType.CLEARTEXT.name();
+	private String krb5SecurityDomain;
 	
 	/*
 	 * Injected state
@@ -162,6 +181,7 @@
         newSession.setApplicationName(applicationName);
         newSession.setClientHostName(properties.getProperty(TeiidURL.CONNECTION.CLIENT_HOSTNAME));
         newSession.setIPAddress(properties.getProperty(TeiidURL.CONNECTION.CLIENT_IP_ADDRESS));
+        newSession.setClientHardwareAddress(properties.getProperty(TeiidURL.CONNECTION.CLIENT_MAC));
         newSession.setSecurityDomain(securityDomain);
         if (vdb != null) {
 	        newSession.setVDBName(vdb.getName());
@@ -172,7 +192,7 @@
         newSession.setSubject(subject);
         newSession.setSecurityContext(securityContext);
         newSession.setVdb(vdb);
-        LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful for \"", userName, "\" - created SessionID \"", newSession.getSessionToken().getSessionID(), "\"" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+        LogManager.logDetail(LogConstants.CTX_SECURITY, new Object[] {"Logon successful, created", newSession }); //$NON-NLS-1$ 
         this.sessionCache.put(newSession.getSessionId(), newSession);
         return newSession;
 	}
@@ -225,6 +245,31 @@
 	}
 	
 	@Override
+	public LoginContext createLoginContext(final String securityDomain, final String user, final String password) throws LoginException{
+		CallbackHandler handler = new CallbackHandler() {
+			@Override
+			public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+				for (int i = 0; i < callbacks.length; i++) {
+					if (callbacks[i] instanceof NameCallback) {
+						NameCallback nc = (NameCallback)callbacks[i];
+						nc.setName(user);
+					} else if (callbacks[i] instanceof PasswordCallback) {
+						PasswordCallback pc = (PasswordCallback)callbacks[i];
+						if (password != null) {
+							pc.setPassword(password.toCharArray());
+						}
+					} else {
+						throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback"); //$NON-NLS-1$
+					}
+				}
+			}
+		}; 		
+		
+		TeiidLoginContext context = new TeiidLoginContext(this.securityHelper);
+		return context.createLoginContext(securityDomain, handler);
+	}
+	
+	@Override
 	public Collection<SessionMetadata> getActiveSessions() throws SessionServiceException {
 		return new ArrayList<SessionMetadata>(this.sessionCache.values());
 	}
@@ -307,8 +352,18 @@
 	
 	public void setSessionExpirationTimeLimit(long limit) {
 		this.sessionExpirationTimeLimit = limit;
-	}	
+	}
 	
+	@Override
+	public AuthenticationType getAuthType() {
+		return AuthenticationType.valueOf(this.authenticationType);
+	}
+	
+	public void setAuthenticationType(String flag) {
+		this.authenticationType = flag;
+		LogManager.logInfo(LogConstants.CTX_SECURITY, "Authentication Type set to: "+flag); //$NON-NLS-1$
+	}
+	
 	public void start() {
         this.sessionMonitor.schedule(new TimerTask() {
         	@Override
@@ -334,4 +389,23 @@
 	public void setDqp(DQPCore dqp) {
 		this.dqp = dqp;
 	}
+	
+	@Override
+	public void assosiateSubjectInContext(String securityDomain, Subject subject) {
+    	Principal principal = null;
+    	for(Principal p:subject.getPrincipals()) {
+			principal = p;
+			break;
+    	}
+    	this.securityHelper.assosiateSecurityContext(securityDomain, this.securityHelper.createSecurityContext(securityDomain, principal, null, subject));		
+	}
+	
+	public void setKrb5SecurityDomain(String domain) {
+		this.krb5SecurityDomain = domain;
+	}
+	
+	@Override
+	public String getKrb5SecurityDomain(){
+		return this.krb5SecurityDomain;
+	}	
 }

Modified: branches/as7/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/services/TeiidLoginContext.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,9 +24,16 @@
 
 import java.security.Principal;
 import java.security.acl.Group;
-import java.util.*;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginContext;
 import javax.security.auth.login.LoginException;
 
 import org.jboss.as.security.plugins.SecurityDomainContext;
@@ -130,6 +137,10 @@
     	return this.securityContext;
     }
     
+	public LoginContext createLoginContext(String domain, CallbackHandler handler) throws LoginException {
+    	return new LoginContext(domain, handler);
+    }    
+    
     static String getBaseUsername(String username) {
         if (username == null) {
             return username;

Modified: branches/as7/runtime/src/main/java/org/teiid/transport/LogonImpl.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/transport/LogonImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/transport/LogonImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,11 +22,18 @@
 
 package org.teiid.transport;
 
+import java.security.PrivilegedAction;
 import java.util.Collection;
 import java.util.Properties;
 
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
 import javax.security.auth.login.LoginException;
 
+import org.ietf.jgss.GSSContext;
+import org.ietf.jgss.GSSCredential;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.GSSManager;
 import org.teiid.adminapi.impl.SessionMetadata;
 import org.teiid.client.security.ILogon;
 import org.teiid.client.security.InvalidSessionException;
@@ -34,7 +41,6 @@
 import org.teiid.client.security.LogonResult;
 import org.teiid.client.security.SessionToken;
 import org.teiid.client.util.ResultsFuture;
-import org.teiid.core.ComponentNotFoundException;
 import org.teiid.core.CoreConstants;
 import org.teiid.core.TeiidComponentException;
 import org.teiid.dqp.internal.process.DQPWorkContext;
@@ -44,6 +50,8 @@
 import org.teiid.logging.LogManager;
 import org.teiid.net.CommunicationException;
 import org.teiid.net.TeiidURL;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
+import org.teiid.runtime.RuntimePlugin;
 import org.teiid.security.Credentials;
 
 
@@ -57,10 +65,17 @@
 		this.clusterName = clusterName;
 	}
 
-	public LogonResult logon(Properties connProps) throws LogonException,
-			ComponentNotFoundException {
+	public LogonResult logon(Properties connProps) throws LogonException, TeiidComponentException, CommunicationException {
+		if (!AuthenticationType.CLEARTEXT.equals(service.getAuthType())) {
+			throw new LogonException(RuntimePlugin.Util.getString("wrong_logon_type_jaas")); //$NON-NLS-1$
+		}
+		return logon(connProps, null);
+	}
+	
+	
+	private LogonResult logon(Properties connProps, byte[] krb5ServiceTicket) throws LogonException {
 		DQPWorkContext workContext = DQPWorkContext.getWorkContext();
-		SessionToken oldToken = workContext.getSessionToken();
+		String oldSessionId = workContext.getSessionId();
         String applicationName = connProps.getProperty(TeiidURL.CONNECTION.APP_NAME);
         // user may be null if using trustedToken to log on
         String user = connProps.getProperty(TeiidURL.CONNECTION.USER_NAME, CoreConstants.DEFAULT_ANON_USERNAME);
@@ -77,20 +92,94 @@
 	        if (DQPWorkContext.getWorkContext().getClientAddress() == null) {
 				sessionInfo.setEmbedded(true);
 	        }
-	        if (oldToken != null) {
+	        if (oldSessionId != null) {
 	        	try {
-					this.service.closeSession(oldToken.getSessionID());
+					this.service.closeSession(oldSessionId);
 				} catch (InvalidSessionException e) {
 				}
 	        }
-			return new LogonResult(sessionInfo.getSessionToken(), sessionInfo.getVDBName(), sessionInfo.getVDBVersion(), clusterName);
+			LogonResult result = new LogonResult(sessionInfo.getSessionToken(), sessionInfo.getVDBName(), sessionInfo.getVDBVersion(), clusterName);
+			if (krb5ServiceTicket != null) {
+				result.addProperty(ILogon.KRB5TOKEN, krb5ServiceTicket);
+			}
+			return result;
 		} catch (LoginException e) {
 			throw new LogonException(e.getMessage());
 		} catch (SessionServiceException e) {
 			throw new LogonException(e, e.getMessage());
 		}
 	}
-
+	  
+	class GssAction implements PrivilegedAction<GSSResult> {
+		byte[] serviceTicket;
+		
+		public GssAction(byte[] ticket) {
+			this.serviceTicket = ticket;
+		}
+		
+		@Override
+		public GSSResult run() {
+			GSSContext context = null;
+			try {
+				GSSManager manager = GSSManager.getInstance();
+				context = manager.createContext((GSSCredential)null);				
+				this.serviceTicket = context.acceptSecContext(this.serviceTicket, 0, this.serviceTicket.length);				
+				return new GSSResult(context, serviceTicket);
+			} catch (GSSException e) {
+				LogManager.logError(LogConstants.CTX_SECURITY, e, "Kerberos context login failed"); //$NON-NLS-1$
+			}
+			return null;
+		}	
+	}
+	
+	class GSSResult {
+		GSSContext context;
+		byte[] serviceTicket;
+		public GSSResult(GSSContext context, byte[] serviceTicket) {
+			this.context = context;
+			this.serviceTicket = serviceTicket;
+		}
+	}
+	
+	@Override
+	public LogonResult neogitiateGssLogin(Properties connProps, byte[] serviceTicket, boolean createSession) throws LogonException {
+		
+		if (!AuthenticationType.KRB5.equals(service.getAuthType())) {
+			throw new LogonException(RuntimePlugin.Util.getString("wrong_logon_type_krb5")); //$NON-NLS-1$
+		}		
+		
+        String user = connProps.getProperty(TeiidURL.CONNECTION.USER_NAME);
+        String password = connProps.getProperty(TeiidURL.CONNECTION.PASSWORD);		
+		
+		try {
+			String securityDomain = service.getKrb5SecurityDomain();
+			if (securityDomain == null) {
+				throw new LogonException(RuntimePlugin.Util.getString("no_security_domains")); //$NON-NLS-1$
+			}
+			// If this KRB5 and using keytab, user and password callback handler never gets called 
+			LoginContext ctx = service.createLoginContext(securityDomain, user, password);
+			ctx.login();
+			Subject subject = ctx.getSubject();
+			GSSResult result =  Subject.doAs(subject, new GssAction(serviceTicket));
+			if (result == null) {
+				throw new LogonException(RuntimePlugin.Util.getString("krb5_login_failed")); //$NON-NLS-1$
+			}
+			if (!result.context.isEstablished() || !createSession) {
+				LogonResult logonResult = new LogonResult(new SessionToken(0, "temp"), "internal", 0, "internal"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+				logonResult.addProperty(ILogon.KRB5TOKEN, result.serviceTicket);
+				logonResult.addProperty(ILogon.KRB5_ESTABLISHED, new Boolean(result.context.isEstablished()));
+				return logonResult;
+			}		
+			
+			LogManager.logDetail(LogConstants.CTX_SECURITY, "Kerberos context established"); //$NON-NLS-1$
+			//connProps.setProperty(TeiidURL.CONNECTION.PASSTHROUGH_AUTHENTICATION, "true"); //$NON-NLS-1$
+			service.assosiateSubjectInContext(securityDomain, subject);
+			return logon(connProps, result.serviceTicket);
+		} catch (LoginException e) {
+			throw new LogonException(e, RuntimePlugin.Util.getString("krb5_login_failed")); //$NON-NLS-1$
+		} 
+	}
+	
 	private String updateDQPContext(SessionMetadata s) {
 		String sessionID = s.getSessionId();
 		

Modified: branches/as7/runtime/src/main/java/org/teiid/transport/ODBCClientInstance.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/transport/ODBCClientInstance.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/transport/ODBCClientInstance.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,12 +28,14 @@
 import java.util.Arrays;
 import java.util.concurrent.ConcurrentLinkedQueue;
 
+import org.teiid.client.security.ILogon;
 import org.teiid.core.util.ReflectionHelper;
 import org.teiid.jdbc.TeiidDriver;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.logging.MessageLevel;
 import org.teiid.net.CommunicationException;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
 import org.teiid.net.socket.ObjectChannel;
 import org.teiid.net.socket.ServiceInvocationStruct;
 import org.teiid.odbc.ODBCClientRemote;
@@ -48,7 +50,7 @@
 	private ReflectionHelper serverProxy = new ReflectionHelper(ODBCServerRemote.class);
 	private ConcurrentLinkedQueue<PGRequest> messageQueue = new ConcurrentLinkedQueue<PGRequest>();
 	
-	public ODBCClientInstance(final ObjectChannel channel, ODBCServerRemote.AuthenticationType authType, TeiidDriver driver) {
+	public ODBCClientInstance(final ObjectChannel channel, AuthenticationType authType, TeiidDriver driver, ILogon logonService) {
 		this.client = (ODBCClientRemote)Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {ODBCClientRemote.class}, new InvocationHandler() {
 			@Override
 			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
@@ -60,7 +62,7 @@
 				return null;
 			}
 		});
-		this.server = new ODBCServerRemoteImpl(this, authType, driver) {
+		this.server = new ODBCServerRemoteImpl(this, authType, driver, logonService) {
 			@Override
 			protected synchronized void doneExecuting() {
 				super.doneExecuting();

Modified: branches/as7/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/transport/ODBCSocketListener.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -23,25 +23,24 @@
 
 import java.util.Properties;
 
-import javax.net.ssl.SSLEngine;
-
 import org.jboss.netty.channel.ChannelPipeline;
 import org.jboss.netty.channel.DefaultChannelPipeline;
-import org.jboss.netty.handler.ssl.SslHandler;
+import org.teiid.client.security.ILogon;
 import org.teiid.common.buffer.StorageManager;
 import org.teiid.core.TeiidException;
 import org.teiid.jdbc.EmbeddedProfile;
 import org.teiid.jdbc.TeiidDriver;
 import org.teiid.net.ServerConnection;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
 import org.teiid.net.socket.ObjectChannel;
-import org.teiid.odbc.ODBCServerRemote;
 
 public class ODBCSocketListener extends SocketListener {
-	private ODBCServerRemote.AuthenticationType authType = ODBCServerRemote.AuthenticationType.CLEARTEXT;
+	private AuthenticationType authType = AuthenticationType.CLEARTEXT;
 	private int maxLobSize;
 	private TeiidDriver driver;
+	private ILogon logonService;
 	
-	public ODBCSocketListener(SocketConfiguration config, StorageManager storageManager, int portOffset, int maxLobSize) {
+	public ODBCSocketListener(SocketConfiguration config, StorageManager storageManager, int portOffset, int maxLobSize, ILogon logon) {
 		//the clientserviceregistry isn't actually used by ODBC 
 		super(config, new ClientServiceRegistryImpl(ClientServiceRegistry.Type.ODBC), storageManager, portOffset);
 		this.maxLobSize = maxLobSize;
@@ -54,6 +53,7 @@
 				return new LocalServerConnection(info, false);
 			}
 		});
+		this.logonService = logon;
 	}
 	
 	public void setDriver(TeiidDriver driver) {
@@ -66,12 +66,8 @@
 			public ChannelPipeline getPipeline() throws Exception {
 				ChannelPipeline pipeline = new DefaultChannelPipeline();
 
-				SSLEngine engine = config.getServerSSLEngine();
-			    if (engine != null) {
-			        pipeline.addLast("ssl", new SslHandler(engine)); //$NON-NLS-1$
-			    }
 			    pipeline.addLast("odbcFrontendProtocol", new PgFrontendProtocol(1 << 20)); //$NON-NLS-1$
-			    pipeline.addLast("odbcBackendProtocol", new PgBackendProtocol(maxLobSize)); //$NON-NLS-1$
+			    pipeline.addLast("odbcBackendProtocol", new PgBackendProtocol(maxLobSize, config)); //$NON-NLS-1$
 			    pipeline.addLast("handler", this); //$NON-NLS-1$
 			    return pipeline;
 			}			
@@ -80,11 +76,11 @@
 	
 	@Override
 	public ChannelListener createChannelListener(ObjectChannel channel) {
-		return new ODBCClientInstance(channel, this.authType, driver);
+		return new ODBCClientInstance(channel, this.authType, driver, logonService);
 	}
 
-	public void setAuthenticationType(String value) {
-		this.authType = ODBCServerRemote.AuthenticationType.valueOf(value);
+	public void setAuthenticationType(AuthenticationType value) {
+		this.authType = value;
 	}
 
 }

Modified: branches/as7/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/transport/PgBackendProtocol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,6 +21,26 @@
  * 02110-1301 USA.
  */package org.teiid.transport;
 
+import static org.teiid.odbc.PGUtil.PG_TYPE_BOOL;
+import static org.teiid.odbc.PGUtil.PG_TYPE_BPCHAR;
+import static org.teiid.odbc.PGUtil.PG_TYPE_BYTEA;
+import static org.teiid.odbc.PGUtil.PG_TYPE_CHARARRAY;
+import static org.teiid.odbc.PGUtil.PG_TYPE_DATE;
+import static org.teiid.odbc.PGUtil.PG_TYPE_FLOAT4;
+import static org.teiid.odbc.PGUtil.PG_TYPE_FLOAT8;
+import static org.teiid.odbc.PGUtil.PG_TYPE_INT2;
+import static org.teiid.odbc.PGUtil.PG_TYPE_INT4;
+import static org.teiid.odbc.PGUtil.PG_TYPE_INT8;
+import static org.teiid.odbc.PGUtil.PG_TYPE_NUMERIC;
+import static org.teiid.odbc.PGUtil.PG_TYPE_OIDARRAY;
+import static org.teiid.odbc.PGUtil.PG_TYPE_OIDVECTOR;
+import static org.teiid.odbc.PGUtil.PG_TYPE_TEXT;
+import static org.teiid.odbc.PGUtil.PG_TYPE_TEXTARRAY;
+import static org.teiid.odbc.PGUtil.PG_TYPE_TIME;
+import static org.teiid.odbc.PGUtil.PG_TYPE_TIMESTAMP_NO_TMZONE;
+import static org.teiid.odbc.PGUtil.PG_TYPE_UNKNOWN;
+import static org.teiid.odbc.PGUtil.PG_TYPE_VARCHAR;
+
 import java.io.ByteArrayOutputStream;
 import java.io.DataOutputStream;
 import java.io.IOException;
@@ -28,39 +48,41 @@
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.nio.charset.Charset;
+import java.security.GeneralSecurityException;
 import java.sql.Blob;
 import java.sql.Clob;
 import java.sql.ParameterMetaData;
-import java.sql.PreparedStatement;
 import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
 import java.sql.SQLException;
-import java.sql.Statement;
 import java.sql.Types;
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
 
+import javax.net.ssl.SSLEngine;
+
 import org.jboss.netty.buffer.ChannelBuffer;
 import org.jboss.netty.buffer.ChannelBuffers;
 import org.jboss.netty.channel.ChannelDownstreamHandler;
 import org.jboss.netty.channel.ChannelEvent;
+import org.jboss.netty.channel.ChannelFuture;
+import org.jboss.netty.channel.ChannelFutureListener;
 import org.jboss.netty.channel.ChannelHandlerContext;
 import org.jboss.netty.channel.Channels;
 import org.jboss.netty.channel.MessageEvent;
+import org.jboss.netty.handler.ssl.SslHandler;
 import org.teiid.client.util.ResultsFuture;
 import org.teiid.core.util.ObjectConverterUtil;
 import org.teiid.core.util.ReaderInputStream;
 import org.teiid.core.util.ReflectionHelper;
-import org.teiid.deployers.PgCatalogMetadataStore;
 import org.teiid.jdbc.ResultSetImpl;
 import org.teiid.jdbc.TeiidSQLException;
 import org.teiid.logging.LogConstants;
 import org.teiid.logging.LogManager;
 import org.teiid.net.socket.ServiceInvocationStruct;
 import org.teiid.odbc.ODBCClientRemote;
+import org.teiid.odbc.PGUtil.PgColInfo;
+import org.teiid.runtime.RuntimePlugin;
 import org.teiid.transport.pg.PGbytea;
-
 /**
  * Represents the messages going from Server --> PG ODBC Client  
  * Some parts of this code is taken from H2's implementation of ODBC
@@ -68,18 +90,41 @@
 @SuppressWarnings("nls")
 public class PgBackendProtocol implements ChannelDownstreamHandler, ODBCClientRemote {
 	
-    private final class ResultsWorkItem implements Runnable {
+    private final class SSLEnabler implements ChannelFutureListener {
+    	
+    	private SSLEngine engine;
+    	
+		public SSLEnabler(SSLEngine engine) {
+			this.engine = engine;
+		}
+
+		@Override
+		public void operationComplete(ChannelFuture future) throws Exception {
+			if (future.isSuccess()) {
+				SslHandler handler = new SslHandler(engine);
+				future.getChannel().getPipeline().addFirst("sslHandler", handler);
+				handler.handshake();
+			}
+		}
+	}
+	
+    // 300k
+	static int ODBC_SOCKET_BUFF_SIZE = Integer.parseInt(System.getProperty("ODBCPacketSize", "307200"));
+	
+	private final class ResultsWorkItem implements Runnable {
 		private final List<PgColInfo> cols;
-		private final String sql;
 		private final ResultSetImpl rs;
-		private final ResultsFuture<Void> result;
+		private final ResultsFuture<Integer> result;
+		private int rows2Send;
+		private int rowsSent = 0;
+		private int rowsInBuffer = 0;
+		private ChannelBuffer buffer = ChannelBuffers.directBuffer(ODBC_SOCKET_BUFF_SIZE);
 
-		private ResultsWorkItem(List<PgColInfo> cols, String sql,
-				ResultSetImpl rs, ResultsFuture<Void> result) {
+		private ResultsWorkItem(List<PgColInfo> cols, ResultSetImpl rs, ResultsFuture<Integer> result, int rows2Send) {
 			this.cols = cols;
-			this.sql = sql;
 			this.rs = rs;
 			this.result = result;
+			this.rows2Send = rows2Send;
 		}
 
 		@Override
@@ -92,8 +137,10 @@
 				    		@Override
 				    		public void onCompletion(ResultsFuture<Boolean> future) {
 				    			if (processRow(future)) {
-				    				//this can be recursive, but ideally won't be called many times 
-				    				ResultsWorkItem.this.run();
+				    				if (rowsSent != rows2Send) {
+				    					//this can be recursive, but ideally won't be called many times 
+				    					ResultsWorkItem.this.run();
+				    				}
 				    			}
 				    		}
 						});
@@ -113,10 +160,18 @@
 			boolean processNext = true;
 			try {
     			if (future.get()) {
-    				sendDataRow(rs, cols);
+    				sendDataRow(rs, cols, buffer);
+    				rowsSent++;
+    				rowsInBuffer++;
+    				boolean done = rowsSent == rows2Send;
+    				flushResults(done);
+    				processNext = !done;
+    				if (done) {
+    					result.getResultsReceiver().receiveResults(rowsSent);
+    				}
     			} else {
-    				sendCommandComplete(sql, 0);
-    				result.getResultsReceiver().receiveResults(null);
+    				sendContents(buffer);
+    				result.getResultsReceiver().receiveResults(rowsSent);
     				processNext = false;
     			}
 			} catch (Throwable t) {
@@ -125,33 +180,17 @@
 			}
 			return processNext;
 		}
+		
+		private void flushResults(boolean force) {
+			int avgRowsize = buffer.readableBytes()/rowsInBuffer;
+			if (force || buffer.writableBytes() < (avgRowsize*2)) {
+				sendContents(buffer);
+				buffer= ChannelBuffers.directBuffer(ODBC_SOCKET_BUFF_SIZE);
+				rowsInBuffer = 0;
+			}			
+		}
 	}
-
-	private static final int PG_TYPE_VARCHAR = 1043;
-
-    private static final int PG_TYPE_BOOL = 16;
-    private static final int PG_TYPE_BYTEA = 17;
-    private static final int PG_TYPE_BPCHAR = 1042;
-    private static final int PG_TYPE_INT8 = 20;
-    private static final int PG_TYPE_INT2 = 21;
-    private static final int PG_TYPE_INT4 = 23;
-    private static final int PG_TYPE_TEXT = 25;
-    //private static final int PG_TYPE_OID = 26;
-    private static final int PG_TYPE_FLOAT4 = 700;
-    private static final int PG_TYPE_FLOAT8 = 701;
-    private static final int PG_TYPE_UNKNOWN = 705;
     
-    private static final int PG_TYPE_OIDVECTOR = PgCatalogMetadataStore.PG_TYPE_OIDVECTOR;
-    private static final int PG_TYPE_OIDARRAY = PgCatalogMetadataStore.PG_TYPE_OIDARRAY;
-    private static final int PG_TYPE_CHARARRAY = PgCatalogMetadataStore.PG_TYPE_CHARARRAY;
-    private static final int PG_TYPE_TEXTARRAY = PgCatalogMetadataStore.PG_TYPE_TEXTARRAY;
-    
-    private static final int PG_TYPE_DATE = 1082;
-    private static final int PG_TYPE_TIME = 1083;
-    private static final int PG_TYPE_TIMESTAMP_NO_TMZONE = 1114;
-    private static final int PG_TYPE_NUMERIC = 1700;
-    //private static final int PG_TYPE_LO = 14939;
-    
     private DataOutputStream dataOut;
     private ByteArrayOutputStream outBuffer;
     private char messageType;
@@ -164,8 +203,11 @@
     
 	private volatile ResultsFuture<Boolean> nextFuture;
 
-    public PgBackendProtocol(int maxLobSize) {
+	private SSLConfiguration config;
+
+	public PgBackendProtocol(int maxLobSize, SSLConfiguration config) {
     	this.maxLobSize = maxLobSize;
+    	this.config = config;
     }
     
 	@Override
@@ -212,6 +254,24 @@
 	}
 	
 	@Override
+	public void useAuthenticationGSS() {
+		try {
+			sendAuthenticationGSS();
+		} catch (IOException e) {
+			terminate(e);
+		}		
+	}
+	
+	@Override
+	public void authenticationGSSContinue(byte[] serviceToken) {
+		try {
+			sendAuthenticationGSSContinue(serviceToken);
+		} catch (IOException e) {
+			terminate(e);
+		}		
+	}
+	
+	@Override
 	public void authenticationSucess(int processId, int screctKey) {
 		try {
 			sendAuthenticationOk();
@@ -312,35 +372,65 @@
 	}
 
 	@Override
-	public void sendResultSetDescription(ResultSetMetaData metaData, Statement stmt) {
+	public void sendResultSetDescription(List<PgColInfo> cols) {
 		try {
+			sendRowDescription(cols);
+		} catch (IOException e) {
+			terminate(e);
+		}
+	}
+	
+	@Override
+	public void sendCursorResults(ResultSetImpl rs, List<PgColInfo> cols, ResultsFuture<Integer> result, int rowCount) {
+		try {
+        	sendRowDescription(cols);
+
+        	ResultsWorkItem r = new ResultsWorkItem(cols, rs, result, rowCount);
+        	r.run();  	        					
+		} catch (IOException e) {
+			terminate(e);
+		}
+	}
+	
+	@Override
+	public void sendPortalResults(String sql, ResultSetImpl rs, List<PgColInfo> cols, ResultsFuture<Integer> result, int rowCount, boolean portal) {
+    	ResultsWorkItem r = new ResultsWorkItem(cols, rs, result, rowCount);
+    	r.run();	        	
+	}
+	
+	@Override
+	public void sendMoveCursor(ResultSetImpl rs, int rowCount, ResultsFuture<Integer> results) {
+		try {
 			try {
-        		List<PgColInfo> cols = getPgColInfo(metaData, stmt);
-				sendRowDescription(cols);
+				int rowsMoved = 0;
+				for (int i = 0; i < rowCount; i++) {
+					if (!rs.next()) {
+						break;
+					}
+					rowsMoved++;
+				}				
+				results.getResultsReceiver().receiveResults(rowsMoved);
 			} catch (SQLException e) {
-				sendErrorResponse(e);				
-			}			
+				sendErrorResponse(e);
+			}
 		} catch (IOException e) {
 			terminate(e);
 		}
-	}
+	}		
 	
 	@Override
-	public void sendResults(final String sql, final ResultSetImpl rs, ResultsFuture<Void> result, boolean describeRows) {
+	public void sendResults(final String sql, final ResultSetImpl rs, List<PgColInfo> cols, ResultsFuture<Integer> result, boolean describeRows) {
 		try {
 			if (nextFuture != null) {
 				sendErrorResponse(new IllegalStateException("Pending results have not been sent")); //$NON-NLS-1$
 			}
         	
-			ResultSetMetaData meta = rs.getMetaData();
-    		List<PgColInfo> cols = getPgColInfo(meta, rs.getStatement());
         	if (describeRows) {
         		sendRowDescription(cols);
         	}
-        	Runnable r = new ResultsWorkItem(cols, sql, rs, result);
+        	ResultsWorkItem r = new ResultsWorkItem(cols, rs, result, -1);
         	r.run();    
-		} catch (SQLException e) {
-			result.getResultsReceiver().exceptionOccurred(e);
+        	sendCommandComplete(sql, 0);
 		} catch (IOException e) {
 			terminate(e);
 		}
@@ -397,8 +487,9 @@
 		startMessage('I');
 		sendMessage();
 	}
-		
-	private void sendCommandComplete(String sql, int updateCount) throws IOException {
+
+	@Override
+	public void sendCommandComplete(String sql, int updateCount) throws IOException {
 		startMessage('C');
 		sql = sql.trim().toUpperCase();
 		// TODO remove remarks at the beginning
@@ -411,7 +502,7 @@
 			tag = "UPDATE " + updateCount;
 		} else if (sql.startsWith("SELECT") || sql.startsWith("CALL")) {
 			tag = "SELECT";
-		} else if (sql.startsWith("BEGIN")) {
+		} else if (sql.startsWith("BEGIN") || sql.startsWith("START TRANSACTION")) {
 			tag = "BEGIN";
 		} else if (sql.startsWith("COMMIT")) {
 			tag = "COMMIT";
@@ -419,15 +510,23 @@
 			tag = "ROLLBACK";
 		} else if (sql.startsWith("SET ")) {
 			tag = "SET";
-		}else {
-			trace("Check command tag:", sql);
-			tag = "UPDATE " + updateCount;
+		}  else if (sql.startsWith("DECLARE CURSOR")) {
+			tag = "DECLARE CURSOR";
+		} else if (sql.startsWith("CLOSE CURSOR")) {
+			tag = "CLOSE CURSOR";
+		} else if (sql.startsWith("FETCH")) {
+			tag = "FETCH "+ updateCount;
+		}  else if (sql.startsWith("MOVE")) {
+			tag = "MOVE "+ updateCount;
 		}
+		else {
+			tag = sql;
+		}
 		writeString(tag);
 		sendMessage();
 	}
 
-	private void sendDataRow(ResultSet rs, List<PgColInfo> cols) throws SQLException, IOException {
+	private void sendDataRow(ResultSet rs, List<PgColInfo> cols, ChannelBuffer buffer) throws SQLException, IOException {
 		startMessage('D');
 		writeShort(cols.size());
 		for (int i = 0; i < cols.size(); i++) {
@@ -439,9 +538,18 @@
 				write(bytes);
 			}
 		}
-		sendMessage();
+		
+		byte[] buff = outBuffer.toByteArray();
+		int len = buff.length;
+		this.outBuffer = null;
+		this.dataOut = null;
+		
+		// now build the wire contents.
+		buffer.writeByte((byte)this.messageType);
+		buffer.writeInt(len+4);
+		buffer.writeBytes(buff);
 	}
-
+	
 	private byte[] getContent(ResultSet rs, PgColInfo col, int column) throws SQLException, TeiidSQLException, IOException {
 		byte[] bytes = null;
 		switch (col.type) {
@@ -550,10 +658,23 @@
 	}	
 	
 	@Override
-	public void sslDenied() {
+	public void sendSslResponse() {
+		SSLEngine engine = null;
+		try {
+			engine = config.getServerSSLEngine();
+		} catch (IOException e) {
+			LogManager.logError(LogConstants.CTX_ODBC, e, RuntimePlugin.Util.getString("PgBackendProtocol.ssl_error"));
+		} catch (GeneralSecurityException e) {
+			LogManager.logError(LogConstants.CTX_ODBC, e, RuntimePlugin.Util.getString("PgBackendProtocol.ssl_error"));
+		}
 		ChannelBuffer buffer = ChannelBuffers.directBuffer(1);
-		buffer.writeByte('N');
-		Channels.write(this.ctx, this.message.getFuture(), buffer, this.message.getRemoteAddress());		
+		if (engine == null) {
+			buffer.writeByte('N');
+		} else {
+			this.message.getFuture().addListener(new SSLEnabler(engine));
+			buffer.writeByte('S');
+		}
+		Channels.write(this.ctx, this.message.getFuture(), buffer, this.message.getRemoteAddress());
 	}
 	
 	private void sendErrorResponse(Throwable t) throws IOException {
@@ -571,20 +692,7 @@
 		write(0);
 		sendMessage();
 	}
-
-	private void sendNoData() {
-		startMessage('n');
-		sendMessage();
-	}
 	
-	private static class PgColInfo {
-		String name;
-		int reloid;
-		short attnum;
-		int type;
-		int precision;
-	}
-
 	private void sendRowDescription(List<PgColInfo> cols) throws IOException {
 		startMessage('T');
 		writeShort(cols.size());
@@ -606,46 +714,6 @@
 		sendMessage();
 	}
 
-	private List<PgColInfo> getPgColInfo(ResultSetMetaData meta, Statement stmt)
-			throws SQLException {
-		int columns = meta.getColumnCount();
-		ArrayList<PgColInfo> result = new ArrayList<PgColInfo>(columns);
-		for (int i = 1; i < columns + 1; i++) {
-	 		PgColInfo info = new PgColInfo();
-			info.name = meta.getColumnName(i).toLowerCase();
-			info.type = meta.getColumnType(i);
-			info.type = convertType(info.type);
-			info.precision = meta.getColumnDisplaySize(i);
-			String name = meta.getColumnName(i);
-			String table = meta.getTableName(i);
-			String schema = meta.getSchemaName(i);
-			if (schema != null) {
-				PreparedStatement ps = null;
-				try {
-					ps = stmt.getConnection().prepareStatement("select attrelid, attnum, typoid from matpg_relatt where attname = ? and relname = ? and nspname = ?");
-					ps.setString(1, name);
-					ps.setString(2, table);
-					ps.setString(3, schema);
-					ResultSet rs = ps.executeQuery();
-					if (rs.next()) {
-						info.reloid = rs.getInt(1);
-						info.attnum = rs.getShort(2);
-						int specificType = rs.getInt(3);
-						if (!rs.wasNull()) {
-							info.type = specificType;
-						}
-					}
-				} finally {
-					if (ps != null) {
-						ps.close();
-					}
-				}
-			}
-			result.add(info);
-		}
-		return result;
-	}
-
 	private int getTypeSize(int pgType, int precision) {
 		switch (pgType) {
 		case PG_TYPE_VARCHAR:
@@ -687,13 +755,32 @@
 		startMessage('2');
 		sendMessage();
 	}
+	
+	@Override
+	public void sendPortalSuspended() {
+		startMessage('s');
+		sendMessage();
+	}	
 
 	private void sendAuthenticationCleartextPassword() throws IOException {
 		startMessage('R');
 		writeInt(3);
 		sendMessage();
 	}
-
+	
+	private void sendAuthenticationGSS()  throws IOException {
+		startMessage('R');
+		writeInt(7);
+		sendMessage();
+	}
+	
+	private void sendAuthenticationGSSContinue(byte[] serviceToken) throws IOException  {
+		startMessage('R');
+		writeInt(8);
+		write(serviceToken);
+		sendMessage();
+	}	
+	
 	private void sendAuthenticationOk() throws IOException {
 		startMessage('R');
 		writeInt(0);
@@ -803,6 +890,10 @@
 		buffer.writeBytes(buff);
 		Channels.write(this.ctx, this.message.getFuture(), buffer, this.message.getRemoteAddress());
 	}
+	
+	private void sendContents(ChannelBuffer buffer) {
+		Channels.write(this.ctx, this.message.getFuture(), buffer, this.message.getRemoteAddress());
+	}
 
 	private static void trace(String... msg) {
 		LogManager.logTrace(LogConstants.CTX_ODBC, (Object[])msg);
@@ -858,6 +949,5 @@
         default:
             return PG_TYPE_UNKNOWN;
         }
-    }
-	
+    }	
 }

Modified: branches/as7/runtime/src/main/java/org/teiid/transport/PgFrontendProtocol.java
===================================================================
--- branches/as7/runtime/src/main/java/org/teiid/transport/PgFrontendProtocol.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/java/org/teiid/transport/PgFrontendProtocol.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -131,7 +131,7 @@
 
         byte[] data = createByteArray(this.dataLength - 4);
         buffer.readBytes(data);
-		createRequestMessage(this.messageType, new NullTerminatedStringDataInputStream(new DataInputStream(new ByteArrayInputStream(data, 0, this.dataLength-4)), this.encoding));
+		createRequestMessage(this.messageType, new NullTerminatedStringDataInputStream(data, new DataInputStream(new ByteArrayInputStream(data, 0, this.dataLength-4)), this.encoding));
 		this.dataLength = null;
 		this.messageType = null;
 		return message;
@@ -223,8 +223,7 @@
 	}
 	
 	private Object buildLogin(NullTerminatedStringDataInputStream data) throws IOException{
-        String password = data.readString();
-        this.odbcProxy.logon(this.databaseName, this.user, password);
+        this.odbcProxy.logon(this.databaseName, this.user, data);
         return message;
 	}	
 
@@ -403,12 +402,14 @@
 		ServiceInvocationStruct struct;
 	}
 	
-	static class NullTerminatedStringDataInputStream extends DataInputStream{
+	public static class NullTerminatedStringDataInputStream extends DataInputStream{
 		private Charset encoding;
+		private byte[] rawData;
 		
-		public NullTerminatedStringDataInputStream(DataInputStream in, Charset encoding) {
+		public NullTerminatedStringDataInputStream(byte[] rawData, DataInputStream in, Charset encoding) {
 			super(in);
 			this.encoding = encoding;
+			this.rawData = rawData;
 		}
 
 	    public String readString() throws IOException {
@@ -422,6 +423,10 @@
 	        }
 	        return new String(buff.toByteArray(), this.encoding);
 	    }
+	    
+	    public byte[] readServiceToken() {
+	    	return this.rawData;
+	    }
 	}
 	
 	private static void trace(Object... msg) {


Property changes on: branches/as7/runtime/src/main/java/org/teiid/transport/SSLAwareChannelHandler.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/runtime/src/main/java/org/teiid/transport/SSLConfiguration.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/runtime/src/main/resources/org/teiid/runtime/i18n.properties
===================================================================
--- branches/as7/runtime/src/main/resources/org/teiid/runtime/i18n.properties	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/main/resources/org/teiid/runtime/i18n.properties	2011-08-18 16:17:24 UTC (rev 3394)
@@ -91,4 +91,11 @@
 metadata_loaded=VDB {0}.{1} model {2} metadata is currently being loaded.
 ambigious_name=Ambiguous VDB name specified. Only single occurrence of the "." is allowed in the VDB name. Also, when version based vdb name is specified, then a separate "version" connection option is not allowed:{0}.{1} 
 lo_not_supported=LO functions are not supported
-SSLConfiguration.no_anonymous=The anonymous cipher suite TLS_DH_anon_WITH_AES_128_CBC_SHA is not available.  Please change the transport to be non-SSL or use non-anonymous SSL.
\ No newline at end of file
+SSLConfiguration.no_anonymous=The anonymous cipher suite TLS_DH_anon_WITH_AES_128_CBC_SHA is not available.  Please change the transport to be non-SSL or use non-anonymous SSL.
+execution_failed=Cursor execution failed
+
+PgBackendProtocol.ssl_error=Could not initialize ODBC SSL.  non-SSL connections will still be allowed.
+wrong_logon_type_jaas = Wrong logon method is being used. Server is not set up for JAAS based authentication. Correct your client's 'AuthenticationType' property.
+wrong_logon_type_krb5 = Wrong logon method is being used. Server is not set up for Kerberos based authentication. Correct your client's 'AuthenticationType' property.
+krb5_login_failed=Kerberos context login failed
+no_security_domains=No security domain configured for Kerberos authentication. Can not authenticate.
\ No newline at end of file

Modified: branches/as7/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java
===================================================================
--- branches/as7/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/test/java/org/teiid/deployers/TestCompositeVDB.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -21,6 +21,8 @@
  */
 package org.teiid.deployers;
 
+import static org.junit.Assert.*;
+
 import java.util.ArrayList;
 import java.util.List;
 
@@ -38,19 +40,26 @@
 import org.teiid.query.parser.QueryParser;
 import org.teiid.query.resolver.QueryResolver;
 import org.teiid.query.sql.lang.Command;
-import org.teiid.query.unittest.FakeMetadataFactory;
 import org.teiid.query.unittest.RealMetadataFactory;
 import org.teiid.translator.ExecutionFactory;
+import org.teiid.vdb.runtime.VDBKey;
 
 @SuppressWarnings("nls")
 public class TestCompositeVDB {
 	
 	public static TransformationMetadata createTransformationMetadata(MetadataStore metadataStore, String vdbName) throws Exception {
-    	VDBMetaData vdbMetaData = new VDBMetaData();
+    	CompositeVDB cvdb = createCompositeVDB(metadataStore, vdbName);
+    	VDBMetaData vdb = cvdb.getVDB();
+    	return vdb.getAttachment(TransformationMetadata.class);
+	}
+
+	private static CompositeVDB createCompositeVDB(MetadataStore metadataStore,
+			String vdbName) {
+		VDBMetaData vdbMetaData = new VDBMetaData();
     	vdbMetaData.setName(vdbName); //$NON-NLS-1$
     	vdbMetaData.setVersion(1);
     	for (Schema schema : metadataStore.getSchemas().values()) {
-			vdbMetaData.addModel(FakeMetadataFactory.createModel(schema.getName(), schema.isPhysical()));
+			vdbMetaData.addModel(RealMetadataFactory.createModel(schema.getName(), schema.isPhysical()));
 		}
     	MetadataStoreGroup metaGroup = new MetadataStoreGroup();
     	metaGroup.addStore(metadataStore);
@@ -59,9 +68,8 @@
     	cmr.addConnectorManager("source", getConnectorManager("bqt1", "FakeTranslator", "FakeConnection", getFuncsOne()));
     	cmr.addConnectorManager("source2", getConnectorManager("bqt2", "FakeTranslator2", "FakeConnection2", getFuncsTwo()));
     	
-    	CompositeVDB cvdb = new CompositeVDB(vdbMetaData, metaGroup, null, null, FakeMetadataFactory.SFM.getSystemFunctions(),cmr);
-    	VDBMetaData vdb = cvdb.getVDB();
-    	return vdb.getAttachment(TransformationMetadata.class);
+    	CompositeVDB cvdb = new CompositeVDB(vdbMetaData, metaGroup, null, null, RealMetadataFactory.SFM.getSystemFunctions(),cmr);
+		return cvdb;
 	}
 	
 	private static ConnectorManager getConnectorManager(String modelName, String translatorName, String connectionName,  List<FunctionMethod> funcs) {
@@ -104,7 +112,7 @@
 	
 	
 	private void helpResolve(String sql) throws Exception {
-		TransformationMetadata metadata = createTransformationMetadata(RealMetadataFactory.exampleBQTStore(), "bqt");
+		TransformationMetadata metadata = createTransformationMetadata(RealMetadataFactory.exampleBQTCached().getMetadataStore(), "bqt");
 		Command command = QueryParser.getQueryParser().parseCommand(sql);
 		QueryResolver.resolveCommand(command, metadata);		
 	}
@@ -139,4 +147,10 @@
 		helpResolve("SELECT duplicate_func(BQT1.SmallA.INTKEY) FROM BQT1.SmallA");
 	}		
 	
+	@Test public void testRemoveChild() throws Exception {
+		CompositeVDB vdb = createCompositeVDB(RealMetadataFactory.exampleBQTStore(), "bqt");
+		vdb.removeChild(new VDBKey("foo", 1));
+		assertNotNull(vdb.getVDB());
+	}
+	
 }

Modified: branches/as7/runtime/src/test/java/org/teiid/dqp/service/buffer/TestLocalBufferService.java
===================================================================
--- branches/as7/runtime/src/test/java/org/teiid/dqp/service/buffer/TestLocalBufferService.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/test/java/org/teiid/dqp/service/buffer/TestLocalBufferService.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -91,7 +91,7 @@
         svc.start();
         
         BufferManager mgr = svc.getBufferManager();
-        assertEquals(16261, mgr.getSchemaSize(schema));
+        assertEquals(13141, mgr.getSchemaSize(schema));
     }
     
 }

Modified: branches/as7/runtime/src/test/java/org/teiid/transport/TestLogonImpl.java
===================================================================
--- branches/as7/runtime/src/test/java/org/teiid/transport/TestLogonImpl.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/test/java/org/teiid/transport/TestLogonImpl.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -34,12 +34,14 @@
 import org.teiid.dqp.internal.process.DQPWorkContext;
 import org.teiid.dqp.service.SessionService;
 import org.teiid.net.TeiidURL;
+import org.teiid.net.TeiidURL.CONNECTION.AuthenticationType;
 
 
 public class TestLogonImpl extends TestCase {
 
 	public void testLogonResult() throws Exception {
 		SessionService ssi = Mockito.mock(SessionService.class);
+		Mockito.stub(ssi.getAuthType()).toReturn(AuthenticationType.CLEARTEXT);
 		DQPWorkContext.setWorkContext(new DQPWorkContext());
 		String userName = "Fred"; //$NON-NLS-1$
 		String applicationName = "test"; //$NON-NLS-1$

Modified: branches/as7/runtime/src/test/java/org/teiid/transport/TestSocketRemoting.java
===================================================================
--- branches/as7/runtime/src/test/java/org/teiid/transport/TestSocketRemoting.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/runtime/src/test/java/org/teiid/transport/TestSocketRemoting.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -193,6 +193,13 @@
 					TeiidComponentException {
 				}
 
+				@Override
+				public LogonResult neogitiateGssLogin(
+						Properties connectionProperties, byte[] serviceToken, boolean createSession)
+						throws LogonException {
+					return null;
+				}
+
 			}, "foo"); //$NON-NLS-1$
 		csr.registerClientService(FakeService.class, new FakeServiceImpl(), "foo"); //$NON-NLS-1$
 		final FakeClientServerInstance serverInstance = new FakeClientServerInstance(csr);


Property changes on: branches/as7/runtime/src/test/resources/dqp/config
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/runtime/src/test/resources/groups.properties
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/runtime/src/test/resources/permissions.xml
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/runtime/src/test/resources/permissions2.xml
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/runtime/src/test/resources/users.properties
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/test-integration/common/pom.xml
===================================================================
--- branches/as7/test-integration/common/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-test-integration</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>test-integration-common</artifactId>
@@ -15,6 +15,11 @@
 			<artifactId>postgresql</artifactId>
 			<version>8.3-606.jdbc3</version>
 		</dependency>
+		<dependency>
+  			<groupId>com.h2database</groupId>
+  			<artifactId>h2</artifactId>
+  			<version>1.2.147</version>
+		</dependency>
 	</dependencies>
      
 </project>
\ No newline at end of file


Property changes on: branches/as7/test-integration/common/src/test/java/org/teiid/connector/language
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/test-integration/common/src/test/java/org/teiid/connector/metadata/runtime/TestMetadataObject.java
___________________________________________________________________
Deleted: svn:mergeinfo
   - 


Property changes on: branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util
___________________________________________________________________
Deleted: svn:mergeinfo
   - 

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestCollectorVisitor.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestCollectorVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestCollectorVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,16 +22,16 @@
 
 package org.teiid.connector.visitor.util;
 
+import static org.junit.Assert.*;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
 
-import junit.framework.TestCase;
-
+import org.junit.Test;
 import org.teiid.language.ColumnReference;
 import org.teiid.language.Comparison;
 import org.teiid.language.Expression;
@@ -41,25 +41,14 @@
 import org.teiid.language.Select;
 import org.teiid.language.Comparison.Operator;
 import org.teiid.language.visitor.CollectorVisitor;
-
 /**
  */
-public class TestCollectorVisitor extends TestCase {
+public class TestCollectorVisitor {
 
-    /**
-     * Constructor for TestElementCollectorVisitor.
-     * @param name
-     */
-    public TestCollectorVisitor(String name) {
-        super(name);
-    }
-
-    public Set getStringSet(Collection objs) {
-        Set strings = new HashSet();
+    public Set<String> getStringSet(Collection<? extends Object> objs) {
+        Set<String> strings = new HashSet<String>();
         
-        Iterator iter = objs.iterator();
-        while(iter.hasNext()) {
-            Object obj = iter.next();
+        for (Object obj : objs) {
             if(obj == null) {
                 strings.add(null);
             } else {
@@ -90,38 +79,38 @@
         return q;   
     }
  
-    public void testCollection1() {
+    @Test public void testCollection1() {
         helpTestCollection(example1(), ColumnReference.class, new String[] {"g1.e1", "g1.e2" }); //$NON-NLS-1$ //$NON-NLS-2$
     }
 
-    public void testCollection2() {
+    @Test public void testCollection2() {
         helpTestCollection(example1(), Function.class, new String[] {"length(g1.e2)" }); //$NON-NLS-1$
     }
 
-    public void testCollection3() {
+    @Test public void testCollection3() {
         helpTestCollection(example1(), Expression.class, new String[] {"g1.e1", "g1.e2", "length(g1.e2)" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
     }
 
 
     public void helpTestElementsUsedByGroups(LanguageObject obj, String[] elements, String[] groups) {
-        Set actualElements = getStringSet(CollectorVisitor.collectElements(obj));
-        Set actualGroups = getStringSet(CollectorVisitor.collectGroupsUsedByElements(obj));
+        Set<String> actualElements = getStringSet(CollectorVisitor.collectElements(obj));
+        Set<String> actualGroups = getStringSet(CollectorVisitor.collectGroupsUsedByElements(obj));
         
-        Set expectedElements = new HashSet(Arrays.asList(elements));
-        Set expectedGroups = new HashSet(Arrays.asList(groups));
+        Set<String> expectedElements = new HashSet<String>(Arrays.asList(elements));
+        Set<String> expectedGroups = new HashSet<String>(Arrays.asList(groups));
         
         assertEquals("Did not get expected elements", expectedElements, actualElements); //$NON-NLS-1$
         assertEquals("Did not get expected groups", expectedGroups, actualGroups);         //$NON-NLS-1$
     }
     
-    public void test1() {
+    @Test public void test1() {
         NamedTable g1 = new NamedTable("g1", null, null); //$NON-NLS-1$
         ColumnReference e1 = new ColumnReference(g1, "e1", null, String.class); //$NON-NLS-1$
         
         helpTestElementsUsedByGroups(e1, new String[] {"g1.e1"}, new String[] {"g1"}); //$NON-NLS-1$ //$NON-NLS-2$
     }
     
-    public void test2() {
+    @Test public void test2() {
         NamedTable g1 = new NamedTable("g1", null, null); //$NON-NLS-1$
         ColumnReference e1 = new ColumnReference(g1, "e1", null, String.class); //$NON-NLS-1$
         ColumnReference e2 = new ColumnReference(g1, "e2", null, String.class); //$NON-NLS-1$

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestSQLStringVisitor.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestSQLStringVisitor.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/connector/visitor/util/TestSQLStringVisitor.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -73,7 +73,7 @@
 import org.teiid.query.sql.lang.CompareCriteria;
 import org.teiid.query.sql.lang.JoinType;
 
-
+ at SuppressWarnings("nls")
 public class TestSQLStringVisitor  {
 
     public static final RuntimeMetadata metadata = TstLanguageBridgeFactory.metadataFactory;
@@ -425,5 +425,19 @@
     	Command command = FakeTranslationFactory.getInstance().getBQTTranslationUtility().parseCommand(sql, true, true);
     	assertEquals("SELECT g_0.IntKey AS c_0 FROM SmallA AS g_0 ORDER BY c_0 NULLS FIRST", command.toString()); //$NON-NLS-1$
     }
+    
+    @Test public void testWindowFunction() throws Exception {
+    	String sql = "select max(intnum) over (order by intkey nulls first) from bqt1.smalla";
+    	
+    	Command command = FakeTranslationFactory.getInstance().getBQTTranslationUtility().parseCommand(sql, true, true);
+    	assertEquals("SELECT MAX(g_0.IntNum) OVER (ORDER BY g_0.IntKey NULLS FIRST) FROM SmallA AS g_0", command.toString()); //$NON-NLS-1$
+    }
+    
+    @Test public void testTrim() throws Exception {
+    	String sql = "select trim(both 'x' from stringkey) from bqt1.smalla";
+    	
+    	Command command = FakeTranslationFactory.getInstance().getBQTTranslationUtility().parseCommand(sql, true, true);
+    	assertEquals("SELECT trim('x' FROM g_0.StringKey) FROM SmallA AS g_0", command.toString()); //$NON-NLS-1$
+    }
 
 }

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestCrossSourceStarJoin.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -44,7 +44,7 @@
 @SuppressWarnings("nls")
 public class TestCrossSourceStarJoin {
 	
-    @Test public void testCrossSourceStartJoin() throws Exception {
+    @Test public void testCrossSourceStarJoin() throws Exception {
         String sql = "select p.Description, sum(AMOUNT) from s3 p, s2 c, s1 b, o1 f " +
         		"where p.PRODUCTID = f.PRODUCT and c.CurrencyCode = f.CURRENCY and b.BOOKID = f.BOOK and b.Name = 'xyz' and c.Name = 'abc' Group by p.Description";
         
@@ -106,7 +106,7 @@
         		"SELECT g_0.CurrencyCode AS c_0 FROM sybase.s2 AS g_0 WHERE g_0.Name = 'abc' ORDER BY c_0", 
         		"SELECT g_0.BOOKID AS c_0 FROM sybase.s1 AS g_0 WHERE g_0.Name = 'xyz' ORDER BY c_0", 
         		"SELECT g_0.PRODUCTID AS c_0, g_0.Description AS c_1 FROM sybase.s3 AS g_0 ORDER BY c_0", 
-        		"SELECT g_0.BOOK AS c_0, g_0.CURRENCY AS c_1, g_0.PRODUCT AS c_2, SUM(g_0.AMOUNT) AS c_3 FROM oracle.o1 AS g_0 WHERE (g_0.BOOK IN (<dependent values>)) AND (g_0.CURRENCY IN (<dependent values>)) AND (g_0.PRODUCT IN (<dependent values>)) GROUP BY g_0.BOOK, g_0.CURRENCY, g_0.PRODUCT ORDER BY c_0 NULLS FIRST"
+        		"SELECT g_0.BOOK, g_0.CURRENCY, g_0.PRODUCT, SUM(g_0.AMOUNT) FROM oracle.o1 AS g_0 WHERE (g_0.BOOK IN (<dependent values>)) AND (g_0.CURRENCY IN (<dependent values>)) AND (g_0.PRODUCT IN (<dependent values>)) GROUP BY g_0.BOOK, g_0.CURRENCY, g_0.PRODUCT"
         }, finder, ComparisonMode.EXACT_COMMAND_STRING);
         
         //test that aggregate will not be staged
@@ -115,7 +115,7 @@
         		"SELECT g_0.CurrencyCode AS c_0 FROM sybase.s2 AS g_0 WHERE g_0.Name = 'abc' ORDER BY c_0", 
         		"SELECT g_0.BOOKID AS c_0 FROM sybase.s1 AS g_0 WHERE g_0.Name = 'xyz' ORDER BY c_0", 
         		"SELECT g_0.PRODUCTID AS c_0, g_0.Description AS c_1 FROM sybase.s3 AS g_0 ORDER BY c_0", 
-        		"SELECT g_0.BOOK AS c_0, g_0.CURRENCY AS c_1, g_0.PRODUCT AS c_2, g_0.AMOUNT AS c_3 FROM oracle.o1 AS g_0 WHERE (g_0.BOOK IN (<dependent values>)) AND (g_0.CURRENCY IN (<dependent values>)) AND (g_0.PRODUCT IN (<dependent values>)) ORDER BY c_0 NULLS FIRST"
+        		"SELECT g_0.BOOK, g_0.CURRENCY, g_0.PRODUCT, g_0.AMOUNT FROM oracle.o1 AS g_0 WHERE (g_0.BOOK IN (<dependent values>)) AND (g_0.CURRENCY IN (<dependent values>)) AND (g_0.PRODUCT IN (<dependent values>))"
         }, finder, ComparisonMode.EXACT_COMMAND_STRING);
     } 
 

Copied: branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java (from rev 3382, trunk/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java)
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestRelate.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,413 @@
+/*
+ * 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 org.teiid.dqp.internal.process;
+
+import static org.junit.Assert.*;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.SQLXML;
+import java.sql.Statement;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import javax.sql.DataSource;
+
+import org.h2.jdbcx.JdbcConnectionPool;
+import org.h2.jdbcx.JdbcDataSource;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.dqp.internal.datamgr.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.jdbc.FakeServer;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.TranslatorException;
+import org.teiid.translator.jdbc.h2.H2ExecutionFactory;
+ at SuppressWarnings("nls")
+public class TestRelate {
+
+	private static boolean writeResults = false;
+	private static boolean DEBUG = false;
+	private static FakeServer server;
+    
+    @BeforeClass public static void oneTimeSetUp() throws Exception {
+    	//DQPConfiguration config = new DQPConfiguration();
+    	//config.setUserRequestSourceConcurrency(1);
+    	server = new FakeServer();
+    	JdbcDataSource h2ds = new JdbcDataSource();
+    	h2ds.setURL("jdbc:h2:zip:src/test/resources/relate/test.zip!/test");
+    	final DataSource ds = JdbcConnectionPool.create(h2ds);
+		ExecutionFactory h2 = new H2ExecutionFactory();
+		h2.start();
+		ConnectorManagerRepository cmr = new ConnectorManagerRepository();
+		ConnectorManager cm = new ConnectorManager("source", "bar") {
+			@Override
+			protected Object getConnectionFactory() throws TranslatorException {
+				return ds;
+			}
+		};
+		cm.setExecutionFactory(h2);
+		cmr.addConnectorManager("source", cm);
+		server.setConnectorManagerRepository(cmr);
+		server.deployVDB("VehicleRentalsVDB", UnitTestUtil.getTestDataPath()+"/relate/VehicleRentalsVDB.vdb");
+		if (DEBUG) {
+	    	Logger logger = Logger.getLogger("org.teiid");
+	    	logger.setLevel(Level.FINER);
+	    	ConsoleHandler handler = new ConsoleHandler();
+	    	handler.setLevel(Level.FINER);
+	    	logger.addHandler(handler);
+    	}
+    }
+    
+	private void compareResults(SQLXML[] docs)
+	throws SQLException, IOException {
+		StackTraceElement ste = new Exception().getStackTrace()[1];
+    	String testName = ste.getMethodName();
+    	testName = "relate/" + testName; //$NON-NLS-1$
+        File actual = new File(UnitTestUtil.getTestDataPath() + "/" +testName+".expected"); //$NON-NLS-1$ //$NON-NLS-2$
+        if (writeResults) {
+	        PrintWriter writer = new PrintWriter(actual);
+			for (SQLXML xml : docs) {
+				writer.write(xml.getString());
+				writer.write('\n');
+			}
+			writer.close();
+			return;
+        }
+        BufferedReader br = new BufferedReader(new FileReader(actual));
+		for (int i = 0; i < docs.length; i++) {
+			assertEquals(br.readLine(), docs[i].getString());
+		}
+	}
+
+    @Test public void testCase3365() throws Exception{
+    	SQLXML[] docs = relate(false, null, null, null, 
+    			"rentals.rentsVehicle", "rentals.company", "rentals.vehicle", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.rentsVehicle.companyId", 
+    			"rentals.rentsVehicle.vehicleId", "'*:rentals/*:rentsVehicle/@vehicleID'", "STRING", "rentals.vehicle.vehicleId", 
+    			"VehicleRentalsDoc.rentalsDocumentWithLocation",
+    			null, 
+    			null, 
+    			null, 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testCase3365_crit() throws Exception{
+    	SQLXML[] docs = relate(false, null, null, null, 
+    			"rentals.rentsVehicle", "rentals.company", "rentals.vehicle", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.rentsVehicle.companyId", 
+    			"rentals.rentsVehicle.vehicleId", "'*:rentals/*:rentsVehicle/@vehicleID'", "STRING", "rentals.vehicle.vehicleId", 
+    			"VehicleRentalsDoc.rentalsDocumentWithLocation",
+    			null, 
+    			"company.companyid = 'CID1'", 
+    			null, 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testCase3365_critNestedSrc() throws Exception {
+    	SQLXML[] docs = relate(false, null, null, null, 
+    			"rentals.rentsVehicle", "rentals.company", "rentals.vehicle", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.rentsVehicle.companyId", 
+    			"rentals.rentsVehicle.vehicleId", "'*:rentals/*:rentsVehicle/@vehicleID'", "STRING", "rentals.vehicle.vehicleId", 
+    			"VehicleRentalsDoc.rentalsDocumentWithLocation",
+    			null, 
+    			"location = 'Pittsburgh'", 
+    			null, 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testCase3365_critNestedSrcContext() throws Exception {
+    	SQLXML[] docs = relate(false, null, null, null, 
+    			"rentals.rentsVehicle", "rentals.company", "rentals.vehicle", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.rentsVehicle.companyId", 
+    			"rentals.rentsVehicle.vehicleId", "'*:rentals/*:rentsVehicle/@vehicleID'", "STRING", "rentals.vehicle.vehicleId", 
+    			"VehicleRentalsDoc.rentalsDocumentWithLocation",
+    			null, 
+    			null, 
+    			null, 
+    			null, 
+    			null, "context(location, location) = 'Pittsburgh'", null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testCase3365_critNestedSrcCombinationContext() throws Exception {
+    	SQLXML[] docs = relate(false, null, null, null, 
+    			"rentals.rentsVehicle", "rentals.company", "rentals.vehicle", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.rentsVehicle.companyId", 
+    			"rentals.rentsVehicle.vehicleId", "'*:rentals/*:rentsVehicle/@vehicleID'", "STRING", "rentals.vehicle.vehicleId", 
+    			"VehicleRentalsDoc.rentalsDocumentWithLocation",
+    			null, 
+    			"location = 'Pittsburgh'", 
+    			null, 
+    			null, 
+    			null, "context(location, location) = 'Pittsburgh'", null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testCase3365_critNestedTgt() throws Exception {
+    	SQLXML[] docs = relate(false, null, null, null, 
+    			"rentals.rentsVehicle", "rentals.company", "rentals.vehicle", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.rentsVehicle.companyId", 
+    			"rentals.rentsVehicle.vehicleId", "'*:rentals/*:rentsVehicle/@vehicleID'", "STRING", "rentals.vehicle.vehicleId", 
+    			"VehicleRentalsDoc.rentalsDocumentWithLocation",
+    			null, 
+    			null, 
+    			"color = 'Black'", 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testCase3365_compoundCritNestedTgt() throws Exception {
+    	SQLXML[] docs = relate(false, null, null, null, 
+    			"rentals.rentsVehicle", "rentals.company", "rentals.vehicle", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.rentsVehicle.companyId", 
+    			"rentals.rentsVehicle.vehicleId", "'*:rentals/*:rentsVehicle/@vehicleID'", "STRING", "rentals.vehicle.vehicleId", 
+    			"VehicleRentalsDoc.rentalsDocumentWithLocation",
+    			null, 
+    			null, 
+    			"color='Black' or color='Puce'", 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testSharesDoc() throws Exception {
+    	SQLXML[] docs = relate(true, null, null, null, 
+    			"rentals.hasSharingAgreement", "rentals.company", "rentals.company", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.hasSharingAgreement.primaryPartyID", 
+    			"rentals.hasSharingAgreement.secondaryPartyID", "'*:rentals/*:hasSharingAgreement/@secondaryPartyID'", "STRING", "rentals.company.companyId", 
+    			"VehicleRentalsDoc.companiesDocument",
+    			null, 
+    			null, 
+    			null, 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testSharesDocWithCritTgt() throws Exception {
+    	SQLXML[] docs = relate(true, null, null, null, 
+    			"rentals.hasSharingAgreement", "rentals.company", "rentals.company", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.hasSharingAgreement.primaryPartyID", 
+    			"rentals.hasSharingAgreement.secondaryPartyID", "'*:rentals/*:hasSharingAgreement/@secondaryPartyID'", "STRING", "rentals.company.companyId", 
+    			"VehicleRentalsDoc.companiesDocument",
+    			null, 
+    			null, 
+    			"rentals.company.name like 'B%'", 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testSharesDocWithCritTgtContext() throws Exception {
+    	SQLXML[] docs = relate(true, null, null, null, 
+    			"rentals.hasSharingAgreement", "rentals.company", "rentals.company", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.hasSharingAgreement.primaryPartyID", 
+    			"rentals.hasSharingAgreement.secondaryPartyID", "'*:rentals/*:hasSharingAgreement/@secondaryPartyID'", "STRING", "rentals.company.companyId", 
+    			"VehicleRentalsDoc.companiesDocument",
+    			null, 
+    			null, 
+    			"rentals.company.name like 'B%'", 
+    			"rentals.company.name like 'B%'", 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    @Test public void testSharesDocEspaceQuestion3() throws Exception {
+    	SQLXML[] docs = relate(true, null, null, null, 
+    			"rentals.hasSharingAgreement", "rentals.company", "rentals.company", 
+    			"rentals.company.companyId", "'*:rentals/*:company/@companyID'", "STRING", "rentals.hasSharingAgreement.primaryPartyID", 
+    			"rentals.hasSharingAgreement.secondaryPartyID", "'*:rentals/*:hasSharingAgreement/@secondaryPartyID'", "STRING", "rentals.company.companyId", 
+    			"VehicleRentalsDoc.companiesDocument",
+    			null, 
+    			"company.locations.location = 'Pittsburgh'", 
+    			null, 
+    			null, 
+    			null, null, null, 
+    			null, null, null);
+    	compareResults(docs);
+    }
+    
+    public SQLXML[] relate(
+    		//distinct is only meaningful for self-relationships
+    		boolean distinct,
+    		//select args to limit the xml projection
+    		//there is an assumption that the source/relationship select must project key values
+    		String relationshipSelect, String sourceSelect, String targetSelect,  
+    		//relevant contexts, the same as expected by the legacy relate function
+    		String relationshipContext, String sourceContext, String targetContext, 
+    		//break down of the relationship predicates
+    		String sourceKey, 
+     		  String sourceKeyPath,
+    		  String sourceKeyType,
+    		  String sourceFKey,
+    		String targetFKey, 
+    		String targetFKeyPath,
+    		  String targetFKeyType,
+    		  String targetKey,
+    		//target document
+    		String xmlDocument,
+    		//explicit/implicit relationship context criteria - should not use the context function 
+    		String relationshipCriteria,
+    		//relateSource/implicit/explicit source context criteria - should not use the context function
+    		String relateSourceCriteria, 
+    		//relateTarget criteria - should not use the context function
+    		String relateTargetCriteria, 
+    		//relateTarget context criteria - should not use the context function
+    		String relateTargetContextCriteria,
+    		//subcontext criteria, logically applied after the relate operation - should use context function(s), and should not be specified against a root context
+    		String relationshipContextCriteria,
+    		String sourceContextCriteria,
+    		String targetContextCriteria,
+    		//order bys
+    		String relationshipOrderBy,
+    		String sourceOrderBy,
+    		String targetOrderBy
+    		) throws Exception {
+    	if (sourceSelect == null) {
+    		sourceSelect = sourceContext + ".*";
+    	}
+    	if (relationshipSelect == null) {
+    		relationshipSelect = relationshipContext + ".*";
+    	}
+    	if (targetSelect == null) {
+    		targetSelect = targetContext + ".*";
+    	}
+    	Connection conn = server.createConnection("jdbc:teiid:VehicleRentalsVDB"); //$NON-NLS-1$
+    	if (DEBUG) {
+    		conn.createStatement().execute("SET SHOWPLAN DEBUG");
+    	}
+    	SQLXML[] result = new SQLXML[3];
+    	//source query
+    	String query = String.format("SELECT %s FROM %s WHERE CONTEXT(%s, %s) IN (SELECT %s FROM %s WHERE %s IN (SELECT %s FROM %s", sourceSelect, xmlDocument, sourceContext, sourceKey, sourceFKey, relationshipContext, targetFKey, targetKey, targetContext);
+    	if (relateTargetCriteria != null) {
+    		query += (" WHERE " + relateTargetCriteria);
+    	}
+    	query += "))";
+    	if (relateSourceCriteria != null) {
+    		query += String.format(" AND (CONTEXT(%s, %s) = null OR %s)", sourceContext, sourceKey, relateSourceCriteria);
+    	}
+    	if (relationshipCriteria != null) {
+    		query += String.format(" AND CONTEXT(%s, %s) IN (SELECT %s FROM %s WHERE AND %s)", sourceContext, sourceKey, sourceFKey, relationshipContext, relationshipCriteria);
+    	}
+    	if (sourceContextCriteria != null) {
+    		query += (" AND " + sourceContextCriteria);
+    	}
+    	if (sourceOrderBy != null) {
+    		query += (" ORDER BY " + sourceOrderBy);
+    	}
+    	PreparedStatement sourcePs = conn.prepareStatement(query);
+    	ResultSet sourceRs = sourcePs.executeQuery();
+    	sourceRs.next();
+    	SQLXML sourceXml = sourceRs.getSQLXML(1);
+    	result[0] = sourceXml;
+    	
+    	Statement ddlStmt = conn.createStatement();
+    	
+    	ddlStmt.execute("CREATE LOCAL TEMPORARY TABLE #st_source (source_key STRING, PRIMARY KEY (source_key))");
+    	//source key extraction
+    	String sourceStagingQuery = String.format("INSERT INTO #st_source (source_key) SELECT DISTINCT source_key FROM XMLTABLE(%s PASSING cast(? AS xml) COLUMNS source_key %s PATH '.') x", sourceKeyPath, sourceKeyType);
+    	PreparedStatement ps = conn.prepareStatement(sourceStagingQuery);
+    	ps.setSQLXML(1, sourceXml);
+    	ps.execute();
+    	ps.close();
+    	
+    	//relationship query
+    	String relQuery = String.format("SELECT %s FROM %s WHERE CONTEXT(%s, %s) IN /*+ DJ */ (SELECT source_key from #st_source) AND CONTEXT(%s, %s) IN (SELECT %s FROM %s", relationshipSelect, xmlDocument, relationshipContext, sourceFKey, relationshipContext, targetFKey, targetKey, targetContext);
+    	if (relateTargetContextCriteria != null) {
+    		relQuery += (" WHERE " + relateTargetContextCriteria);
+    	}
+    	relQuery += ")";
+    	if (relationshipCriteria != null) {
+    		relQuery += String.format(" AND (CONTEXT(%s, %s) = null OR %s)", relationshipContext, sourceFKey, relationshipCriteria);
+    	}
+    	if (relationshipContextCriteria != null) {
+    		relQuery += (" AND " + relationshipContextCriteria);
+    	}
+    	if (relationshipOrderBy != null) {
+    		relQuery += (" ORDER BY " + relationshipOrderBy);
+    	}
+    	PreparedStatement relStmt = conn.prepareStatement(relQuery);
+    	ResultSet relRs = relStmt.executeQuery();
+    	relRs.next();
+    	SQLXML relXml = relRs.getSQLXML(1);
+    	result[1] = relXml;
+    	
+    	ddlStmt.execute("CREATE LOCAL TEMPORARY TABLE #st_rel (target_key STRING, PRIMARY KEY (target_key))");
+    	//target key extraction
+    	String relStagingQuery = String.format("INSERT INTO #st_rel (target_key) SELECT DISTINCT target_key FROM XMLTABLE(%s PASSING cast(? AS xml) COLUMNS target_key %s PATH '.') x", targetFKeyPath, targetFKeyType);
+    	PreparedStatement psRel = conn.prepareStatement(relStagingQuery);
+    	psRel.setSQLXML(1, relXml);
+    	psRel.execute();
+    	psRel.close();
+    	
+    	//target query
+    	String targetQuery = String.format("SELECT %s FROM %s WHERE CONTEXT(%s, %s) IN /*+ DJ */ (SELECT target_key FROM #st_rel", targetSelect, xmlDocument, targetContext, targetKey);
+    	if (distinct && targetContext.equalsIgnoreCase(sourceContext)) {
+    		targetQuery += " EXCEPT SELECT source_key FROM #st_source";
+    	}
+    	targetQuery += ")";
+    	if (targetContextCriteria != null) {
+    		targetQuery += (" AND " + targetContextCriteria);
+    	}
+    	if (targetOrderBy != null) {
+    		targetQuery += (" ORDER BY " + targetOrderBy);
+    	}
+    	PreparedStatement targetStmt = conn.prepareStatement(targetQuery);
+    	ResultSet taretRs = targetStmt.executeQuery();
+    	taretRs.next();
+    	SQLXML targetXml = taretRs.getSQLXML(1);
+    	result[2] = targetXml;
+    	
+    	ddlStmt.execute("drop table #st_source");
+    	ddlStmt.execute("drop table #st_rel");
+    	
+    	return result;
+    }
+    
+}

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestTPCR.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -191,7 +191,7 @@
         
         ProcessorPlan plan = TestOptimizer.helpPlan("SELECT custsale.cntrycode, COUNT(*) AS numcust, SUM(c_acctbal) AS totacctbal FROM (SELECT left(C_PHONE, 2) AS cntrycode, CUSTOMER.C_ACCTBAL FROM CUSTOMER WHERE (left(C_PHONE, 2) IN ('13','31','23','29','30','18','17')) AND (CUSTOMER.C_ACCTBAL > (SELECT AVG(CUSTOMER.C_ACCTBAL) FROM CUSTOMER WHERE (CUSTOMER.C_ACCTBAL > 0.0) AND (left(C_PHONE, 2) IN ('13','31','23','29','30','18','17')))) AND (NOT (EXISTS (SELECT * FROM ORDERS WHERE O_CUSTKEY = C_CUSTKEY)))) AS custsale GROUP BY custsale.cntrycode ORDER BY custsale.cntrycode", //$NON-NLS-1$
         		METADATA, null, finder,
-        		new String[] {"SELECT v_0.c_0, COUNT(*) AS c_1, SUM(v_0.c_1) AS c_2 FROM (SELECT left(g_0.C_PHONE, 2) AS c_0, g_0.C_ACCTBAL AS c_1 FROM TPCR_Oracle_9i.CUSTOMER AS g_0 WHERE (left(g_0.C_PHONE, 2) IN ('13', '31', '23', '29', '30', '18', '17')) AND (g_0.C_ACCTBAL > (SELECT AVG(g_1.C_ACCTBAL) FROM TPCR_Oracle_9i.CUSTOMER AS g_1 WHERE (g_1.C_ACCTBAL > 0E-15) AND (left(g_1.C_PHONE, 2) IN ('13', '31', '23', '29', '30', '18', '17')))) AND (NOT EXISTS (SELECT 1 FROM TPCR_Oracle_9i.ORDERS AS g_2 WHERE g_2.O_CUSTKEY = g_0.C_CUSTKEY))) AS v_0 GROUP BY v_0.c_0 ORDER BY c_0 NULLS FIRST"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
+        		new String[] {"SELECT left(g_0.C_PHONE, 2) AS c_0, COUNT(*) AS c_1, SUM(g_0.C_ACCTBAL) AS c_2 FROM TPCR_Oracle_9i.CUSTOMER AS g_0 WHERE (left(g_0.C_PHONE, 2) IN ('13', '31', '23', '29', '30', '18', '17')) AND (g_0.C_ACCTBAL > (SELECT AVG(g_1.C_ACCTBAL) FROM TPCR_Oracle_9i.CUSTOMER AS g_1 WHERE (g_1.C_ACCTBAL > 0E-15) AND (left(g_1.C_PHONE, 2) IN ('13', '31', '23', '29', '30', '18', '17')))) AND (NOT EXISTS (SELECT 1 FROM TPCR_Oracle_9i.ORDERS AS g_2 WHERE g_2.O_CUSTKEY = g_0.C_CUSTKEY)) GROUP BY left(g_0.C_PHONE, 2) ORDER BY c_0 NULLS FIRST"}, ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$
         TestOptimizer.checkNodeTypes(plan, TestOptimizer.FULL_PUSHDOWN);
     }
     

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/dqp/internal/process/TestXMLTypeTranslations.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -74,18 +74,14 @@
         Timestamp ts = new Timestamp(-2106305630000l);
         ts.setNanos(3000000);
         
-        dataMgr.addData("SELECT g_0.\"timestamp\", g_0.\"double\", g_0.\"float\", convert(g_0.\"double\", biginteger), convert(g_0.\"double\", biginteger), convert(g_0.\"date\", timestamp), convert(g_0.\"double\", biginteger), convert(g_0.\"date\", timestamp), '1' FROM sample.RUNTIMEVALUE AS g_0", //$NON-NLS-1$ 
+        dataMgr.addData("SELECT g_0.\"timestamp\", g_0.\"double\", g_0.\"float\", convert(g_0.\"double\", biginteger), convert(g_0.\"date\", timestamp) FROM sample.RUNTIMEVALUE AS g_0", //$NON-NLS-1$ 
                         
                         new List[] { Arrays.asList(new Object[] { 
                             ts, 
                             new Double(Double.NEGATIVE_INFINITY), 
                             new Float(Float.POSITIVE_INFINITY), 
                             new BigInteger("100"), //$NON-NLS-1$
-                            new BigInteger("100"), //$NON-NLS-1$
                             ts, 
-                            new BigInteger("100"), //$NON-NLS-1$
-                            ts,
-                            "1" //$NON-NLS-1$
                                                    })});
         
         

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractMMQueryTestCase.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractMMQueryTestCase.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractMMQueryTestCase.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -80,7 +80,7 @@
     }    
         
       
-    protected void helpTest(String query, String[] expected, String vdb, String props, String urlProperties) {
+    protected void helpTest(String query, String[] expected, String vdb, String props, String urlProperties) throws SQLException {
         getConnection(vdb, props, urlProperties);
         executeAndAssertResults(query, expected);
         closeConnection();

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractQueryTest.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractQueryTest.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/AbstractQueryTest.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -86,11 +86,11 @@
     	return this.internalConnection;
     }
           
-    public boolean execute(String sql) {
+    public boolean execute(String sql) throws SQLException {
         return execute(sql, new Object[] {});
     }
     
-    public boolean execute(String sql, Object[] params) {
+    public boolean execute(String sql, Object[] params) throws SQLException {
     	closeResultSet();
     	closeStatement();
     	this.updateCount = -1;
@@ -122,7 +122,7 @@
         } catch (SQLException e) {
             this.internalException = e;
             if (!exceptionExpected()) {
-            	throw new RuntimeException(e);
+            	throw e;
             }            
         } 
         return false;
@@ -465,7 +465,7 @@
     }
 
     
-    protected void executeAndAssertResults(String query, String[] expected) {
+    protected void executeAndAssertResults(String query, String[] expected) throws SQLException {
         execute(query);
         if (expected != null) {
             assertResults(expected);

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/FakeServer.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,20 +22,30 @@
 package org.teiid.jdbc;
 
 import java.io.File;
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
 import java.util.LinkedHashMap;
+import java.util.Map;
 import java.util.Properties;
 
+import javax.security.auth.Subject;
+
+import org.jboss.as.security.plugins.SecurityDomainContext;
+import org.jboss.security.AuthenticationManager;
 import org.mockito.Mockito;
 import org.teiid.adminapi.AdminException;
 import org.teiid.adminapi.VDB;
 import org.teiid.adminapi.impl.ModelMetaData;
 import org.teiid.adminapi.impl.VDBMetaData;
 import org.teiid.cache.CacheConfiguration;
+import org.teiid.cache.CacheConfiguration.Policy;
 import org.teiid.cache.DefaultCacheFactory;
-import org.teiid.cache.CacheConfiguration.Policy;
 import org.teiid.client.DQP;
 import org.teiid.client.security.ILogon;
 import org.teiid.deployers.MetadataStoreGroup;
+import org.teiid.deployers.UDFMetaData;
 import org.teiid.deployers.VDBRepository;
 import org.teiid.deployers.VirtualDatabaseException;
 import org.teiid.dqp.internal.datamgr.ConnectorManager;
@@ -44,6 +54,7 @@
 import org.teiid.dqp.internal.process.DQPConfiguration;
 import org.teiid.dqp.internal.process.DQPCore;
 import org.teiid.dqp.service.FakeBufferService;
+import org.teiid.metadata.FunctionMethod;
 import org.teiid.metadata.MetadataRepository;
 import org.teiid.metadata.MetadataStore;
 import org.teiid.metadata.Schema;
@@ -55,13 +66,14 @@
 import org.teiid.query.metadata.TransformationMetadata.Resource;
 import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
 import org.teiid.query.optimizer.capabilities.SourceCapabilities;
+import org.teiid.security.SecurityHelper;
 import org.teiid.services.SessionServiceImpl;
 import org.teiid.transport.ClientServiceRegistry;
 import org.teiid.transport.ClientServiceRegistryImpl;
 import org.teiid.transport.LocalServerConnection;
 import org.teiid.transport.LogonImpl;
 
- at SuppressWarnings("nls")
+ at SuppressWarnings({"nls", "serial"})
 public class FakeServer extends ClientServiceRegistryImpl implements ConnectionProfile {
 
 	SessionServiceImpl sessionService = new SessionServiceImpl();
@@ -72,6 +84,44 @@
 	private boolean useCallingThread = true;
 	
 	public FakeServer() {
+		this(new DQPConfiguration());
+	}
+	
+	public FakeServer(DQPConfiguration config) {
+		
+		Map<String, SecurityDomainContext> securityDomainMap = new HashMap<String, SecurityDomainContext>();
+        SecurityDomainContext securityContext = Mockito.mock(SecurityDomainContext.class);
+        AuthenticationManager authManager = new AuthenticationManager() {
+			@Override
+			public String getSecurityDomain() {
+				return null;
+			}
+			@Override
+			public boolean isValid(Principal principal, Object credential) {
+				return true;
+			}
+			@Override
+			public boolean isValid(Principal principal, Object credential,Subject activeSubject) {
+				return true;
+			}
+			@Override
+			public Subject getActiveSubject() {
+				return null;
+			}
+			@Override
+			public Principal getTargetPrincipal(
+					Principal anotherDomainPrincipal,
+					Map<String, Object> contextMap) {
+				return null;
+			}
+        	
+        };
+        Mockito.stub(securityContext.getAuthenticationManager()).toReturn(authManager);
+        securityDomainMap.put("somedomain", securityContext); //$NON-NLS-1$
+        sessionService.setSecurityHelper(Mockito.mock(SecurityHelper.class));
+		
+        sessionService.setSecurityDomains(Arrays.asList("somedomain"), securityDomainMap);		
+		
 		this.logon = new LogonImpl(sessionService, null);
 		
 		this.repo.setSystemStore(VDBMetadataFactory.getSystem());
@@ -92,9 +142,13 @@
         	}
         });
         
-        DQPConfiguration config = new DQPConfiguration();
         config.setResultsetCacheConfig(new CacheConfiguration(Policy.LRU, 60, 250, "resultsetcache")); //$NON-NLS-1$
-        this.dqp.setCacheFactory(new DefaultCacheFactory());
+        this.dqp.setCacheFactory(new DefaultCacheFactory() {
+        	@Override
+        	public boolean isReplicated() {
+        		return true; //pretend to be replicated for matview tests
+        	}
+        });
         this.dqp.start(config);
         this.sessionService.setDqp(this.dqp);
         
@@ -102,6 +156,10 @@
         registerClientService(DQP.class, dqp, null);
 	}
 	
+	public void setConnectorManagerRepository(ConnectorManagerRepository cmr) {
+		this.cmr = cmr;
+	}
+	
 	public void stop() {
 		this.dqp.stop();
 	}
@@ -114,18 +172,25 @@
 	public void setUseCallingThread(boolean useCallingThread) {
 		this.useCallingThread = useCallingThread;
 	}
+
+	public void deployVDB(String vdbName, String vdbPath) throws Exception {
+		deployVDB(vdbName, vdbPath, null);
+	}
 	
-	public void deployVDB(String vdbName, String vdbPath) throws Exception {
-		
-		IndexMetadataFactory imf = VDBMetadataFactory.loadMetadata(new File(vdbPath).toURI().toURL());
+	public void deployVDB(String vdbName, String vdbPath, Map<String, Collection<FunctionMethod>> udfs) throws Exception {
+		IndexMetadataFactory imf = VDBMetadataFactory.loadMetadata(vdbName, new File(vdbPath).toURI().toURL());
 		MetadataStore metadata = imf.getMetadataStore(repo.getSystemStore().getDatatypes());
 		LinkedHashMap<String, Resource> entries = imf.getEntriesPlusVisibilities();
-		
-        deployVDB(vdbName, metadata, entries);		
+        deployVDB(vdbName, metadata, entries, udfs);		
 	}
+	
+	public void deployVDB(String vdbName, MetadataStore metadata,
+			LinkedHashMap<String, Resource> entries) {
+		deployVDB(vdbName, metadata, entries, null);
+	}
 
 	public void deployVDB(String vdbName, MetadataStore metadata,
-			LinkedHashMap<String, Resource> entries) {
+			LinkedHashMap<String, Resource> entries, Map<String, Collection<FunctionMethod>> udfs) {
 		VDBMetaData vdbMetaData = new VDBMetaData();
         vdbMetaData.setName(vdbName);
         vdbMetaData.setStatus(VDB.Status.ACTIVE);
@@ -145,7 +210,14 @@
         try {
         	MetadataStoreGroup stores = new MetadataStoreGroup();
         	stores.addStore(metadata);
-			this.repo.addVDB(vdbMetaData, stores, entries, null, cmr);
+        	UDFMetaData udfMetaData = null;
+        	if (udfs != null) {
+        		udfMetaData = new UDFMetaData();
+        		for (Map.Entry<String, Collection<FunctionMethod>> entry : udfs.entrySet()) {
+        			udfMetaData.addFunctions(entry.getKey(), entry.getValue());
+        		}
+        	}
+			this.repo.addVDB(vdbMetaData, stores, entries, udfMetaData, cmr);
 			this.repo.finishDeployment(vdbName, 1);
 		} catch (VirtualDatabaseException e) {
 			throw new RuntimeException(e);

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestDymamicImportedMetaData.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestDymamicImportedMetaData.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestDymamicImportedMetaData.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -74,7 +74,7 @@
     	assertEquals(1, p.getResultSet().getColumns().size());
     }
     
-    @Test public void testDuplicatException() throws Exception {
+    @Test public void testDuplicateException() throws Exception {
     	FakeServer server = new FakeServer();
     	MetadataFactory mf = createMetadataFactory("x", new Properties());
     	MetadataFactory mf1 = createMetadataFactory("y", new Properties());
@@ -93,8 +93,9 @@
     	
     	Properties importProperties = new Properties();
     	
-    	getMetadata(importProperties, conn);
-    	assertNotNull(mf.getMetadataStore().getSchemas().get("X").getTables().get("DUP"));
+    	mf = getMetadata(importProperties, conn);
+    	Table t = mf.getMetadataStore().getSchemas().get("TEST").getTables().get("TEST.X.DUP");
+    	assertEquals("\"test\".\"x\".\"dup\"", t.getNameInSource());
 
     	importProperties.setProperty("importer.useFullSchemaName", Boolean.FALSE.toString());
     	try {
@@ -104,5 +105,25 @@
     		
     	}
     }
+    
+    @Test public void testUseCatalog() throws Exception {
+    	FakeServer server = new FakeServer();
+    	MetadataFactory mf = createMetadataFactory("x", new Properties());
+    	
+    	Table dup = mf.addTable("dup");
+    	
+    	mf.addColumn("x", DataTypeManager.DefaultDataTypes.STRING, dup);
+    	
+    	MetadataStore ms = mf.getMetadataStore();
+    	
+    	server.deployVDB("test", ms, new LinkedHashMap<String, Resource>());
+    	Connection conn = server.createConnection("jdbc:teiid:test"); //$NON-NLS-1$
+    	
+    	Properties importProperties = new Properties();
+    	importProperties.setProperty("importer.useCatalogName", Boolean.FALSE.toString());
+    	mf = getMetadata(importProperties, conn);
+    	Table t = mf.getMetadataStore().getSchemas().get("TEST").getTables().get("X.DUP");
+    	assertEquals("\"x\".\"dup\"", t.getNameInSource());
+    }
 
 }

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestLocalConnections.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -22,14 +22,21 @@
 
 package org.teiid.jdbc;
 
-import static org.junit.Assert.fail;
+import static org.junit.Assert.*;
 
 import java.lang.Thread.UncaughtExceptionHandler;
 import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
 import java.sql.Statement;
-import java.util.LinkedHashMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.ReentrantLock;
 
@@ -37,13 +44,21 @@
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.teiid.core.types.DataTypeManager;
+import org.teiid.core.util.UnitTestUtil;
+import org.teiid.dqp.internal.datamgr.ConnectorManager;
+import org.teiid.dqp.internal.datamgr.ConnectorManagerRepository;
+import org.teiid.language.Command;
 import org.teiid.metadata.FunctionMethod;
 import org.teiid.metadata.FunctionParameter;
-import org.teiid.metadata.MetadataStore;
-import org.teiid.metadata.Schema;
+import org.teiid.metadata.RuntimeMetadata;
 import org.teiid.metadata.FunctionMethod.PushDown;
 import org.teiid.query.function.metadata.FunctionCategoryConstants;
-import org.teiid.query.metadata.TransformationMetadata.Resource;
+import org.teiid.translator.DataNotAvailableException;
+import org.teiid.translator.Execution;
+import org.teiid.translator.ExecutionContext;
+import org.teiid.translator.ExecutionFactory;
+import org.teiid.translator.ResultSetExecution;
+import org.teiid.translator.TranslatorException;
 
 @SuppressWarnings("nls")
 public class TestLocalConnections {
@@ -62,12 +77,15 @@
 	static Condition waiting = lock.newCondition();
 	static Condition wait = lock.newCondition();
 	
-	public static int blocking() throws InterruptedException, TimeoutException {
+	static Semaphore sourceCounter = new Semaphore(0);
+	
+	public static int blocking() throws InterruptedException {
+
 		lock.lock();
 		try {
 			waiting.signal();
 			if (!wait.await(2, TimeUnit.SECONDS)) {
-				throw new TimeoutException();
+				throw new RuntimeException();
 			}
 		} finally {
 			lock.unlock();
@@ -77,15 +95,75 @@
 
 	static FakeServer server = new FakeServer();
 	
-	@BeforeClass public static void oneTimeSetup() {
+	@SuppressWarnings("serial")
+	@BeforeClass public static void oneTimeSetup() throws Exception {
     	server.setUseCallingThread(true);
-    	MetadataStore ms = new MetadataStore();
-    	Schema s = new Schema();
-    	s.setName("test");
+    	server.setConnectorManagerRepository(new ConnectorManagerRepository() {
+    		@Override
+    		public ConnectorManager getConnectorManager(String connectorName) {
+    			return new ConnectorManager(connectorName, connectorName) {
+    				@Override
+    				protected ExecutionFactory<Object, Object> getExecutionFactory() {
+    					return new ExecutionFactory<Object, Object>() {
+    						@Override
+    						public Execution createExecution(Command command,
+    								ExecutionContext executionContext,
+    								RuntimeMetadata metadata, Object connection)
+    								throws TranslatorException {
+    						    return new ResultSetExecution() {
+    						    	
+    						    	boolean returnedRow = false;
+    						    	
+									@Override
+									public void execute() throws TranslatorException {
+										lock.lock();
+										try {
+											sourceCounter.release();
+											if (!wait.await(2, TimeUnit.SECONDS)) {
+												throw new RuntimeException();
+											}
+										} catch (InterruptedException e) {
+											throw new RuntimeException(e);
+										} finally {
+											lock.unlock();
+										}
+									}
+									
+									@Override
+									public void close() {
+										
+									}
+									
+									@Override
+									public void cancel() throws TranslatorException {
+										
+									}
+									
+									@Override
+									public List<?> next() throws TranslatorException, DataNotAvailableException {
+										if (returnedRow) {
+											return null;
+										}
+										returnedRow = true;
+										return new ArrayList<Object>(Collections.singleton(null));
+									}
+								};
+    						}
+    					};
+    				}
+    				
+    				@Override
+    				protected Object getConnectionFactory()
+    						throws TranslatorException {
+    					return null;
+    				}
+    			};
+    		}
+    	});
     	FunctionMethod function = new FunctionMethod("foo", null, FunctionCategoryConstants.MISCELLANEOUS, PushDown.CANNOT_PUSHDOWN, TestLocalConnections.class.getName(), "blocking", new FunctionParameter[0], new FunctionParameter("result", DataTypeManager.DefaultDataTypes.INTEGER), true, FunctionMethod.Determinism.NONDETERMINISTIC);
-    	s.addFunction(function);
-    	ms.addSchema(s);
-    	server.deployVDB("test", ms, new LinkedHashMap<String, Resource>());
+    	HashMap<String, Collection<FunctionMethod>> udfs = new HashMap<String, Collection<FunctionMethod>>();
+    	udfs.put("test", Arrays.asList(function));
+    	server.deployVDB("PartsSupplier", UnitTestUtil.getTestDataPath() + "/PartsSupplier.vdb", udfs);
 	}
 	
 	@AfterClass public static void oneTimeTearDown() {
@@ -98,10 +176,11 @@
     		
     		public void run() {
     			try {
-	    	    	Connection c = server.createConnection("jdbc:teiid:test");
+	    	    	Connection c = server.createConnection("jdbc:teiid:PartsSupplier");
 	    	    	
 	    	    	Statement s = c.createStatement();
 	    	    	s.execute("select foo()");
+	    	    	s.close();
     			} catch (Exception e) {
     				throw new RuntimeException(e);
     			}
@@ -117,7 +196,7 @@
     	} finally {
     		lock.unlock();
     	}
-    	Connection c = server.createConnection("jdbc:teiid:test");
+    	Connection c = server.createConnection("jdbc:teiid:PartsSupplier");
     	Statement s = c.createStatement();
     	s.execute("select * from tables");
     	
@@ -131,9 +210,129 @@
     	if (t.isAlive()) {
     		fail();
     	}
+    	s.close();
     	if (handler.t != null) {
     		throw handler.t;
     	}
 	}
 	
+	@Test public void testUseInDifferentThreads() throws Throwable {
+		Connection c = server.createConnection("jdbc:teiid:PartsSupplier");
+    	
+    	final Statement s = c.createStatement();
+    	s.execute("select 1");
+    	
+    	assertFalse(server.dqp.getRequests().isEmpty());
+
+    	Thread t = new Thread() {
+    		public void run() {
+    			try {
+					s.close();
+				} catch (SQLException e) {
+					throw new RuntimeException(e);
+				}
+    		}
+    	};
+    	SimpleUncaughtExceptionHandler handler = new SimpleUncaughtExceptionHandler();
+    	t.setUncaughtExceptionHandler(handler);
+    	t.start();
+    	t.join(2000);
+    	if (t.isAlive()) {
+    		fail();
+    	}
+    	
+    	assertTrue(server.dqp.getRequests().isEmpty());
+    	
+    	if (handler.t != null) {
+    		throw handler.t;
+    	}
+	}
+	
+	@Test public void testWait() throws Throwable {
+		final Connection c = server.createConnection("jdbc:teiid:PartsSupplier");
+    	
+		Thread t = new Thread() {
+			public void run() {
+		    	Statement s;
+				try {
+					s = c.createStatement();
+			    	assertTrue(s.execute("select part_id from parts"));
+				} catch (SQLException e) {
+					throw new RuntimeException(e);
+				}
+			}
+		};
+    	t.start();
+    	SimpleUncaughtExceptionHandler handler = new SimpleUncaughtExceptionHandler();
+    	t.setUncaughtExceptionHandler(handler);
+    	
+    	sourceCounter.acquire();
+    	
+    	//t should now be waiting also
+    	
+    	lock.lock();
+    	try {
+    		wait.signal();
+    	} finally {
+    		lock.unlock();
+    	}
+
+    	//t should finish
+    	t.join();
+    	
+    	if (handler.t != null) {
+    		throw handler.t;
+    	}
+	}
+	
+	@Test public void testWaitMultiple() throws Throwable {
+		final Connection c = server.createConnection("jdbc:teiid:PartsSupplier");
+    	
+		Thread t = new Thread() {
+			public void run() {
+		    	Statement s;
+				try {
+					s = c.createStatement();
+			    	assertTrue(s.execute("select part_id from parts union all select part_id from parts"));
+			    	ResultSet r = s.getResultSet();
+			    	
+			    	//wake up the other source thread, should put the requestworkitem into the more work state 
+			    	lock.lock();
+			    	try {
+			    		wait.signal();
+			    	} finally {
+			    		lock.unlock();
+			    	}
+			    	Thread.sleep(1000); //TODO: need a better hook to determine that connector work has finished
+			    	while (r.next()) {
+			    		//will hang unless this thread is allowed to resume processing
+			    	}
+				} catch (Exception e) {
+					throw new RuntimeException(e);
+				}
+			}
+		};
+    	t.start();
+    	SimpleUncaughtExceptionHandler handler = new SimpleUncaughtExceptionHandler();
+    	t.setUncaughtExceptionHandler(handler);
+    	
+    	sourceCounter.acquire(2);
+    	
+    	//t should now be waiting also
+    	
+    	//wake up 1 source thread
+    	lock.lock();
+    	try {
+    		wait.signal();
+    	} finally {
+    		lock.unlock();
+    	}
+    	
+    	t.join();
+    	
+    	if (handler.t != null) {
+    		throw handler.t;
+    	}
+	}
+	
 }

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestMMDatabaseMetaData.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestMMDatabaseMetaData.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestMMDatabaseMetaData.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -615,6 +615,12 @@
         ResultSet rs = dbmd.getTables(null, "SYSTEM", "VIRTUALDATABASES", null); //$NON-NLS-1$ //$NON-NLS-2$
         compareResultSet(rs);
     }
+    
+    @Test
+    public void testGetTables_noTypes() throws Exception {
+        ResultSet rs = dbmd.getTables(null, "SYSTEM", "VIRTUALDATABASES", new String[0]); //$NON-NLS-1$ //$NON-NLS-2$
+        assertFalse(rs.next());
+    }
 
     @Test
     public void testGetTables_specificTableTypes() throws Exception {
@@ -909,7 +915,7 @@
         expected.put("getSystemFunctions", DatabaseMetaDataImpl.SYSTEM_FUNCTIONS); //$NON-NLS-1$
         expected.put("getTimeDateFunctions", DatabaseMetaDataImpl.DATE_FUNCTIONS); //$NON-NLS-1$
         //expected.put("getUrl", primaryUrl + serverUrl); //$NON-NLS-1$
-        expected.put("getUserName", CoreConstants.DEFAULT_ANON_USERNAME); //$NON-NLS-1$
+        expected.put("getUserName", CoreConstants.DEFAULT_ANON_USERNAME+"@somedomain"); //$NON-NLS-1$
 
         // return type - Object
         expected.put("getConnection", conn); //$NON-NLS-1$

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestQueryPlans.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestQueryPlans.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestQueryPlans.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -32,6 +32,7 @@
 
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
+import org.junit.Ignore;
 import org.junit.Test;
 import org.teiid.core.util.UnitTestUtil;
 

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestResultsMetadataWithProvider.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestResultsMetadataWithProvider.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestResultsMetadataWithProvider.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -45,8 +45,8 @@
 
     public MetadataProvider exampleProvider() throws Exception {
         MetaDataProcessor processor = new MetaDataProcessor(null, null, "vdb", 1); //$NON-NLS-1$  
-        Map col1 = processor.getDefaultColumn("table", "col1", String.class); //$NON-NLS-1$ //$NON-NLS-2$ 
-        Map col2 = processor.getDefaultColumn("table", "col2", Integer.class); //$NON-NLS-1$ //$NON-NLS-2$ 
+        Map col1 = processor.getDefaultColumn("table", "col1", "col1Label", String.class); //$NON-NLS-1$ //$NON-NLS-2$ 
+        Map col2 = processor.getDefaultColumn("table", "col2", "col2Label", Integer.class); //$NON-NLS-1$ //$NON-NLS-2$ 
         
         Map[] columnMetadata = new Map[] {
             col1, col2
@@ -55,9 +55,9 @@
         MetadataProvider provider = new MetadataProvider(columnMetadata);                      
         return provider;        
     }
-
+    
     public void test1() throws Exception {        
-        ResultSetMetaDataImpl rmd = new ResultSetMetaDataImpl(exampleProvider());
+        ResultSetMetaDataImpl rmd = new ResultSetMetaDataImpl(exampleProvider(), null);
         
         assertEquals(false, rmd.isAutoIncrement(1));
         assertEquals(false, rmd.isCaseSensitive(1));
@@ -71,6 +71,26 @@
         assertEquals(null, rmd.getSchemaName(1)); 
         assertEquals("table", rmd.getTableName(1)); //$NON-NLS-1$
         assertEquals("col1", rmd.getColumnName(1)); //$NON-NLS-1$
+        assertEquals("col1Label", rmd.getColumnLabel(1)); //$NON-NLS-1$
         assertEquals("string", rmd.getColumnTypeName(1)); //$NON-NLS-1$
     }
+    
+    public void test2BackwardCompatibilityTest() throws Exception {        
+        ResultSetMetaDataImpl rmd = new ResultSetMetaDataImpl(exampleProvider(), "false");
+        
+        assertEquals(false, rmd.isAutoIncrement(1));
+        assertEquals(false, rmd.isCaseSensitive(1));
+        assertEquals(false, rmd.isCurrency(1));
+        assertEquals(true, rmd.isDefinitelyWritable(1));
+        assertEquals(false, rmd.isReadOnly(1));
+        assertEquals(true, rmd.isSearchable(1));
+        assertEquals(true, rmd.isSigned(1));
+        assertEquals(true, rmd.isWritable(1));
+        assertEquals("vdb", rmd.getCatalogName(1)); //$NON-NLS-1$
+        assertEquals(null, rmd.getSchemaName(1)); 
+        assertEquals("table", rmd.getTableName(1)); //$NON-NLS-1$
+        assertEquals("col1Label", rmd.getColumnName(1)); //$NON-NLS-1$
+        assertEquals("col1Label", rmd.getColumnLabel(1)); //$NON-NLS-1$
+        assertEquals("string", rmd.getColumnTypeName(1)); //$NON-NLS-1$
+    }    
 }

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestVDBMerge.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestVDBMerge.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/jdbc/TestVDBMerge.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,5 +1,7 @@
 package org.teiid.jdbc;
 
+import java.sql.SQLException;
+
 import org.junit.Test;
 import org.teiid.core.util.UnitTestUtil;
 
@@ -66,7 +68,7 @@
        executeTest("select * from tables where schemaname ='PartsSupplier'", expected); //$NON-NLS-1$
     }
 	
-    private void executeTest(String sql, String[] expected){
+    private void executeTest(String sql, String[] expected) throws SQLException{
     	execute(sql);
     	if (expected != null) {
     		assertResults(expected);

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMatViews.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMatViews.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMatViews.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -28,15 +28,22 @@
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
 
+import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
-import org.teiid.adminapi.impl.VDBMetaData;
+import org.teiid.core.TeiidRuntimeException;
+import org.teiid.core.types.DataTypeManager;
 import org.teiid.core.util.UnitTestUtil;
 import org.teiid.jdbc.FakeServer;
 import org.teiid.jdbc.TeiidSQLException;
-import org.teiid.metadata.Table;
-import org.teiid.query.metadata.TransformationMetadata;
+import org.teiid.metadata.FunctionMethod;
+import org.teiid.metadata.FunctionParameter;
+import org.teiid.metadata.FunctionMethod.Determinism;
+import org.teiid.metadata.FunctionMethod.PushDown;
 
 @SuppressWarnings("nls")
 public class TestMatViews {
@@ -44,13 +51,33 @@
     private static final String MATVIEWS = "matviews";
 	private Connection conn;
 	private FakeServer server;
+	
+	private static int count = 0;
+	
+	public static int pause() throws InterruptedException {
+		synchronized (TestMatViews.class) {
+			count++;
+			TestMatViews.class.notify();
+			while (count < 2) {
+				TestMatViews.class.wait();
+			}
+		}
+		return 1;
+	}
 
 	@Before public void setUp() throws Exception {
     	server = new FakeServer();
-    	server.deployVDB(MATVIEWS, UnitTestUtil.getTestDataPath() + "/matviews.vdb");
+    	HashMap<String, Collection<FunctionMethod>> udfs = new HashMap<String, Collection<FunctionMethod>>();
+    	udfs.put("funcs", Arrays.asList(new FunctionMethod("pause", null, null, PushDown.CANNOT_PUSHDOWN, TestMatViews.class.getName(), "pause", null, new FunctionParameter("return", DataTypeManager.DefaultDataTypes.INTEGER), false, Determinism.NONDETERMINISTIC)));
+    	server.deployVDB(MATVIEWS, UnitTestUtil.getTestDataPath() + "/matviews.vdb", udfs);
     	conn = server.createConnection("jdbc:teiid:matviews");
     }
 	
+	@After public void tearDown() throws Exception {
+		server.stop();
+		conn.close();
+	}
+	
 	@Test public void testSystemMatViewsWithImplicitLoad() throws Exception {
 		Statement s = conn.createStatement();
 		ResultSet rs = s.executeQuery("select * from MatViews order by name");
@@ -80,6 +107,34 @@
 	
 	@Test public void testSystemMatViewsWithExplicitRefresh() throws Exception {
 		Statement s = conn.createStatement();
+		ResultSet rs = s.executeQuery("select * from (call refreshMatView('TEST.RANDOMVIEW', false)) p");
+		assertTrue(rs.next());
+		assertEquals(1, rs.getInt(1));
+		rs = s.executeQuery("select * from MatViews where name = 'RandomView'");
+		assertTrue(rs.next());
+		assertEquals("LOADED", rs.getString("loadstate"));
+		assertEquals(true, rs.getBoolean("valid"));
+		rs = s.executeQuery("select x from TEST.RANDOMVIEW");
+		assertTrue(rs.next());
+		double key = rs.getDouble(1);
+
+		rs = s.executeQuery("select * from (call refreshMatView('TEST.RANDOMVIEW', false)) p");
+		assertTrue(rs.next());
+		assertEquals(1, rs.getInt(1));
+		rs = s.executeQuery("select * from MatViews where name = 'RandomView'");
+		assertTrue(rs.next());
+		assertEquals("LOADED", rs.getString("loadstate"));
+		assertEquals(true, rs.getBoolean("valid"));
+		rs = s.executeQuery("select x from TEST.RANDOMVIEW");
+		assertTrue(rs.next());
+		double key1 = rs.getDouble(1);
+
+		//ensure that invalidate with distributed caching works
+		assertTrue(key1 != key);
+	}
+	
+	@Test public void testSystemManViewsWithExplictRefreshAndInvalidate() throws Exception {
+		Statement s = conn.createStatement();
 		ResultSet rs = s.executeQuery("select * from (call refreshMatView('TEST.MATVIEW', false)) p");
 		assertTrue(rs.next());
 		assertEquals(1, rs.getInt(1));
@@ -87,6 +142,42 @@
 		assertTrue(rs.next());
 		assertEquals("LOADED", rs.getString("loadstate"));
 		assertEquals(true, rs.getBoolean("valid"));
+		
+		count = 0;
+		s.execute("alter view TEST.MATVIEW as select pause() as x");
+		Thread t = new Thread() {
+			public void run() {
+				try {
+					Statement s1 = conn.createStatement();
+					ResultSet rs = s1.executeQuery("select * from (call refreshMatView('TEST.MATVIEW', true)) p");
+					assertTrue(rs.next());
+					assertEquals(1, rs.getInt(1));
+				} catch (Exception e) {
+					throw new TeiidRuntimeException(e);
+				}
+			}
+		};
+		t.start();
+		synchronized (TestMatViews.class) {
+			while (count < 1) {
+				TestMatViews.class.wait();
+			}
+		}
+		rs = s.executeQuery("select * from MatViews where name = 'MatView'");
+		assertTrue(rs.next());
+		assertEquals("NEEDS_LOADING", rs.getString("loadstate"));
+		assertEquals(false, rs.getBoolean("valid"));
+
+		synchronized (TestMatViews.class) {
+			count++;
+			TestMatViews.class.notify();
+		}
+		t.join();
+		
+		rs = s.executeQuery("select * from MatViews where name = 'MatView'");
+		assertTrue(rs.next());
+		assertEquals("LOADED", rs.getString("loadstate"));
+		assertEquals(true, rs.getBoolean("valid"));
 	}
 	
 	@Test(expected=TeiidSQLException.class) public void testSystemMatViewsInvalidView() throws Exception {
@@ -99,14 +190,27 @@
 		s.execute("call refreshMatView('foo', false)");
 	}
 	
+	@Test(expected=TeiidSQLException.class) public void testSystemMatViewsWithRowRefreshNotAllowed() throws Exception {
+		Statement s = conn.createStatement();
+		s.execute("alter view test.randomview as select rand() as x, rand() as y");
+		ResultSet rs = s.executeQuery("select * from (call refreshMatView('TEST.RANDOMVIEW', false)) p");
+		assertTrue(rs.next());
+		assertEquals(1, rs.getInt(1));
+		rs = s.executeQuery("select * from MatViews where name = 'RandomView'");
+		assertTrue(rs.next());
+		assertEquals("LOADED", rs.getString("loadstate"));
+		assertEquals(true, rs.getBoolean("valid"));
+		rs = s.executeQuery("select x from TEST.RANDOMVIEW");
+		assertTrue(rs.next());
+		double key = rs.getDouble(1);
+		
+		rs = s.executeQuery("select * from (call refreshMatViewRow('TEST.RANDOMVIEW', "+key+")) p");
+	}
+	
 	@Test public void testSystemMatViewsWithRowRefresh() throws Exception {
-		//TOOD: remove this. it's a workaround for TEIIDDES-549
-		VDBMetaData vdb = server.getVDB(MATVIEWS);
-		TransformationMetadata tm = vdb.getAttachment(TransformationMetadata.class);
-		Table t = tm.getGroupID("TEST.RANDOMVIEW");
-		t.setSelectTransformation("/*+ cache(updatable) */ " +  t.getSelectTransformation());
+		Statement s = conn.createStatement();
 		
-		Statement s = conn.createStatement();
+		s.execute("alter view test.randomview as /*+ cache(updatable) */ select rand() as x, rand() as y");
 		//prior to load refresh of a single row returns -1
 		ResultSet rs = s.executeQuery("select * from (call refreshMatViewRow('TEST.RANDOMVIEW', 0)) p");
 		assertTrue(rs.next());

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMetadataUpdates.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMetadataUpdates.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestMetadataUpdates.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -67,7 +67,7 @@
     		public String answer(InvocationOnMock invocation) throws Throwable {
     			Procedure t = (Procedure)invocation.getArguments()[2];
     			if (t.getName().equals("proc")) {
-    				return "create virtual procedure begin select '2011'; end";
+    				return "create virtual procedure begin select '2011'; if ((call isLoggable())) call logMsg(msg=>'hello'); end";
     			}
     			return null;
     		}

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestSystemVirtualModel.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestSystemVirtualModel.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestSystemVirtualModel.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -83,7 +83,7 @@
 		checkResult("testProcedures", "select* from SYS.Procedures order by Name"); //$NON-NLS-1$ //$NON-NLS-2$
 	}
 
-	@Test public void testProperties() {
+	@Test public void testProperties() throws Exception {
 		String[] expected = { "Name[string]	Value[string]	UID[string]	OID[integer]	ClobValue[clob]",
 				"pg_type:oid	30	mmuid:ffa4ac73-b549-470e-931f-dc36330cb8c4	1	30",
 				"pg_type:oid	1009	mmuid:d9f36bdc-7b25-4af0-b9f5-a96aac6d3094	2	1009",
@@ -94,7 +94,7 @@
 		executeAndAssertResults("select* from SYS.Properties", expected); //$NON-NLS-1$
 	}
 
-	@Test public void testVirtualDatabase() {
+	@Test public void testVirtualDatabase() throws Exception {
 
 		String[] expected = { "Name[string]	Version[string]	", "PartsSupplier	1", //$NON-NLS-1$ //$NON-NLS-2$
 
@@ -116,7 +116,7 @@
 		checkResult("testColumns", "select* from SYS.Columns order by Name"); //$NON-NLS-1$ //$NON-NLS-2$
 	}
 
-	@Test public void testTableType() {
+	@Test public void testTableType() throws Exception {
 
 		String[] expected = { "Type[string]	", "Table", }; //$NON-NLS-1$ //$NON-NLS-2$
 		executeAndAssertResults(
@@ -128,7 +128,7 @@
 		checkResult("testTableIsSystem", "select Name from SYS.Tables where IsSystem = 'false' order by Name"); //$NON-NLS-1$ //$NON-NLS-2$
 	}
 
-	@Test public void testDefect12064() {
+	@Test public void testDefect12064() throws Exception {
 		String[] expected = { 
 				"KeyName[string]	RefKeyUID[string]	",  //$NON-NLS-1$
 				"PK_PARTS	null", //$NON-NLS-1$
@@ -174,4 +174,12 @@
 		oidCount = getRowCount();
 		assertEquals(uidCount, oidCount);		
 	}
+	
+	@Test public void testLogMsg() throws Exception {
+		execute("call logMsg(level=>'DEBUG', context=>'org.teiid.foo', msg=>'hello world')"); //$NON-NLS-1$
+	}
+	
+	@Test(expected=SQLException.class) public void testLogMsg1() throws Exception {
+		execute("call logMsg(level=>'foo', context=>'org.teiid.foo', msg=>'hello world')"); //$NON-NLS-1$
+	}
 }

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestVirtualDocWithVirtualProc.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestVirtualDocWithVirtualProc.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/systemmodel/TestVirtualDocWithVirtualProc.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -55,7 +55,7 @@
     	closeConnection();
     }
     
-    @Test public void testDefect15241() {
+    @Test public void testDefect15241() throws Exception {
 
     	String sql = "SELECT SchemaName, Name, Description FROM SYS.Tables WHERE Name = 'yyyTestDocument'"; //$NON-NLS-1$
 
@@ -67,7 +67,7 @@
     	executeAndAssertResults(sql, expected);
     }
 
-    @Test public void testDefect15241a() {
+    @Test public void testDefect15241a() throws Exception {
     	String sql = "SELECT TableName, Name, Description FROM SYS.Columns WHERE Name = 'IntKey'"; //$NON-NLS-1$
     	String[] expected ={
 		    "TableName[string]	Name[string]	Description[string]",	 //$NON-NLS-1$
@@ -83,7 +83,7 @@
     	executeAndAssertResults(sql, expected);
     }
 
-    @Test public void testDefect15241b() {
+    @Test public void testDefect15241b() throws Exception {
     	
     	String sql = "SELECT p.Name, p.Value, UID FROM SYS.Properties p"; //$NON-NLS-1$
     	String[] expected ={

Modified: branches/as7/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java
===================================================================
--- branches/as7/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -24,8 +24,13 @@
 
 import static org.junit.Assert.*;
 
+import java.io.IOException;
+import java.net.InetAddress;
 import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
 import java.nio.charset.Charset;
+import java.security.NoSuchAlgorithmException;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
@@ -33,48 +38,124 @@
 import java.sql.Statement;
 import java.util.Properties;
 
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSocket;
+import javax.net.ssl.SSLSocketFactory;
+
 import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
+import org.mockito.Mockito;
 import org.postgresql.Driver;
+import org.teiid.client.security.ILogon;
 import org.teiid.common.buffer.BufferManagerFactory;
 import org.teiid.core.util.UnitTestUtil;
 import org.teiid.jdbc.FakeServer;
 import org.teiid.jdbc.TeiidDriver;
 import org.teiid.jdbc.TestMMDatabaseMetaData;
+import org.teiid.net.socket.SocketUtil;
 
 @SuppressWarnings("nls")
 public class TestODBCSocketTransport {
-
-	static InetSocketAddress addr;
-	static ODBCSocketListener odbcTransport;
 	
-	@BeforeClass public static void oneTimeSetup() throws Exception {
-		SocketConfiguration config = new SocketConfiguration();
-		config.setSSLConfiguration(new SSLConfiguration());
-		addr = new InetSocketAddress(0);
-		config.setBindAddress(addr.getHostName());
-		config.setPortNumber(0);
-		odbcTransport = new ODBCSocketListener(config, BufferManagerFactory.getStandaloneBufferManager(), 0, 100000);
+public static class AnonSSLSocketFactory extends SSLSocketFactory {
 		
-		FakeServer server = new FakeServer();
-		server.setUseCallingThread(false);
-		server.deployVDB("parts", UnitTestUtil.getTestDataPath() + "/PartsSupplier.vdb");
+		private SSLSocketFactory sslSocketFactory;
 		
-		TeiidDriver driver = new TeiidDriver();
-		driver.setEmbeddedProfile(server);
-		odbcTransport.setDriver(driver);
+		public AnonSSLSocketFactory() {
+			try {
+				sslSocketFactory = SSLContext.getDefault().getSocketFactory();
+			} catch (NoSuchAlgorithmException e) {
+				throw new RuntimeException();
+			}			
+		}
+
+		public Socket createSocket() throws IOException {
+			return sslSocketFactory.createSocket();
+		}
+
+		public Socket createSocket(InetAddress address, int port,
+				InetAddress localAddress, int localPort) throws IOException {
+			return sslSocketFactory.createSocket(address, port, localAddress,
+					localPort);
+		}
+
+		public Socket createSocket(InetAddress host, int port)
+				throws IOException {
+			return sslSocketFactory.createSocket(host, port);
+		}
+
+		public Socket createSocket(Socket s, String host, int port,
+				boolean autoClose) throws IOException {
+			SSLSocket socket = (SSLSocket)sslSocketFactory.createSocket(s, host, port, autoClose);
+			SocketUtil.addCipherSuite(socket, SocketUtil.ANON_CIPHER_SUITE);
+			return socket;
+		}
+
+		public Socket createSocket(String host, int port,
+				InetAddress localHost, int localPort) throws IOException,
+				UnknownHostException {
+			return sslSocketFactory.createSocket(host, port, localHost,
+					localPort);
+		}
+
+		public Socket createSocket(String host, int port) throws IOException,
+				UnknownHostException {
+			return sslSocketFactory.createSocket(host, port);
+		}
+
+		public String[] getDefaultCipherSuites() {
+			return sslSocketFactory.getDefaultCipherSuites();
+		}
+
+		public String[] getSupportedCipherSuites() {
+			return sslSocketFactory.getSupportedCipherSuites();
+		}
 		
 	}
 	
-	@AfterClass public static void oneTimeTearDown() throws Exception {
-		if (odbcTransport != null) {
+	static class FakeOdbcServer {
+		InetSocketAddress addr;
+		ODBCSocketListener odbcTransport;
+		
+		public void start() throws Exception {
+			SocketConfiguration config = new SocketConfiguration();
+			SSLConfiguration sslConfig = new SSLConfiguration();
+			sslConfig.setMode(SSLConfiguration.ENABLED);
+			sslConfig.setAuthenticationMode(SSLConfiguration.ANONYMOUS);
+			config.setSSLConfiguration(sslConfig);
+			addr = new InetSocketAddress(0);
+			config.setBindAddress(addr.getHostName());
+			config.setPortNumber(0);
+			odbcTransport = new ODBCSocketListener(config, BufferManagerFactory.getStandaloneBufferManager(), 0, 100000, Mockito.mock(ILogon.class));
+			
+			FakeServer server = new FakeServer();
+			server.setUseCallingThread(false);
+			server.deployVDB("parts", UnitTestUtil.getTestDataPath() + "/PartsSupplier.vdb");
+			
+			TeiidDriver driver = new TeiidDriver();
+			driver.setEmbeddedProfile(server);
+			odbcTransport.setDriver(driver);
+		}
+		
+		public void stop() {
 			odbcTransport.stop();
 		}
+		
 	}
 	
+	private static FakeOdbcServer odbcServer = new FakeOdbcServer();
+	
+	@BeforeClass public static void oneTimeSetup() throws Exception {
+		odbcServer.start();
+	}
+	
+	@AfterClass public static void oneTimeTearDown() throws Exception {
+		odbcServer.stop();
+	}
+	
 	Connection conn;
 	
 	@Before public void setUp() throws Exception {
@@ -82,7 +163,7 @@
 		Properties p = new Properties();
 		p.setProperty("user", "testuser");
 		p.setProperty("password", "testpassword");
-		conn = d.connect("jdbc:postgresql://"+addr.getHostName()+":" +odbcTransport.getPort()+"/parts", p);
+		conn = d.connect("jdbc:postgresql://"+odbcServer.addr.getHostName()+":" +odbcServer.odbcTransport.getPort()+"/parts", p);
 	}
 	
 	@After public void tearDown() throws Exception {
@@ -143,6 +224,12 @@
 		TestMMDatabaseMetaData.compareResultSet(rs);
 	}	
 	
+	@Test public void testColumnMetadataWithAlias() throws Exception {
+		PreparedStatement stmt = conn.prepareStatement("select ta.attname as x from pg_catalog.pg_attribute ta limit 1");
+		ResultSet rs = stmt.executeQuery();
+		TestMMDatabaseMetaData.compareResultSet(rs);
+	}	
+	
 	@Test public void testPreparedError() throws Exception {
 		PreparedStatement stmt = conn.prepareStatement("select cast(? as integer)");
 		stmt.setString(1, "a");
@@ -176,9 +263,30 @@
 		assertEquals("oid", rs.getArray("proargtypes").getBaseTypeName());
 	}
 	
+	// this does not work as JDBC always sends the queries in prepared form
+	public void testPgDeclareCursor() throws Exception {
+		Statement stmt = conn.createStatement();
+		ResultSet rs = stmt.executeQuery("begin;declare \"foo\" cursor for select * from pg_proc;fetch 10 in \"foo\"; close \"foo\"");
+		rs.next();		
+	}	
+	
 	@Test public void testPgProcedure() throws Exception {
 		Statement stmt = conn.createStatement();
 		ResultSet rs = stmt.executeQuery("select has_function_privilege(100, 'foo')");
 		rs.next();
 	}
+	
+	@Test public void testSelectSsl() throws Exception {
+		conn.close();
+		Driver d = new Driver();
+		Properties p = new Properties();
+		p.setProperty("user", "testuser");
+		p.setProperty("password", "testpassword");
+		p.setProperty("ssl", "true");
+		p.setProperty("sslfactory", AnonSSLSocketFactory.class.getName());
+		conn = d.connect("jdbc:postgresql://"+odbcServer.addr.getHostName()+":" +odbcServer.odbcTransport.getPort()+"/parts", p);
+		Statement s = conn.createStatement();
+		assertTrue(s.execute("select * from tables order by name"));
+		TestMMDatabaseMetaData.compareResultSet("TestODBCSocketTransport/testSelect", s.getResultSet());
+	}
 }


Property changes on: branches/as7/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java:3149-3217,3281-3325
/trunk/test-integration/common/src/test/java/org/teiid/transport/TestODBCSocketTransport.java:3188-3382

Modified: branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedureColumns.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedureColumns.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedureColumns.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -43,6 +43,13 @@
 QT_Ora9DS                                                          SP                                                                 sp_rows_between                                                    ObjectValue                                                        3            2000         object                     2147483647   2048         0       10           1            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             17           YES                                                                sp_rows_between                                                  
 QT_Ora9DS                                                          SYS                                                                getXMLSchemas                                                      document                                                           1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 getXMLSchemas                                                    
 QT_Ora9DS                                                          SYS                                                                getXMLSchemas                                                      schema                                                             3            2009         xml                        2147483647   2147483647   0       10           1            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            YES                                                                getXMLSchemas                                                    
+QT_Ora9DS                                                          SYSADMIN                                                           isLoggable                                                         level                                                              1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 isLoggable                                                       
+QT_Ora9DS                                                          SYSADMIN                                                           isLoggable                                                         context                                                            1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             3            NO                                                                 isLoggable                                                       
+QT_Ora9DS                                                          SYSADMIN                                                           isLoggable                                                         loggable                                                           5            -7           boolean                    1            1            0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 isLoggable                                                       
+QT_Ora9DS                                                          SYSADMIN                                                           logMsg                                                             level                                                              1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 logMsg                                                           
+QT_Ora9DS                                                          SYSADMIN                                                           logMsg                                                             context                                                            1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             3            NO                                                                 logMsg                                                           
+QT_Ora9DS                                                          SYSADMIN                                                           logMsg                                                             msg                                                                1            2000         object                     2147483647   2147483647   0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             4            NO                                                                 logMsg                                                           
+QT_Ora9DS                                                          SYSADMIN                                                           logMsg                                                             logged                                                             5            -7           boolean                    1            1            0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 logMsg                                                           
 QT_Ora9DS                                                          SYSADMIN                                                           refreshMatView                                                     ViewName                                                           1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 refreshMatView                                                   
 QT_Ora9DS                                                          SYSADMIN                                                           refreshMatView                                                     Invalidate                                                         1            -7           boolean                    1            1            0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 refreshMatView                                                   
 QT_Ora9DS                                                          SYSADMIN                                                           refreshMatView                                                     RowsUpdated                                                        5            4            integer                    10           10           0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             3            NO                                                                 refreshMatView                                                   
@@ -61,7 +68,7 @@
 QT_Ora9DS                                                          SYSADMIN                                                           setProperty                                                        OldValue                                                           5            2005         clob                       2147483647   2097152      0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 setProperty                                                      
 QT_Ora9DS                                                          SYSADMIN                                                           setTableStats                                                      tableName                                                          1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 setTableStats                                                    
 QT_Ora9DS                                                          SYSADMIN                                                           setTableStats                                                      cardinality                                                        1            4            integer                    10           10           0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 setTableStats                                                    
-Row Count : 61
+Row Count : 68
 getColumnName      getColumnType  getCatalogName  getColumnClassName  getColumnLabel     getColumnTypeName  getSchemaName  getTableName     getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 VDBName            12             QT_Ora9DS       java.lang.String    PROCEDURE_CAT      string             SYS            ProcedureParams  255                   255           0         false            false            false       false                 0           true        true          false     false       
 SchemaName         12             QT_Ora9DS       java.lang.String    PROCEDURE_SCHEM    string             SYS            ProcedureParams  255                   255           0         false            true             false       true                  1           false       true          true      true        

Modified: branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedures.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedures.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProcedures.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -5,12 +5,14 @@
 QT_Ora9DS                                                          SP                                                                 sp_count_rows_between                                              <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               sp_count_rows_between                                            
 QT_Ora9DS                                                          SP                                                                 sp_rows_between                                                    <null>                                                             <null>                                                             <null>                                                             <null>                                                             2               sp_rows_between                                                  
 QT_Ora9DS                                                          SYS                                                                getXMLSchemas                                                      <null>                                                             <null>                                                             <null>                                                             <null>                                                             2               getXMLSchemas                                                    
+QT_Ora9DS                                                          SYSADMIN                                                           isLoggable                                                         <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               isLoggable                                                       
+QT_Ora9DS                                                          SYSADMIN                                                           logMsg                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               logMsg                                                           
 QT_Ora9DS                                                          SYSADMIN                                                           refreshMatView                                                     <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               refreshMatView                                                   
 QT_Ora9DS                                                          SYSADMIN                                                           refreshMatViewRow                                                  <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               refreshMatViewRow                                                
 QT_Ora9DS                                                          SYSADMIN                                                           setColumnStats                                                     <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setColumnStats                                                   
 QT_Ora9DS                                                          SYSADMIN                                                           setProperty                                                        <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setProperty                                                      
 QT_Ora9DS                                                          SYSADMIN                                                           setTableStats                                                      <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setTableStats                                                    
-Row Count : 10
+Row Count : 12
 getColumnName   getColumnType  getCatalogName  getColumnClassName  getColumnLabel   getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 VDBName         12             QT_Ora9DS       java.lang.String    PROCEDURE_CAT    string             SYS            Procedures    255                   255           0         false            false            false       false                 0           true        true          false     false       
 SchemaName      12             QT_Ora9DS       java.lang.String    PROCEDURE_SCHEM  string             SYS            Procedures    255                   255           0         false            true             false       true                  1           false       true          true      true        

Modified: branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProceduresWithEscape.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProceduresWithEscape.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestMMDatabaseMetaData/testGetProceduresWithEscape.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -5,12 +5,14 @@
 QT_Ora9DS                                                          SP                                                                 sp_count_rows_between                                              <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               sp_count_rows_between                                            
 QT_Ora9DS                                                          SP                                                                 sp_rows_between                                                    <null>                                                             <null>                                                             <null>                                                             <null>                                                             2               sp_rows_between                                                  
 QT_Ora9DS                                                          SYS                                                                getXMLSchemas                                                      <null>                                                             <null>                                                             <null>                                                             <null>                                                             2               getXMLSchemas                                                    
+QT_Ora9DS                                                          SYSADMIN                                                           isLoggable                                                         <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               isLoggable                                                       
+QT_Ora9DS                                                          SYSADMIN                                                           logMsg                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               logMsg                                                           
 QT_Ora9DS                                                          SYSADMIN                                                           refreshMatView                                                     <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               refreshMatView                                                   
 QT_Ora9DS                                                          SYSADMIN                                                           refreshMatViewRow                                                  <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               refreshMatViewRow                                                
 QT_Ora9DS                                                          SYSADMIN                                                           setColumnStats                                                     <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setColumnStats                                                   
 QT_Ora9DS                                                          SYSADMIN                                                           setProperty                                                        <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setProperty                                                      
 QT_Ora9DS                                                          SYSADMIN                                                           setTableStats                                                      <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setTableStats                                                    
-Row Count : 10
+Row Count : 12
 getColumnName   getColumnType  getCatalogName  getColumnClassName  getColumnLabel   getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 VDBName         12             QT_Ora9DS       java.lang.String    PROCEDURE_CAT    string             SYS            Procedures    255                   255           0         false            false            false       false                 0           true        true          false     false       
 SchemaName      12             QT_Ora9DS       java.lang.String    PROCEDURE_SCHEM  string             SYS            Procedures    255                   255           0         false            true             false       true                  1           false       true          true      true        

Modified: branches/as7/test-integration/common/src/test/resources/TestODBCSchema/test_PG_ATTRIBUTE.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestODBCSchema/test_PG_ATTRIBUTE.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestODBCSchema/test_PG_ATTRIBUTE.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,257 +1,257 @@
 integer      integer      string                                                             integer      short   short   integer      boolean     boolean       boolean  
 oid          attrelid     attname                                                            atttypid     attlen  attnum  atttypmod    attnotnull  attisdropped  atthasdef
-1            1            PART_ID                                                            1043         -1      1       4            true        false         false    
-2            1            PART_NAME                                                          1043         -1      2       255          false       false         false    
-3            1            PART_COLOR                                                         1043         -1      3       30           false       false         false    
-4            1            PART_WEIGHT                                                        1043         -1      4       255          false       false         false    
-5            2            SHIPPER_ID                                                         21           2       1       0            true        false         false    
-6            2            SHIPPER_NAME                                                       1043         -1      2       30           false       false         false    
-7            3            STATUS_ID                                                          21           2       1       0            true        false         false    
-8            3            STATUS_NAME                                                        1043         -1      2       30           false       false         false    
-9            4            SUPPLIER_ID                                                        1043         -1      1       10           true        false         false    
-10           4            PART_ID                                                            1043         -1      2       4            true        false         false    
-11           4            QUANTITY                                                           21           2       3       0            false       false         false    
-12           4            SHIPPER_ID                                                         21           2       4       0            false       false         false    
-13           5            SUPPLIER_ID                                                        1043         -1      1       10           true        false         false    
-14           5            SUPPLIER_NAME                                                      1043         -1      2       30           false       false         false    
-15           5            SUPPLIER_STATUS                                                    21           2       3       0            false       false         false    
-16           5            SUPPLIER_CITY                                                      1043         -1      4       30           false       false         false    
-17           5            SUPPLIER_STATE                                                     1043         -1      5       2            false       false         false    
-18           6            VDBName                                                            1043         -1      1       255          true        false         false    
-19           6            SchemaName                                                         1043         -1      2       255          true        false         false    
-20           6            Name                                                               1043         -1      3       255          true        false         false    
-21           6            TargetSchemaName                                                   1043         -1      4       255          false       false         false    
-22           6            TargetName                                                         1043         -1      5       4000         false       false         false    
-23           6            Valid                                                              16           1       6       0            false       false         false    
-24           6            LoadState                                                          1043         -1      7       255          false       false         false    
-25           6            Updated                                                            1114         8       8       0            false       false         false    
-26           6            Cardinality                                                        23           4       9       10           false       false         false    
-27           7            resourcePath                                                       1043         -1      1       255          false       false         false    
-28           7            contents                                                           14939        -1      2       0            false       false         false    
-29           8            VDBName                                                            1043         -1      1       255          true        false         false    
-30           8            SchemaName                                                         1043         -1      2       255          false       false         false    
-31           8            TableName                                                          1043         -1      3       255          true        false         false    
-32           8            Name                                                               1043         -1      4       255          true        false         false    
-33           8            Position                                                           23           4       5       10           true        false         false    
-34           8            NameInSource                                                       1043         -1      6       255          false       false         false    
-35           8            DataType                                                           1043         -1      7       100          true        false         false    
-36           8            Scale                                                              23           4       8       10           true        false         false    
-37           8            Length                                                             23           4       9       10           true        false         false    
-38           8            IsLengthFixed                                                      16           1       10      1            true        false         false    
-39           8            SupportsSelect                                                     16           1       11      1            true        false         false    
-40           8            SupportsUpdates                                                    16           1       12      1            true        false         false    
-41           8            IsCaseSensitive                                                    16           1       13      1            true        false         false    
-42           8            IsSigned                                                           16           1       14      1            true        false         false    
-43           8            IsCurrency                                                         16           1       15      1            true        false         false    
-44           8            IsAutoIncremented                                                  16           1       16      1            true        false         false    
-45           8            NullType                                                           1043         -1      17      20           true        false         false    
-46           8            MinRange                                                           1043         -1      18      50           false       false         false    
-47           8            MaxRange                                                           1043         -1      19      50           false       false         false    
-48           8            DistinctCount                                                      23           4       20      10           false       false         false    
-49           8            NullCount                                                          23           4       21      10           false       false         false    
-50           8            SearchType                                                         1043         -1      22      20           true        false         false    
-51           8            Format                                                             1043         -1      23      255          false       false         false    
-52           8            DefaultValue                                                       1043         -1      24      255          false       false         false    
-53           8            JavaClass                                                          1043         -1      25      500          true        false         false    
-54           8            Precision                                                          23           4       26      10           true        false         false    
-55           8            CharOctetLength                                                    23           4       27      10           false       false         false    
-56           8            Radix                                                              23           4       28      10           true        false         false    
-57           8            UID                                                                1043         -1      29      50           true        false         false    
-58           8            Description                                                        1043         -1      30      255          false       false         false    
-59           8            OID                                                                23           4       31      10           true        false         false    
-60           9            Name                                                               1043         -1      1       100          true        false         false    
-61           9            IsStandard                                                         16           1       2       1            false       false         false    
-62           9            IsPhysical                                                         16           1       3       1            false       false         false    
-63           9            TypeName                                                           1043         -1      4       100          true        false         false    
-64           9            JavaClass                                                          1043         -1      5       500          true        false         false    
-65           9            Scale                                                              23           4       6       10           false       false         false    
-66           9            TypeLength                                                         23           4       7       10           true        false         false    
-67           9            NullType                                                           1043         -1      8       20           true        false         false    
-68           9            IsSigned                                                           16           1       9       1            true        false         false    
-69           9            IsAutoIncremented                                                  16           1       10      1            true        false         false    
-70           9            IsCaseSensitive                                                    16           1       11      1            true        false         false    
-71           9            Precision                                                          23           4       12      10           true        false         false    
-72           9            Radix                                                              23           4       13      10           false       false         false    
-73           9            SearchType                                                         1043         -1      14      20           true        false         false    
-74           9            UID                                                                1043         -1      15      50           true        false         false    
-75           9            RuntimeType                                                        1043         -1      16      64           false       false         false    
-76           9            BaseType                                                           1043         -1      17      64           false       false         false    
-77           9            Description                                                        1043         -1      18      255          false       false         false    
-78           9            OID                                                                23           4       19      10           true        false         false    
-79           10           VDBName                                                            1043         -1      1       255          true        false         false    
-80           10           SchemaName                                                         1043         -1      2       255          false       false         false    
-81           10           TableName                                                          1043         -1      3       2048         true        false         false    
-82           10           Name                                                               1043         -1      4       255          true        false         false    
-83           10           KeyName                                                            1043         -1      5       255          false       false         false    
-84           10           KeyType                                                            1043         -1      6       20           true        false         false    
-85           10           RefKeyUID                                                          1043         -1      7       50           false       false         false    
-86           10           UID                                                                1043         -1      8       50           true        false         false    
-87           10           Position                                                           23           4       9       10           false       false         false    
-88           10           OID                                                                23           4       10      10           true        false         false    
-89           11           VDBName                                                            1043         -1      1       255          true        false         false    
-90           11           SchemaName                                                         1043         -1      2       255          false       false         false    
-91           11           TableName                                                          1043         -1      3       2048         true        false         false    
-92           11           Name                                                               1043         -1      4       255          true        false         false    
-93           11           Description                                                        1043         -1      5       255          false       false         false    
-94           11           NameInSource                                                       1043         -1      6       255          false       false         false    
-95           11           Type                                                               1043         -1      7       20           true        false         false    
-96           11           IsIndexed                                                          16           1       8       1            true        false         false    
-97           11           RefKeyUID                                                          1043         -1      9       50           false       false         false    
-98           11           UID                                                                1043         -1      10      50           true        false         false    
-99           11           OID                                                                23           4       11      10           true        false         false    
-100          12           VDBName                                                            1043         -1      1       255          true        false         false    
-101          12           SchemaName                                                         1043         -1      2       255          false       false         false    
-102          12           ProcedureName                                                      1043         -1      3       255          true        false         false    
-103          12           Name                                                               1043         -1      4       255          true        false         false    
-104          12           DataType                                                           1043         -1      5       25           true        false         false    
-105          12           Position                                                           23           4       6       10           true        false         false    
-106          12           Type                                                               1043         -1      7       100          true        false         false    
-107          12           Optional                                                           16           1       8       1            true        false         false    
-108          12           Precision                                                          23           4       9       10           true        false         false    
-109          12           TypeLength                                                         23           4       10      10           true        false         false    
-110          12           Scale                                                              23           4       11      10           true        false         false    
-111          12           Radix                                                              23           4       12      10           true        false         false    
-112          12           NullType                                                           1043         -1      13      10           true        false         false    
-113          12           UID                                                                1043         -1      14      50           false       false         false    
-114          12           Description                                                        1043         -1      15      255          false       false         false    
-115          12           OID                                                                23           4       16      10           true        false         false    
-116          13           VDBName                                                            1043         -1      1       255          true        false         false    
-117          13           SchemaName                                                         1043         -1      2       255          false       false         false    
-118          13           Name                                                               1043         -1      3       255          true        false         false    
-119          13           NameInSource                                                       1043         -1      4       255          false       false         false    
-120          13           ReturnsResults                                                     16           1       5       1            true        false         false    
-121          13           UID                                                                1043         -1      6       50           true        false         false    
-122          13           Description                                                        1043         -1      7       255          false       false         false    
-123          13           OID                                                                23           4       8       10           true        false         false    
-124          14           Name                                                               1043         -1      1       255          true        false         false    
-125          14           Value                                                              1043         -1      2       255          true        false         false    
-126          14           UID                                                                1043         -1      3       50           true        false         false    
-127          14           OID                                                                23           4       4       10           true        false         false    
-128          14           ClobValue                                                          14939        -1      5       2097152      false       false         false    
-129          15           PKTABLE_CAT                                                        1043         -1      1       255          false       false         false    
-130          15           PKTABLE_SCHEM                                                      1043         -1      2       255          false       false         false    
-131          15           PKTABLE_NAME                                                       1043         -1      3       255          false       false         false    
-132          15           PKCOLUMN_NAME                                                      1043         -1      4       255          false       false         false    
-133          15           FKTABLE_CAT                                                        1043         -1      5       255          false       false         false    
-134          15           FKTABLE_SCHEM                                                      1043         -1      6       255          false       false         false    
-135          15           FKTABLE_NAME                                                       1043         -1      7       255          false       false         false    
-136          15           FKCOLUMN_NAME                                                      1043         -1      8       255          false       false         false    
-137          15           KEY_SEQ                                                            21           2       9       5            false       false         false    
-138          15           UPDATE_RULE                                                        23           4       10      10           false       false         false    
-139          15           DELETE_RULE                                                        23           4       11      10           false       false         false    
-140          15           FK_NAME                                                            1043         -1      12      255          false       false         false    
-141          15           PK_NAME                                                            1043         -1      13      255          false       false         false    
-142          15           DEFERRABILITY                                                      23           4       14      10           false       false         false    
-143          16           VDBName                                                            1043         -1      1       255          false       false         false    
-144          16           Name                                                               1043         -1      2       255          false       false         false    
-145          16           IsPhysical                                                         16           1       3       1            true        false         false    
-146          16           UID                                                                1043         -1      4       50           true        false         false    
-147          16           Description                                                        1043         -1      5       255          false       false         false    
-148          16           PrimaryMetamodelURI                                                1043         -1      6       255          true        false         false    
-149          16           OID                                                                23           4       7       10           true        false         false    
-150          17           VDBName                                                            1043         -1      1       255          false       false         false    
-151          17           SchemaName                                                         1043         -1      2       255          false       false         false    
-152          17           Name                                                               1043         -1      3       255          true        false         false    
-153          17           Type                                                               1043         -1      4       20           true        false         false    
-154          17           NameInSource                                                       1043         -1      5       255          false       false         false    
-155          17           IsPhysical                                                         16           1       6       1            true        false         false    
-156          17           SupportsUpdates                                                    16           1       7       1            true        false         false    
-157          17           UID                                                                1043         -1      8       50           true        false         false    
-158          17           Cardinality                                                        23           4       9       10           true        false         false    
-159          17           Description                                                        1043         -1      10      255          false       false         false    
-160          17           IsSystem                                                           16           1       11      1            false       false         false    
-161          17           IsMaterialized                                                     16           1       12      0            true        false         false    
-162          17           OID                                                                23           4       13      10           true        false         false    
-163          18           Name                                                               1043         -1      1       255          true        false         false    
-164          18           Version                                                            1043         -1      2       50           true        false         false    
-165          19           oid                                                                23           4       1       0            false       false         false    
-166          19           nspname                                                            1043         -1      2       0            false       false         false    
-167          20           oid                                                                23           4       1       0            false       false         false    
-168          20           relname                                                            1043         -1      2       0            false       false         false    
-169          20           relnamespace                                                       23           4       3       0            false       false         false    
-170          20           relkind                                                            1042         1       4       0            false       false         false    
-171          20           relam                                                              23           4       5       0            false       false         false    
-172          20           reltuples                                                          700          4       6       0            false       false         false    
-173          20           relpages                                                           23           4       7       0            false       false         false    
-174          20           relhasrules                                                        16           1       8       0            false       false         false    
-175          20           relhasoids                                                         16           1       9       0            false       false         false    
-176          21           oid                                                                23           4       1       0            false       false         false    
-177          21           attrelid                                                           23           4       2       0            false       false         false    
-178          21           attname                                                            1043         -1      3       0            false       false         false    
-179          21           atttypid                                                           23           4       4       0            false       false         false    
-180          21           attlen                                                             21           2       5       0            false       false         false    
-181          21           attnum                                                             21           2       6       0            false       false         false    
-182          21           atttypmod                                                          23           4       7       0            false       false         false    
-183          21           attnotnull                                                         16           1       8       0            false       false         false    
-184          21           attisdropped                                                       16           1       9       0            false       false         false    
-185          21           atthasdef                                                          16           1       10      0            false       false         false    
-186          22           oid                                                                23           4       1       0            false       false         false    
-187          22           typname                                                            1043         -1      2       0            false       false         false    
-188          22           typnamespace                                                       23           4       3       0            false       false         false    
-189          22           typlen                                                             21           2       4       0            false       false         false    
-190          22           typtype                                                            1042         1       5       0            false       false         false    
-191          22           typbasetype                                                        23           4       6       0            false       false         false    
-192          22           typtypmod                                                          23           4       7       0            false       false         false    
-193          22           typrelid                                                           23           4       8       0            false       false         false    
-194          22           typelem                                                            23           4       9       0            false       false         false    
-195          23           oid                                                                23           4       1       0            false       false         false    
-196          23           indexrelid                                                         23           4       2       0            false       false         false    
-197          23           indrelid                                                           23           4       3       0            false       false         false    
-198          23           indisclustered                                                     16           1       4       0            false       false         false    
-199          23           indisunique                                                        16           1       5       0            false       false         false    
-200          23           indisprimary                                                       16           1       6       0            false       false         false    
-201          23           indexprs                                                           1043         -1      7       0            false       false         false    
-202          23           indkey                                                             1043         -1      8       0            false       false         false    
-203          24           oid                                                                23           4       1       0            false       false         false    
-204          24           amname                                                             1043         -1      2       0            false       false         false    
-205          25           oid                                                                23           4       1       0            false       false         false    
-206          25           proname                                                            1043         -1      2       0            false       false         false    
-207          25           proretset                                                          16           1       3       0            false       false         false    
-208          25           prorettype                                                         23           4       4       0            false       false         false    
-209          25           pronargs                                                           21           2       5       0            false       false         false    
-210          25           proargtypes                                                        <null>       <null>  6       0            false       false         false    
-211          25           proargnames                                                        <null>       <null>  7       0            false       false         false    
-212          25           proargmodes                                                        <null>       <null>  8       0            false       false         false    
-213          25           proallargtypes                                                     <null>       <null>  9       0            false       false         false    
-214          25           pronamespace                                                       23           4       10      0            false       false         false    
-215          26           oid                                                                23           4       1       0            false       false         false    
-216          26           tgconstrrelid                                                      23           4       2       0            false       false         false    
-217          26           tgfoid                                                             23           4       3       0            false       false         false    
-218          26           tgargs                                                             23           4       4       0            false       false         false    
-219          26           tgnargs                                                            23           4       5       0            false       false         false    
-220          26           tgdeferrable                                                       16           1       6       0            false       false         false    
-221          26           tginitdeferred                                                     16           1       7       0            false       false         false    
-222          26           tgconstrname                                                       1043         -1      8       0            false       false         false    
-223          26           tgrelid                                                            23           4       9       0            false       false         false    
-224          27           adrelid                                                            23           4       1       0            false       false         false    
-225          27           adnum                                                              23           4       2       0            false       false         false    
-226          27           adbin                                                              1043         -1      3       0            false       false         false    
-227          27           adsrc                                                              1043         -1      4       0            false       false         false    
-228          28           oid                                                                23           4       1       0            false       false         false    
-229          28           datname                                                            1043         -1      2       0            false       false         false    
-230          28           encoding                                                           23           4       3       0            false       false         false    
-231          28           datlastsysoid                                                      23           4       4       0            false       false         false    
-232          28           datallowconn                                                       1042         1       5       0            false       false         false    
-233          28           datconfig                                                          <null>       <null>  6       0            false       false         false    
-234          28           datacl                                                             <null>       <null>  7       0            false       false         false    
-235          28           datdba                                                             23           4       8       0            false       false         false    
-236          28           dattablespace                                                      23           4       9       0            false       false         false    
-237          29           oid                                                                23           4       1       0            false       false         false    
-238          29           usename                                                            1043         -1      2       0            false       false         false    
-239          29           usecreatedb                                                        16           1       3       0            false       false         false    
-240          29           usesuper                                                           16           1       4       0            false       false         false    
-241          30           attrelid                                                           23           4       1       0            false       false         false    
-242          30           attnum                                                             21           2       2       0            false       false         false    
-243          30           attname                                                            1043         -1      3       0            false       false         false    
-244          30           relname                                                            1043         -1      4       0            false       false         false    
-245          30           nspname                                                            1043         -1      5       0            false       false         false    
-246          30           autoinc                                                            16           1       6       0            false       false         false    
-247          30           typoid                                                             23           4       7       0            false       false         false    
-248          31           oid                                                                23           4       1       0            false       false         false    
-249          31           typname                                                            1043         -1      2       0            false       false         false    
-250          31           name                                                               1043         -1      3       0            false       false         false    
-251          31           uid                                                                1043         -1      4       0            false       false         false    
-252          31           typlen                                                             21           2       5       0            false       false         false    
+1            1            PART_ID                                                            1043         -1      1       8            true        false         false    
+2            1            PART_NAME                                                          1043         -1      2       259          false       false         false    
+3            1            PART_COLOR                                                         1043         -1      3       34           false       false         false    
+4            1            PART_WEIGHT                                                        1043         -1      4       259          false       false         false    
+5            2            SHIPPER_ID                                                         21           2       1       4            true        false         false    
+6            2            SHIPPER_NAME                                                       1043         -1      2       34           false       false         false    
+7            3            STATUS_ID                                                          21           2       1       4            true        false         false    
+8            3            STATUS_NAME                                                        1043         -1      2       34           false       false         false    
+9            4            SUPPLIER_ID                                                        1043         -1      1       14           true        false         false    
+10           4            PART_ID                                                            1043         -1      2       8            true        false         false    
+11           4            QUANTITY                                                           21           2       3       4            false       false         false    
+12           4            SHIPPER_ID                                                         21           2       4       4            false       false         false    
+13           5            SUPPLIER_ID                                                        1043         -1      1       14           true        false         false    
+14           5            SUPPLIER_NAME                                                      1043         -1      2       34           false       false         false    
+15           5            SUPPLIER_STATUS                                                    21           2       3       4            false       false         false    
+16           5            SUPPLIER_CITY                                                      1043         -1      4       34           false       false         false    
+17           5            SUPPLIER_STATE                                                     1043         -1      5       6            false       false         false    
+18           6            VDBName                                                            1043         -1      1       259          true        false         false    
+19           6            SchemaName                                                         1043         -1      2       259          true        false         false    
+20           6            Name                                                               1043         -1      3       259          true        false         false    
+21           6            TargetSchemaName                                                   1043         -1      4       259          false       false         false    
+22           6            TargetName                                                         1043         -1      5       4004         false       false         false    
+23           6            Valid                                                              16           1       6       4            false       false         false    
+24           6            LoadState                                                          1043         -1      7       259          false       false         false    
+25           6            Updated                                                            1114         8       8       4            false       false         false    
+26           6            Cardinality                                                        23           4       9       14           false       false         false    
+27           7            resourcePath                                                       1043         -1      1       259          false       false         false    
+28           7            contents                                                           14939        -1      2       4            false       false         false    
+29           8            VDBName                                                            1043         -1      1       259          true        false         false    
+30           8            SchemaName                                                         1043         -1      2       259          false       false         false    
+31           8            TableName                                                          1043         -1      3       259          true        false         false    
+32           8            Name                                                               1043         -1      4       259          true        false         false    
+33           8            Position                                                           23           4       5       14           true        false         false    
+34           8            NameInSource                                                       1043         -1      6       259          false       false         false    
+35           8            DataType                                                           1043         -1      7       104          true        false         false    
+36           8            Scale                                                              23           4       8       14           true        false         false    
+37           8            Length                                                             23           4       9       14           true        false         false    
+38           8            IsLengthFixed                                                      16           1       10      5            true        false         false    
+39           8            SupportsSelect                                                     16           1       11      5            true        false         false    
+40           8            SupportsUpdates                                                    16           1       12      5            true        false         false    
+41           8            IsCaseSensitive                                                    16           1       13      5            true        false         false    
+42           8            IsSigned                                                           16           1       14      5            true        false         false    
+43           8            IsCurrency                                                         16           1       15      5            true        false         false    
+44           8            IsAutoIncremented                                                  16           1       16      5            true        false         false    
+45           8            NullType                                                           1043         -1      17      24           true        false         false    
+46           8            MinRange                                                           1043         -1      18      54           false       false         false    
+47           8            MaxRange                                                           1043         -1      19      54           false       false         false    
+48           8            DistinctCount                                                      23           4       20      14           false       false         false    
+49           8            NullCount                                                          23           4       21      14           false       false         false    
+50           8            SearchType                                                         1043         -1      22      24           true        false         false    
+51           8            Format                                                             1043         -1      23      259          false       false         false    
+52           8            DefaultValue                                                       1043         -1      24      259          false       false         false    
+53           8            JavaClass                                                          1043         -1      25      504          true        false         false    
+54           8            Precision                                                          23           4       26      14           true        false         false    
+55           8            CharOctetLength                                                    23           4       27      14           false       false         false    
+56           8            Radix                                                              23           4       28      14           true        false         false    
+57           8            UID                                                                1043         -1      29      54           true        false         false    
+58           8            Description                                                        1043         -1      30      259          false       false         false    
+59           8            OID                                                                23           4       31      14           true        false         false    
+60           9            Name                                                               1043         -1      1       104          true        false         false    
+61           9            IsStandard                                                         16           1       2       5            false       false         false    
+62           9            IsPhysical                                                         16           1       3       5            false       false         false    
+63           9            TypeName                                                           1043         -1      4       104          true        false         false    
+64           9            JavaClass                                                          1043         -1      5       504          true        false         false    
+65           9            Scale                                                              23           4       6       14           false       false         false    
+66           9            TypeLength                                                         23           4       7       14           true        false         false    
+67           9            NullType                                                           1043         -1      8       24           true        false         false    
+68           9            IsSigned                                                           16           1       9       5            true        false         false    
+69           9            IsAutoIncremented                                                  16           1       10      5            true        false         false    
+70           9            IsCaseSensitive                                                    16           1       11      5            true        false         false    
+71           9            Precision                                                          23           4       12      14           true        false         false    
+72           9            Radix                                                              23           4       13      14           false       false         false    
+73           9            SearchType                                                         1043         -1      14      24           true        false         false    
+74           9            UID                                                                1043         -1      15      54           true        false         false    
+75           9            RuntimeType                                                        1043         -1      16      68           false       false         false    
+76           9            BaseType                                                           1043         -1      17      68           false       false         false    
+77           9            Description                                                        1043         -1      18      259          false       false         false    
+78           9            OID                                                                23           4       19      14           true        false         false    
+79           10           VDBName                                                            1043         -1      1       259          true        false         false    
+80           10           SchemaName                                                         1043         -1      2       259          false       false         false    
+81           10           TableName                                                          1043         -1      3       2052         true        false         false    
+82           10           Name                                                               1043         -1      4       259          true        false         false    
+83           10           KeyName                                                            1043         -1      5       259          false       false         false    
+84           10           KeyType                                                            1043         -1      6       24           true        false         false    
+85           10           RefKeyUID                                                          1043         -1      7       54           false       false         false    
+86           10           UID                                                                1043         -1      8       54           true        false         false    
+87           10           Position                                                           23           4       9       14           false       false         false    
+88           10           OID                                                                23           4       10      14           true        false         false    
+89           11           VDBName                                                            1043         -1      1       259          true        false         false    
+90           11           SchemaName                                                         1043         -1      2       259          false       false         false    
+91           11           TableName                                                          1043         -1      3       2052         true        false         false    
+92           11           Name                                                               1043         -1      4       259          true        false         false    
+93           11           Description                                                        1043         -1      5       259          false       false         false    
+94           11           NameInSource                                                       1043         -1      6       259          false       false         false    
+95           11           Type                                                               1043         -1      7       24           true        false         false    
+96           11           IsIndexed                                                          16           1       8       5            true        false         false    
+97           11           RefKeyUID                                                          1043         -1      9       54           false       false         false    
+98           11           UID                                                                1043         -1      10      54           true        false         false    
+99           11           OID                                                                23           4       11      14           true        false         false    
+100          12           VDBName                                                            1043         -1      1       259          true        false         false    
+101          12           SchemaName                                                         1043         -1      2       259          false       false         false    
+102          12           ProcedureName                                                      1043         -1      3       259          true        false         false    
+103          12           Name                                                               1043         -1      4       259          true        false         false    
+104          12           DataType                                                           1043         -1      5       29           true        false         false    
+105          12           Position                                                           23           4       6       14           true        false         false    
+106          12           Type                                                               1043         -1      7       104          true        false         false    
+107          12           Optional                                                           16           1       8       5            true        false         false    
+108          12           Precision                                                          23           4       9       14           true        false         false    
+109          12           TypeLength                                                         23           4       10      14           true        false         false    
+110          12           Scale                                                              23           4       11      14           true        false         false    
+111          12           Radix                                                              23           4       12      14           true        false         false    
+112          12           NullType                                                           1043         -1      13      14           true        false         false    
+113          12           UID                                                                1043         -1      14      54           false       false         false    
+114          12           Description                                                        1043         -1      15      259          false       false         false    
+115          12           OID                                                                23           4       16      14           true        false         false    
+116          13           VDBName                                                            1043         -1      1       259          true        false         false    
+117          13           SchemaName                                                         1043         -1      2       259          false       false         false    
+118          13           Name                                                               1043         -1      3       259          true        false         false    
+119          13           NameInSource                                                       1043         -1      4       259          false       false         false    
+120          13           ReturnsResults                                                     16           1       5       5            true        false         false    
+121          13           UID                                                                1043         -1      6       54           true        false         false    
+122          13           Description                                                        1043         -1      7       259          false       false         false    
+123          13           OID                                                                23           4       8       14           true        false         false    
+124          14           Name                                                               1043         -1      1       259          true        false         false    
+125          14           Value                                                              1043         -1      2       259          true        false         false    
+126          14           UID                                                                1043         -1      3       54           true        false         false    
+127          14           OID                                                                23           4       4       14           true        false         false    
+128          14           ClobValue                                                          14939        -1      5       2097156      false       false         false    
+129          15           PKTABLE_CAT                                                        1043         -1      1       259          false       false         false    
+130          15           PKTABLE_SCHEM                                                      1043         -1      2       259          false       false         false    
+131          15           PKTABLE_NAME                                                       1043         -1      3       259          false       false         false    
+132          15           PKCOLUMN_NAME                                                      1043         -1      4       259          false       false         false    
+133          15           FKTABLE_CAT                                                        1043         -1      5       259          false       false         false    
+134          15           FKTABLE_SCHEM                                                      1043         -1      6       259          false       false         false    
+135          15           FKTABLE_NAME                                                       1043         -1      7       259          false       false         false    
+136          15           FKCOLUMN_NAME                                                      1043         -1      8       259          false       false         false    
+137          15           KEY_SEQ                                                            21           2       9       9            false       false         false    
+138          15           UPDATE_RULE                                                        23           4       10      14           false       false         false    
+139          15           DELETE_RULE                                                        23           4       11      14           false       false         false    
+140          15           FK_NAME                                                            1043         -1      12      259          false       false         false    
+141          15           PK_NAME                                                            1043         -1      13      259          false       false         false    
+142          15           DEFERRABILITY                                                      23           4       14      14           false       false         false    
+143          16           VDBName                                                            1043         -1      1       259          false       false         false    
+144          16           Name                                                               1043         -1      2       259          false       false         false    
+145          16           IsPhysical                                                         16           1       3       5            true        false         false    
+146          16           UID                                                                1043         -1      4       54           true        false         false    
+147          16           Description                                                        1043         -1      5       259          false       false         false    
+148          16           PrimaryMetamodelURI                                                1043         -1      6       259          true        false         false    
+149          16           OID                                                                23           4       7       14           true        false         false    
+150          17           VDBName                                                            1043         -1      1       259          false       false         false    
+151          17           SchemaName                                                         1043         -1      2       259          false       false         false    
+152          17           Name                                                               1043         -1      3       259          true        false         false    
+153          17           Type                                                               1043         -1      4       24           true        false         false    
+154          17           NameInSource                                                       1043         -1      5       259          false       false         false    
+155          17           IsPhysical                                                         16           1       6       5            true        false         false    
+156          17           SupportsUpdates                                                    16           1       7       5            true        false         false    
+157          17           UID                                                                1043         -1      8       54           true        false         false    
+158          17           Cardinality                                                        23           4       9       14           true        false         false    
+159          17           Description                                                        1043         -1      10      259          false       false         false    
+160          17           IsSystem                                                           16           1       11      5            false       false         false    
+161          17           IsMaterialized                                                     16           1       12      4            true        false         false    
+162          17           OID                                                                23           4       13      14           true        false         false    
+163          18           Name                                                               1043         -1      1       259          true        false         false    
+164          18           Version                                                            1043         -1      2       54           true        false         false    
+165          19           oid                                                                23           4       1       4            false       false         false    
+166          19           nspname                                                            1043         -1      2       4            false       false         false    
+167          20           oid                                                                23           4       1       4            false       false         false    
+168          20           relname                                                            1043         -1      2       4            false       false         false    
+169          20           relnamespace                                                       23           4       3       4            false       false         false    
+170          20           relkind                                                            1042         1       4       4            false       false         false    
+171          20           relam                                                              23           4       5       4            false       false         false    
+172          20           reltuples                                                          700          4       6       4            false       false         false    
+173          20           relpages                                                           23           4       7       4            false       false         false    
+174          20           relhasrules                                                        16           1       8       4            false       false         false    
+175          20           relhasoids                                                         16           1       9       4            false       false         false    
+176          21           oid                                                                23           4       1       4            false       false         false    
+177          21           attrelid                                                           23           4       2       4            false       false         false    
+178          21           attname                                                            1043         -1      3       4            false       false         false    
+179          21           atttypid                                                           23           4       4       4            false       false         false    
+180          21           attlen                                                             21           2       5       4            false       false         false    
+181          21           attnum                                                             21           2       6       4            false       false         false    
+182          21           atttypmod                                                          23           4       7       4            false       false         false    
+183          21           attnotnull                                                         16           1       8       4            false       false         false    
+184          21           attisdropped                                                       16           1       9       4            false       false         false    
+185          21           atthasdef                                                          16           1       10      4            false       false         false    
+186          22           oid                                                                23           4       1       4            false       false         false    
+187          22           typname                                                            1043         -1      2       4            false       false         false    
+188          22           typnamespace                                                       23           4       3       4            false       false         false    
+189          22           typlen                                                             21           2       4       4            false       false         false    
+190          22           typtype                                                            1042         1       5       4            false       false         false    
+191          22           typbasetype                                                        23           4       6       4            false       false         false    
+192          22           typtypmod                                                          23           4       7       4            false       false         false    
+193          22           typrelid                                                           23           4       8       4            false       false         false    
+194          22           typelem                                                            23           4       9       4            false       false         false    
+195          23           oid                                                                23           4       1       4            false       false         false    
+196          23           indexrelid                                                         23           4       2       4            false       false         false    
+197          23           indrelid                                                           23           4       3       4            false       false         false    
+198          23           indisclustered                                                     16           1       4       4            false       false         false    
+199          23           indisunique                                                        16           1       5       4            false       false         false    
+200          23           indisprimary                                                       16           1       6       4            false       false         false    
+201          23           indexprs                                                           1043         -1      7       4            false       false         false    
+202          23           indkey                                                             1043         -1      8       4            false       false         false    
+203          24           oid                                                                23           4       1       4            false       false         false    
+204          24           amname                                                             1043         -1      2       4            false       false         false    
+205          25           oid                                                                23           4       1       4            false       false         false    
+206          25           proname                                                            1043         -1      2       4            false       false         false    
+207          25           proretset                                                          16           1       3       4            false       false         false    
+208          25           prorettype                                                         23           4       4       4            false       false         false    
+209          25           pronargs                                                           21           2       5       4            false       false         false    
+210          25           proargtypes                                                        <null>       <null>  6       4            false       false         false    
+211          25           proargnames                                                        <null>       <null>  7       4            false       false         false    
+212          25           proargmodes                                                        <null>       <null>  8       4            false       false         false    
+213          25           proallargtypes                                                     <null>       <null>  9       4            false       false         false    
+214          25           pronamespace                                                       23           4       10      4            false       false         false    
+215          26           oid                                                                23           4       1       4            false       false         false    
+216          26           tgconstrrelid                                                      23           4       2       4            false       false         false    
+217          26           tgfoid                                                             23           4       3       4            false       false         false    
+218          26           tgargs                                                             23           4       4       4            false       false         false    
+219          26           tgnargs                                                            23           4       5       4            false       false         false    
+220          26           tgdeferrable                                                       16           1       6       4            false       false         false    
+221          26           tginitdeferred                                                     16           1       7       4            false       false         false    
+222          26           tgconstrname                                                       1043         -1      8       4            false       false         false    
+223          26           tgrelid                                                            23           4       9       4            false       false         false    
+224          27           adrelid                                                            23           4       1       4            false       false         false    
+225          27           adnum                                                              23           4       2       4            false       false         false    
+226          27           adbin                                                              1043         -1      3       4            false       false         false    
+227          27           adsrc                                                              1043         -1      4       4            false       false         false    
+228          28           oid                                                                23           4       1       4            false       false         false    
+229          28           datname                                                            1043         -1      2       4            false       false         false    
+230          28           encoding                                                           23           4       3       4            false       false         false    
+231          28           datlastsysoid                                                      23           4       4       4            false       false         false    
+232          28           datallowconn                                                       1042         1       5       4            false       false         false    
+233          28           datconfig                                                          <null>       <null>  6       4            false       false         false    
+234          28           datacl                                                             <null>       <null>  7       4            false       false         false    
+235          28           datdba                                                             23           4       8       4            false       false         false    
+236          28           dattablespace                                                      23           4       9       4            false       false         false    
+237          29           oid                                                                23           4       1       4            false       false         false    
+238          29           usename                                                            1043         -1      2       4            false       false         false    
+239          29           usecreatedb                                                        16           1       3       4            false       false         false    
+240          29           usesuper                                                           16           1       4       4            false       false         false    
+241          30           attrelid                                                           23           4       1       4            false       false         false    
+242          30           attnum                                                             21           2       2       4            false       false         false    
+243          30           attname                                                            1043         -1      3       4            false       false         false    
+244          30           relname                                                            1043         -1      4       4            false       false         false    
+245          30           nspname                                                            1043         -1      5       4            false       false         false    
+246          30           autoinc                                                            16           1       6       4            false       false         false    
+247          30           typoid                                                             23           4       7       4            false       false         false    
+248          31           oid                                                                23           4       1       4            false       false         false    
+249          31           typname                                                            1043         -1      2       4            false       false         false    
+250          31           name                                                               1043         -1      3       4            false       false         false    
+251          31           uid                                                                1043         -1      4       4            false       false         false    
+252          31           typlen                                                             21           2       5       4            false       false         false    
 Row Count : 252
 getColumnName  getColumnType  getCatalogName  getColumnClassName  getColumnLabel  getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 oid            4              PartsSupplier   java.lang.Integer   oid             integer            pg_catalog     pg_attribute  11                    10            0         false            false            false       false                 2           true        true          false     false       

Copied: branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testColumnMetadataWithAlias.expected (from rev 3382, trunk/test-integration/common/src/test/resources/TestODBCSocketTransport/testColumnMetadataWithAlias.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testColumnMetadataWithAlias.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testColumnMetadataWithAlias.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,6 @@
+varchar                                                          
+x                                                                
+PART_ID                                                          
+Row Count : 1
+getColumnName  getColumnType  getCatalogName  getColumnClassName  getColumnLabel  getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
+x              12                             java.lang.String    x               varchar                                         2147483647            0             0         false            true             false       false                 1           false       true          false     true        

Modified: branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPk.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPk.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPk.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,10 +1,10 @@
 varchar                                                            int2    varchar                                                            varchar                                                            varchar                                                          
-name                                                               attnum  tablename                                                          schemaname                                                         tablename                                                        
+attname                                                            attnum  relname                                                            nspname                                                            relname                                                          
 oid                                                                1       pg_attribute                                                       pg_catalog                                                         pg_attribute                                                     
 Row Count : 1
 getColumnName  getColumnType  getCatalogName  getColumnClassName  getColumnLabel  getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
-name           12                             java.lang.String    name            varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
+attname        12                             java.lang.String    attname         varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
 attnum         5                              java.lang.Integer   attnum          int2                                            6                     5             0         false            false            false       false                 2           false       true          true      true        
-tablename      12                             java.lang.String    tablename       varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
-schemaname     12                             java.lang.String    schemaname      varchar                                         2147483647            0             0         false            true             false       false                 1           false       true          false     true        
-tablename      12                             java.lang.String    tablename       varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
+relname        12                             java.lang.String    relname         varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
+nspname        12                             java.lang.String    nspname         varchar                                         2147483647            0             0         false            true             false       false                 1           false       true          false     true        
+relname        12                             java.lang.String    relname         varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        


Property changes on: branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPk.expected
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/test-integration/common/src/test/resources/TestODBCSocketTransport/testPk.expected:3281-3325
/trunk/test-integration/common/src/test/resources/TestODBCSocketTransport/testPk.expected:3188-3382

Modified: branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPkPrepared.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPkPrepared.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPkPrepared.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,10 +1,10 @@
 varchar                                                            int2    varchar                                                            varchar                                                            varchar                                                          
-name                                                               attnum  tablename                                                          schemaname                                                         tablename                                                        
+attname                                                            attnum  relname                                                            nspname                                                            relname                                                          
 oid                                                                1       pg_attribute                                                       pg_catalog                                                         pg_attribute                                                     
 Row Count : 1
 getColumnName  getColumnType  getCatalogName  getColumnClassName  getColumnLabel  getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
-name           12                             java.lang.String    name            varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
+attname        12                             java.lang.String    attname         varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
 attnum         5                              java.lang.Integer   attnum          int2                                            6                     5             0         false            false            false       false                 2           false       true          true      true        
-tablename      12                             java.lang.String    tablename       varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
-schemaname     12                             java.lang.String    schemaname      varchar                                         2147483647            0             0         false            true             false       false                 1           false       true          false     true        
-tablename      12                             java.lang.String    tablename       varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
+relname        12                             java.lang.String    relname         varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        
+nspname        12                             java.lang.String    nspname         varchar                                         2147483647            0             0         false            true             false       false                 1           false       true          false     true        
+relname        12                             java.lang.String    relname         varchar                                         2147483647            0             0         false            true             false       false                 0           false       true          false     true        


Property changes on: branches/as7/test-integration/common/src/test/resources/TestODBCSocketTransport/testPkPrepared.expected
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/test-integration/common/src/test/resources/TestODBCSocketTransport/testPkPrepared.expected:3281-3325
/trunk/test-integration/common/src/test/resources/TestODBCSocketTransport/testPkPrepared.expected:3188-3382

Modified: branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedureColumns.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedureColumns.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedureColumns.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -2,6 +2,13 @@
 VDBName                                                            SchemaName                                                         ProcedureName                                                      Name                                                               COLUMN_TYPE  DATA_TYPE    DataType                   PRECISION    LENGTH       SCALE   Radix        NULLABLE     Description                                                        COLUMN_DEF                                                         SQL_DATA_TYPE                                                      SQL_DATETIME_SUB                                                   CHAR_OCTET_LENGTH                                                  Position     IS_NULLABLE                                                        ProcedureName                                                    
 PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      document                                                           1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 getXMLSchemas                                                    
 PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      schema                                                             3            2009         xml                        2147483647   2147483647   0       10           1            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            YES                                                                getXMLSchemas                                                    
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         level                                                              1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 isLoggable                                                       
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         context                                                            1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             3            NO                                                                 isLoggable                                                       
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         loggable                                                           5            -7           boolean                    1            1            0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 isLoggable                                                       
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             level                                                              1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 logMsg                                                           
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             context                                                            1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             3            NO                                                                 logMsg                                                           
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             msg                                                                1            2000         object                     2147483647   2147483647   0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             4            NO                                                                 logMsg                                                           
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             logged                                                             5            -7           boolean                    1            1            0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 logMsg                                                           
 PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     ViewName                                                           1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 refreshMatView                                                   
 PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     Invalidate                                                         1            -7           boolean                    1            1            0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 refreshMatView                                                   
 PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     RowsUpdated                                                        5            4            integer                    10           10           0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             3            NO                                                                 refreshMatView                                                   
@@ -20,7 +27,7 @@
 PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        OldValue                                                           5            2005         clob                       2147483647   2097152      0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 setProperty                                                      
 PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      tableName                                                          1            12           string                     4000         4000         0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1            NO                                                                 setTableStats                                                    
 PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      cardinality                                                        1            4            integer                    10           10           0       10           0            <null>                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             2            NO                                                                 setTableStats                                                    
-Row Count : 20
+Row Count : 27
 getColumnName      getColumnType  getCatalogName  getColumnClassName  getColumnLabel     getColumnTypeName  getSchemaName  getTableName     getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 VDBName            12             PartsSupplier   java.lang.String    PROCEDURE_CAT      string             SYS            ProcedureParams  255                   255           0         false            false            false       false                 0           true        true          false     false       
 SchemaName         12             PartsSupplier   java.lang.String    PROCEDURE_SCHEM    string             SYS            ProcedureParams  255                   255           0         false            true             false       true                  1           false       true          true      true        

Modified: branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedures.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedures.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestPartsDatabaseMetadata/testProcedures.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,12 +1,14 @@
 string                                                             string                                                             string                                                             string                                                             string                                                             string                                                             string                                                             short           string                                                           
 VDBName                                                            SchemaName                                                         Name                                                               RESERVED_1                                                         RESERVED_2                                                         RESERVED_3                                                         Description                                                        PROCEDURE_TYPE  Name                                                             
 PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      <null>                                                             <null>                                                             <null>                                                             <null>                                                             2               getXMLSchemas                                                    
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               isLoggable                                                       
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               logMsg                                                           
 PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               refreshMatView                                                   
 PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               refreshMatViewRow                                                
 PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setColumnStats                                                   
 PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setProperty                                                      
 PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      <null>                                                             <null>                                                             <null>                                                             <null>                                                             1               setTableStats                                                    
-Row Count : 6
+Row Count : 8
 getColumnName   getColumnType  getCatalogName  getColumnClassName  getColumnLabel   getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 VDBName         12             PartsSupplier   java.lang.String    PROCEDURE_CAT    string             SYS            Procedures    255                   255           0         false            false            false       false                 0           true        true          false     false       
 SchemaName      12             PartsSupplier   java.lang.String    PROCEDURE_SCHEM  string             SYS            Procedures    255                   255           0         false            true             false       true                  1           false       true          true      true        

Modified: branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedureParams.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedureParams.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedureParams.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,26 +1,33 @@
 string                                                             string                                                             string                                                             string                                                             string                     integer      string                                                             boolean   integer      integer      integer      integer      string      string                                              string                                                             integer    
 VDBName                                                            SchemaName                                                         ProcedureName                                                      Name                                                               DataType                   Position     Type                                                               Optional  Precision    TypeLength   Scale        Radix        NullType    UID                                                 Description                                                        OID        
-PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     Invalidate                                                         boolean                    2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:5736cfd3-750f-42d8-b083-102061e11c60         <null>                                                             5          
-PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  Key                                                                object                     2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:7af5a63b-1b91-4d1e-912e-846a7e84c579         <null>                                                             2          
-PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        Name                                                               string                     3            In                                                                 false     0            0            0            10           No Nulls    mmuuid:ea92812c-1516-4c75-b5d3-c531fdbd8475         <null>                                                             15         
-PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        OldValue                                                           clob                       1            ReturnValue                                                        false     0            2097152      0            10           No Nulls    mmuuid:48034d50-dd11-4653-aeae-b0d8d3d55656         <null>                                                             13         
-PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  RowsUpdated                                                        integer                    3            ReturnValue                                                        false     0            0            0            10           No Nulls    mmuuid:05a6a9be-c014-4d06-bcac-746cee4f118b         <null>                                                             3          
-PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     RowsUpdated                                                        integer                    3            ReturnValue                                                        false     0            0            0            10           No Nulls    mmuuid:d07a6a75-aa12-4dac-8eab-b2acdbaaffd8         <null>                                                             6          
-PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        UID                                                                string                     2            In                                                                 false     0            50           0            10           No Nulls    mmuuid:d377510e-2ec5-445e-bdf0-59c7c0380962         <null>                                                             14         
-PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        Value                                                              clob                       4            In                                                                 false     0            2097152      0            10           Nullable    mmuuid:ac5beeb8-2d0d-48ff-a533-4237d53b67e8         <null>                                                             16         
-PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  ViewName                                                           string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:ba635c44-a052-496d-9c35-ca010c0ebebe         <null>                                                             1          
-PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     ViewName                                                           string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:e0c28e00-d987-48e4-8c60-5f637f10bf33         <null>                                                             4          
-PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      cardinality                                                        integer                    2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:0aba7849-7fd3-4bc6-a3d3-dfe433bc67a4         <null>                                                             18         
-PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     columnName                                                         string                     2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:76553706-632f-4e60-8489-9d0361f58541         <null>                                                             8          
-PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     distinctCount                                                      integer                    3            In                                                                 false     0            0            0            10           Nullable    mmuuid:2c61976e-abb5-4c74-bdae-278681b82aa3         <null>                                                             9          
-PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      document                                                           string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:85b88af5-f0b8-401f-b35a-ccee56155492         <null>                                                             19         
-PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     max                                                                string                     5            In                                                                 false     0            0            0            10           Nullable    mmuuid:8f42e701-3609-413d-8c10-77e32cd816f2         <null>                                                             11         
-PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     min                                                                string                     6            In                                                                 false     0            0            0            10           Nullable    mmuuid:4511ea3f-f2d2-4abf-b363-afb5186bc2d2         <null>                                                             12         
-PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     nullCount                                                          integer                    4            In                                                                 false     0            0            0            10           Nullable    mmuuid:44b8c83c-9fcd-4bd2-a730-76e401205536         <null>                                                             10         
-PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      schema                                                             xml                        1            ResultSet                                                          false     0            0            0            10           Nullable    mmuuid:003980bb-38bb-41ad-b8c2-c87ca47aa554         <null>                                                             20         
-PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     tableName                                                          string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:4dcab018-ca4a-467b-96cc-7f28734c840e         <null>                                                             7          
-PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      tableName                                                          string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:28d8ad4a-e091-4934-afd9-7d27310bd370         <null>                                                             17         
-Row Count : 20
+PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     Invalidate                                                         boolean                    2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:5736cfd3-750f-42d8-b083-102061e11c60         <null>                                                             12         
+PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  Key                                                                object                     2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:7af5a63b-1b91-4d1e-912e-846a7e84c579         <null>                                                             9          
+PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        Name                                                               string                     3            In                                                                 false     0            0            0            10           No Nulls    mmuuid:ea92812c-1516-4c75-b5d3-c531fdbd8475         <null>                                                             22         
+PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        OldValue                                                           clob                       1            ReturnValue                                                        false     0            2097152      0            10           No Nulls    mmuuid:48034d50-dd11-4653-aeae-b0d8d3d55656         <null>                                                             20         
+PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  RowsUpdated                                                        integer                    3            ReturnValue                                                        false     0            0            0            10           No Nulls    mmuuid:05a6a9be-c014-4d06-bcac-746cee4f118b         <null>                                                             10         
+PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     RowsUpdated                                                        integer                    3            ReturnValue                                                        false     0            0            0            10           No Nulls    mmuuid:d07a6a75-aa12-4dac-8eab-b2acdbaaffd8         <null>                                                             13         
+PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        UID                                                                string                     2            In                                                                 false     0            50           0            10           No Nulls    mmuuid:d377510e-2ec5-445e-bdf0-59c7c0380962         <null>                                                             21         
+PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        Value                                                              clob                       4            In                                                                 false     0            2097152      0            10           Nullable    mmuuid:ac5beeb8-2d0d-48ff-a533-4237d53b67e8         <null>                                                             23         
+PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  ViewName                                                           string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:ba635c44-a052-496d-9c35-ca010c0ebebe         <null>                                                             8          
+PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     ViewName                                                           string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:e0c28e00-d987-48e4-8c60-5f637f10bf33         <null>                                                             11         
+PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      cardinality                                                        integer                    2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:0aba7849-7fd3-4bc6-a3d3-dfe433bc67a4         <null>                                                             25         
+PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     columnName                                                         string                     2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:76553706-632f-4e60-8489-9d0361f58541         <null>                                                             15         
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         context                                                            string                     3            In                                                                 false     0            0            0            10           No Nulls    mmuuid:d62e3ceb-8e58-4c22-96b7-d76ee923e180         <null>                                                             3          
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             context                                                            string                     3            In                                                                 false     0            0            0            10           No Nulls    mmuuid:c3f22b88-7f80-4ae3-8e60-6953722b8c38         <null>                                                             6          
+PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     distinctCount                                                      integer                    3            In                                                                 false     0            0            0            10           Nullable    mmuuid:2c61976e-abb5-4c74-bdae-278681b82aa3         <null>                                                             16         
+PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      document                                                           string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:85b88af5-f0b8-401f-b35a-ccee56155492         <null>                                                             26         
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         level                                                              string                     2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:995ab23a-3fd8-4ce0-aedd-6dcf99a65be1         <null>                                                             2          
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             level                                                              string                     2            In                                                                 false     0            0            0            10           No Nulls    mmuuid:ce0fd267-0038-49d5-ab1c-d8166d556b72         <null>                                                             5          
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         loggable                                                           boolean                    1            ReturnValue                                                        false     0            0            0            10           No Nulls    mmuuid:589773e4-2f8c-4972-ac0d-d694e317f154         <null>                                                             1          
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             logged                                                             boolean                    1            ReturnValue                                                        false     0            0            0            10           No Nulls    mmuuid:3086a5d9-ae1a-4c99-a649-ad9b8d3db8da         <null>                                                             4          
+PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     max                                                                string                     5            In                                                                 false     0            0            0            10           Nullable    mmuuid:8f42e701-3609-413d-8c10-77e32cd816f2         <null>                                                             18         
+PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     min                                                                string                     6            In                                                                 false     0            0            0            10           Nullable    mmuuid:4511ea3f-f2d2-4abf-b363-afb5186bc2d2         <null>                                                             19         
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             msg                                                                object                     4            In                                                                 false     0            0            0            10           No Nulls    mmuuid:81b921cc-9417-4655-898b-3d587ad3af16         <null>                                                             7          
+PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     nullCount                                                          integer                    4            In                                                                 false     0            0            0            10           Nullable    mmuuid:44b8c83c-9fcd-4bd2-a730-76e401205536         <null>                                                             17         
+PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      schema                                                             xml                        1            ResultSet                                                          false     0            0            0            10           Nullable    mmuuid:003980bb-38bb-41ad-b8c2-c87ca47aa554         <null>                                                             27         
+PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     tableName                                                          string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:4dcab018-ca4a-467b-96cc-7f28734c840e         <null>                                                             14         
+PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      tableName                                                          string                     1            In                                                                 false     0            0            0            10           No Nulls    mmuuid:28d8ad4a-e091-4934-afd9-7d27310bd370         <null>                                                             24         
+Row Count : 27
 getColumnName  getColumnType  getCatalogName  getColumnClassName  getColumnLabel  getColumnTypeName  getSchemaName  getTableName     getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 VDBName        12             PartsSupplier   java.lang.String    VDBName         string             SYS            ProcedureParams  255                   255           0         false            false            false       false                 0           true        true          false     false       
 SchemaName     12             PartsSupplier   java.lang.String    SchemaName      string             SYS            ProcedureParams  255                   255           0         false            true             false       true                  1           false       true          true      true        


Property changes on: branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedureParams.expected
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedureParams.expected:3220-3275
/trunk/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedureParams.expected:3188-3382

Modified: branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedures.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedures.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedures.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,12 +1,14 @@
 string                                                             string                                                             string                                                             string                                                             boolean         string                                              string                                                             integer    
 VDBName                                                            SchemaName                                                         Name                                                               NameInSource                                                       ReturnsResults  UID                                                 Description                                                        OID        
-PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      <null>                                                             true            mmuuid:68497bd9-30f5-461b-bf13-6b26aeb2fc4f         <null>                                                             6          
-PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     <null>                                                             false           mmuuid:52178344-dca8-4c76-8549-00a4515c7044         <null>                                                             2          
-PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  <null>                                                             false           mmuuid:1674912b-af56-465a-a1b9-d1de8b761f10         <null>                                                             1          
-PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     <null>                                                             false           mmuuid:49c367be-918f-43be-8b9e-99e275179859         <null>                                                             3          
-PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        <null>                                                             false           mmuuid:8db9b08e-3d6e-415a-9ceb-3fef726f424c         <null>                                                             4          
-PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      <null>                                                             false           mmuuid:6d167c35-04d1-41f6-83ff-888c39423823         <null>                                                             5          
-Row Count : 6
+PartsSupplier                                                      SYS                                                                getXMLSchemas                                                      <null>                                                             true            mmuuid:68497bd9-30f5-461b-bf13-6b26aeb2fc4f         <null>                                                             8          
+PartsSupplier                                                      SYSADMIN                                                           isLoggable                                                         <null>                                                             false           mmuuid:36769e93-4cc3-417b-853e-5ee5e6653d01         <null>                                                             1          
+PartsSupplier                                                      SYSADMIN                                                           logMsg                                                             <null>                                                             false           mmuuid:9a754e95-853b-40b2-a085-56d57f45953d         <null>                                                             2          
+PartsSupplier                                                      SYSADMIN                                                           refreshMatView                                                     <null>                                                             false           mmuuid:52178344-dca8-4c76-8549-00a4515c7044         <null>                                                             4          
+PartsSupplier                                                      SYSADMIN                                                           refreshMatViewRow                                                  <null>                                                             false           mmuuid:1674912b-af56-465a-a1b9-d1de8b761f10         <null>                                                             3          
+PartsSupplier                                                      SYSADMIN                                                           setColumnStats                                                     <null>                                                             false           mmuuid:49c367be-918f-43be-8b9e-99e275179859         <null>                                                             5          
+PartsSupplier                                                      SYSADMIN                                                           setProperty                                                        <null>                                                             false           mmuuid:8db9b08e-3d6e-415a-9ceb-3fef726f424c         <null>                                                             6          
+PartsSupplier                                                      SYSADMIN                                                           setTableStats                                                      <null>                                                             false           mmuuid:6d167c35-04d1-41f6-83ff-888c39423823         <null>                                                             7          
+Row Count : 8
 getColumnName   getColumnType  getCatalogName  getColumnClassName  getColumnLabel  getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 VDBName         12             PartsSupplier   java.lang.String    VDBName         string             SYS            Procedures    255                   255           0         false            false            false       false                 0           true        true          false     false       
 SchemaName      12             PartsSupplier   java.lang.String    SchemaName      string             SYS            Procedures    255                   255           0         false            true             false       true                  1           false       true          true      true        


Property changes on: branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedures.expected
___________________________________________________________________
Added: svn:mergeinfo
   + /branches/7.4.x/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedures.expected:3220-3275
/trunk/test-integration/common/src/test/resources/TestSystemVirtualModel/testProcedures.expected:3188-3382

Modified: branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testVDBResources.expected
===================================================================
--- branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testVDBResources.expected	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/common/src/test/resources/TestSystemVirtualModel/testVDBResources.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,25 +1,25 @@
 string                                                             blob                                                             
 resourcePath                                                       contents                                                         
+/MetaMatrix-VdbManifestModel.xmi                                   Blob[2393]                                                       
+/ConfigurationInfo.def                                             Blob[4830]                                                       
 /parts/partsmd/PartsSupplier.xmi                                   Blob[9655]                                                       
-/ConfigurationInfo.def                                             Blob[4830]                                                       
 /META-INF/MANIFEST.MF                                              Blob[25]                                                         
-/MetaMatrix-VdbManifestModel.xmi                                   Blob[2393]                                                       
 /runtime-inf/ANNOTATION.INDEX                                      Blob[8212]                                                       
-/runtime-inf/COLUMNS.INDEX                                         Blob[25021]                                                      
+/runtime-inf/MODELS.INDEX                                          Blob[24855]                                                      
+/runtime-inf/SELECT_TRANSFORM.INDEX                                Blob[8212]                                                       
+/runtime-inf/INSERT_TRANSFORM.INDEX                                Blob[8212]                                                       
 /runtime-inf/DATATYPES.INDEX                                       Blob[42378]                                                      
+/runtime-inf/VDBS.INDEX                                            Blob[24924]                                                      
 /runtime-inf/DELETE_TRANSFORM.INDEX                                Blob[8212]                                                       
+/runtime-inf/PROPERTIES.INDEX                                      Blob[8212]                                                       
+/runtime-inf/KEYS.INDEX                                            Blob[25014]                                                      
+/runtime-inf/UPDATE_TRANSFORM.INDEX                                Blob[8212]                                                       
 /runtime-inf/FILES.INDEX                                           Blob[8212]                                                       
-/runtime-inf/INSERT_TRANSFORM.INDEX                                Blob[8212]                                                       
-/runtime-inf/KEYS.INDEX                                            Blob[25014]                                                      
+/runtime-inf/PROCEDURES.INDEX                                      Blob[8212]                                                       
 /runtime-inf/MAPPING_TRANSFORM.INDEX                               Blob[8212]                                                       
-/runtime-inf/MODELS.INDEX                                          Blob[24855]                                                      
-/runtime-inf/PROCEDURES.INDEX                                      Blob[8212]                                                       
+/runtime-inf/COLUMNS.INDEX                                         Blob[25021]                                                      
+/runtime-inf/TABLES.INDEX                                          Blob[24947]                                                      
 /runtime-inf/PROC_TRANSFORM.INDEX                                  Blob[8212]                                                       
-/runtime-inf/PROPERTIES.INDEX                                      Blob[8212]                                                       
-/runtime-inf/SELECT_TRANSFORM.INDEX                                Blob[8212]                                                       
-/runtime-inf/TABLES.INDEX                                          Blob[24947]                                                      
-/runtime-inf/UPDATE_TRANSFORM.INDEX                                Blob[8212]                                                       
-/runtime-inf/VDBS.INDEX                                            Blob[24924]                                                      
 Row Count : 20
 getColumnName  getColumnType  getCatalogName  getColumnClassName  getColumnLabel  getColumnTypeName  getSchemaName  getTableName  getColumnDisplaySize  getPrecision  getScale  isAutoIncrement  isCaseSensitive  isCurrency  isDefinitelyWritable  isNullable  isReadOnly  isSearchable  isSigned  isWritable  
 resourcePath   12             PartsSupplier   java.lang.String    resourcePath    string             SYSADMIN       VDBResources  255                   255           0         false            true             false       false                 1           true        true          true      false       

Deleted: branches/as7/test-integration/common/src/test/resources/relate/VehicleRentalsVDB.vdb
===================================================================
(Binary files differ)

Copied: branches/as7/test-integration/common/src/test/resources/relate/VehicleRentalsVDB.vdb (from rev 3382, trunk/test-integration/common/src/test/resources/relate/VehicleRentalsVDB.vdb)
===================================================================
(Binary files differ)

Deleted: branches/as7/test-integration/common/src/test/resources/relate/rentals.sql
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/rentals.sql	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/rentals.sql	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,347 +0,0 @@
-CREATE TABLE "ACCESSORIES"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   ACCID varchar(10),
-   TYPE varchar(40),
-   MODEL varchar(15),
-   VERSION varchar(15)
-);
-CREATE TABLE "COLORS"
-(
-   COLORID varchar(10) primary key,
-   NAME varchar(42),
-   VEHICLEID varchar(10)
-);
-create index colors_vid_idx on colors (vehicleid);
-
-CREATE TABLE "COMPANIES"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   COMPANYID varchar(10) primary key,
-   FULLNAME varchar(40),
-   CLASSIFICATION varchar(15)
-);
-CREATE TABLE "LOCATIONS"
-(
-   LOCATIONID varchar(10),
-   NAME varchar(42),
-   COMPANYID varchar(10)
-);
-CREATE TABLE "REL_COMP_ACC"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   NATURE varchar(15),
-   SUBJECTTYPE varchar(40),
-   TARGETTYPE varchar(40),
-   COMPANYID varchar(10) NOT NULL,
-   ACCESSORYID varchar(10) NOT NULL,
-   QUANTITYAUTH int,
-   QUANTITYAVAIL int
-);
-CREATE TABLE "REL_COMP_SHARE"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   NATURE varchar(15),
-   SUBJECTTYPE varchar(40),
-   TARGETTYPE varchar(40),
-   PRIMARYID varchar(10),
-   SECONDARYID varchar(10),
-   SINCE numeric(10,0)
-);
-CREATE TABLE "REL_COMP_SUBSID"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   NATURE varchar(15),
-   SUBJECTTYPE varchar(40),
-   TARGETTYPE varchar(40),
-   COMPANYID varchar(10),
-   SUBSIDIARYID varchar(10),
-   PERCENTOWNS numeric(10,0)
-);
-CREATE TABLE "REL_COMP_VEH"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   NATURE varchar(15),
-   SUBJECTTYPE varchar(40),
-   TARGETTYPE varchar(40),
-   COMPANYID varchar(10) NOT NULL,
-   VEHICLEID varchar(10) NOT NULL,
-   QUANTITYAUTH int,
-   QUANTITYAVAIL int
-);
-CREATE TABLE "REL_VEH_ACC"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   NATURE varchar(15),
-   SUBJECTTYPE varchar(40),
-   TARGETTYPE varchar(40),
-   VEHICLEID varchar(10) NOT NULL,
-   ACCESSORYID varchar(10) NOT NULL,
-   QUANTITYAUTH int,
-   QUANTITYAVAIL int
-);
-CREATE TABLE "RENTAL_PRODUCTS"
-(
-   PRODUCTID varchar(10) NOT NULL,
-   DURATION varchar(42),
-   VEHICLEID varchar(10),
-   COMPANYID varchar(10)
-);
-CREATE TABLE "VEHICLES"
-(
-   COMMONNAME varchar(40),
-   UUID varchar(36),
-   QUUID varchar(36),
-   VEHICLEID varchar(10) primary key,
-   STYLE varchar(40),
-   MAKE varchar(15),
-   MODEL varchar(15),
-   MODELYEAR int
-);
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Emerson NV-5000','AUUID2','AQUUID2','AID2','GPS','Emerson','NV-5000');
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Garmin Street Pilot','AUUID1','AQUUID1','AID1','GPS','Garmin','Street Pilot');
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Gvox A0102','AUUID5','AQUUID5','AID5','DVD','Gvox','A0102');
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Gvox A0201','AUUID4','AQUUID4','AID4','DVD','Gvox','A0201');
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Pioneer AVIC-N2','AUUID6','AQUUID6','AID6','Navigation','Pioneer','AVIC-N2');
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Pioneer CD-VC60','AUUID8','AQUUID8','AID8','Voice Guidance','Pioneer','CD-VC60');
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Pyle PLDVD65IN','AUUID3','AQUUID3','AID3','DVD','Pyle','PLDVD65IN');
-
-INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Sanyo NV-E700','AUUID7','AQUUID7','AID7','Navigation','Sanyo','NV-E700');
-
-
-
-INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C1','Red','VID1');
-
-INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C2','Black','VID1');
-
-INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C3','Puce','VID2');
-
-INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C4','Red','VID3');
-
-INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C5','Black','VID4');
-
-
-
-INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Avian','CUUID1','CQUUID1','CID1','Avian Rentals, Inc.','Consumer');
-
-INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Budge','CUUID3','CQUUID3','CID3','Budge, Inc.','Wholesale');
-
-INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Entertwine','CUUID2','CQUUID2','CID2','Entertwine Rent A Car, Inc.','Consumer');
-
-INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Gigahertz','CUUID4','CQUUID4','CID4','Gigahertz, Inc.','Consumer');
-
-INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Peso','CUUID5','CQUUID5','CID5','Peso, Inc.','Consumer');
-
-INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Wholefleet','CUUID6','CQUUID6','CID6','Wholefleet, Inc.','Wholesale');
-
-
-
-INSERT INTO "LOCATIONS" (LOCATIONID,NAME,COMPANYID) VALUES ('LOC1','Pittsburgh','CID1');
-
-INSERT INTO "LOCATIONS" (LOCATIONID,NAME,COMPANYID) VALUES ('LOC2','Moosejaw','CID2');
-
-INSERT INTO "LOCATIONS" (LOCATIONID,NAME,COMPANYID) VALUES ('LOC3','Keokuk','CID1');
-
-
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA11','CAUUID11','CAQUUID11','offers','Company','Accessory','CID1','AID1',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA12','CAUUID12','CAQUUID12','offers','Company','Accessory','CID1','AID2',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA13','CAUUID13','CAQUUID13','offers','Company','Accessory','CID1','AID3',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA14','CAUUID14','CAQUUID14','offers','Company','Accessory','CID1','AID4',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA15','CAUUID15','CAQUUID15','offers','Company','Accessory','CID1','AID5',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA16','CAUUID16','CAQUUID16','offers','Company','Accessory','CID1','AID6',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA21','CAUUID21','CAQUUID21','offers','Company','Accessory','CID2','AID1',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA22','CAUUID22','CAQUUID22','offers','Company','Accessory','CID2','AID2',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA23','CAUUID23','CAQUUID23','offers','Company','Accessory','CID2','AID3',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA33','CAUUID33','CAQUUID33','offers','Company','Accessory','CID3','AID3',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA61','CAUUID61','CAQUUID61','offers','Company','Accessory','CID6','AID1',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA62','CAUUID62','CAQUUID62','offers','Company','Accessory','CID6','AID2',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA63','CAUUID63','CAQUUID63','offers','Company','Accessory','CID6','AID3',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA64','CAUUID64','CAQUUID64','offers','Company','Accessory','CID6','AID4',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA65','CAUUID65','CAQUUID65','offers','Company','Accessory','CID6','AID5',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA66','CAUUID66','CAQUUID66','offers','Company','Accessory','CID6','AID6',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA67','CAUUID67','CAQUUID67','offers','Company','Accessory','CID6','AID7',1,1);
-
-INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA68','CAUUID68','CAQUUID68','offers','Company','Accessory','CID6','AID8',1,1);
-
-
-
-INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC12','CCUUID12','CCQUUID12','sharesWith','Company','Company','CID1','CID2',1985);
-
-INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC13','CCUUID13','CCQUUID13','sharesWith','Company','Company','CID1','CID3',1995);
-
-INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC14','CCUUID14','CCQUUID14','sharesWith','Company','Company','CID1','CID4',2005);
-
-INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC34','CCUUID34','CCQUUID34','sharesWith','Company','Company','CID3','CID4',2001);
-
-INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC54','CCUUID54','CCQUUID54','sharesWith','Company','Company','CID5','CID4',1999);
-
-INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC64','CCUUID64','CCQUUID64','sharesWith','Company','Company','CID6','CID4',1995);
-
-
-
-INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS12','CSUUID12','CSQUUID12','owns','Company','Subsidiary','CID1','CID2',10);
-
-INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS13','CSUUID13','CSQUUID13','owns','Company','Subsidiary','CID1','CID3',50);
-
-INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS43','CSUUID43','CSQUUID43','owns','Company','Subsidiary','CID4','CID3',10);
-
-INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS56','CSUUID56','CSQUUID56','owns','Company','Subsidiary','CID5','CID6',100);
-
-
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV11','CVUUID11','CVQUUID11','rents','Company','Vehicle','CID1','VID1',10,2);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV12','CVUUID12','CVQUUID12','rents','Company','Vehicle','CID1','VID2',2,2);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV13','CVUUID13','CVQUUID13','rents','Company','Vehicle','CID1','VID3',2,0);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV14','CVUUID14','CVQUUID14','rents','Company','Vehicle','CID1','VID4',2,1);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV21','CVUUID21','CVQUUID21','rents','Company','Vehicle','CID2','VID1',5,3);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV22','CVUUID22','CVQUUID22','rents','Company','Vehicle','CID2','VID2',2,1);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV32','CVUUID32','CVQUUID32','rents','Company','Vehicle','CID3','VID2',1,1);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV47','CVUUID47','CVQUUID47','rents','Company','Vehicle','CID4','VID7',1,1);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV61','CVUUID61','CVQUUID61','rents','Company','Vehicle','CID6','VID1',1,1);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV62','CVUUID62','CVQUUID62','rents','Company','Vehicle','CID6','VID2',2,2);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV63','CVUUID63','CVQUUID63','rents','Company','Vehicle','CID6','VID3',3,3);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV64','CVUUID64','CVQUUID64','rents','Company','Vehicle','CID6','VID4',4,4);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV65','CVUUID65','CVQUUID65','rents','Company','Vehicle','CID6','VID5',5,5);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV66','CVUUID66','CVQUUID66','rents','Company','Vehicle','CID6','VID6',6,6);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV67','CVUUID67','CVQUUID67','rents','Company','Vehicle','CID6','VID7',7,7);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV68','CVUUID68','CVQUUID68','rents','Company','Vehicle','CID6','VID8',8,8);
-
-INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV69','CVUUID69','CVQUUID69','rents','Company','Vehicle','CID6','VID9',9,9);
-
-
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA11','VAUUID11','VAQUUID11','has','Vehicle','Accessory','VID1','AID1',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA12','VAUUID12','VAQUUID12','has','Vehicle','Accessory','VID1','AID2',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA13','VAUUID13','VAQUUID13','has','Vehicle','Accessory','VID1','AID3',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA23','VAUUID23','VAQUUID23','has','Vehicle','Accessory','VID2','AID3',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA34','VAUUID34','VAQUUID34','has','Vehicle','Accessory','VID3','AID4',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA35','VAUUID35','VAQUUID35','has','Vehicle','Accessory','VID3','AID5',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA41','VAUUID41','VAQUUID41','has','Vehicle','Accessory','VID4','AID1',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA45','VAUUID45','VAQUUID45','has','Vehicle','Accessory','VID4','AID5',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA46','VAUUID46','VAQUUID46','has','Vehicle','Accessory','VID4','AID6',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA51','VAUUID51','VAQUUID51','has','Vehicle','Accessory','VID5','AID1',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA53','VAUUID53','VAQUUID53','has','Vehicle','Accessory','VID5','AID3',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA55','VAUUID55','VAQUUID55','has','Vehicle','Accessory','VID5','AID5',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA57','VAUUID57','VAQUUID57','has','Vehicle','Accessory','VID5','AID7',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA62','VAUUID62','VAQUUID62','has','Vehicle','Accessory','VID6','AID2',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA64','VAUUID64','VAQUUID64','has','Vehicle','Accessory','VID6','AID4',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA66','VAUUID66','VAQUUID66','has','Vehicle','Accessory','VID6','AID6',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA68','VAUUID68','VAQUUID68','has','Vehicle','Accessory','VID6','AID8',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA88','VAUUID88','VAQUUID88','has','Vehicle','Accessory','VID8','AID8',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA91','VAUUID91','VAQUUID91','has','Vehicle','Accessory','VID9','AID1',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA92','VAUUID92','VAQUUID92','has','Vehicle','Accessory','VID9','AID2',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA93','VAUUID93','VAQUUID93','has','Vehicle','Accessory','VID9','AID3',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA94','VAUUID94','VAQUUID94','has','Vehicle','Accessory','VID9','AID4',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA95','VAUUID95','VAQUUID95','has','Vehicle','Accessory','VID9','AID5',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA96','VAUUID96','VAQUUID96','has','Vehicle','Accessory','VID9','AID6',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA97','VAUUID97','VAQUUID97','has','Vehicle','Accessory','VID9','AID7',1,1);
-
-INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA98','VAUUID98','VAQUUID98','has','Vehicle','Accessory','VID9','AID8',1,1);
-
-
-
-INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P1','Hourly','VID1','CID1');
-
-INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P2','Daily','VID1','CID1');
-
-INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P3','Weekly','VID1','CID1');
-
-INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P4','Weekly','VID2','CID1');
-
-
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Chevy Tahoe 2005','VUUID3','VQUUID3','VID3','Utility','Chevrolet','Tahoe',2005);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford F150 2004','VUUID2','VQUUID2','VID2','Utility','Ford','F150',2004);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford F150 2005','VUUID1','VQUUID1','VID1','Utility','Ford','F150',2005);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford Windstar 2004','VUUID5','VQUUID5','VID5','Minivan','Ford','Windstar',2004);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford Windstar 2005','VUUID4','VQUUID4','VID4','Minivan','Ford','Windstar',2005);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Honda Pilot 2005','VUUID9','VQUUID9','VID9','SUV','Honda','Pilot',2005);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Nissan Quest 2004','VUUID7','VQUUID7','VID7','Minivan','Nissan','Quest',2004);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Nissan Quest 2005','VUUID6','VQUUID6','VID6','Minivan','Nissan','Quest',2005);
-
-INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Toyota Sienna 2004','VUUID8','VQUUID8','VID8','Minivan','Toyota','Sienna',2004);
-

Copied: branches/as7/test-integration/common/src/test/resources/relate/rentals.sql (from rev 3382, trunk/test-integration/common/src/test/resources/relate/rentals.sql)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/rentals.sql	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/rentals.sql	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,347 @@
+CREATE TABLE "ACCESSORIES"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   ACCID varchar(10),
+   TYPE varchar(40),
+   MODEL varchar(15),
+   VERSION varchar(15)
+);
+CREATE TABLE "COLORS"
+(
+   COLORID varchar(10) primary key,
+   NAME varchar(42),
+   VEHICLEID varchar(10)
+);
+create index colors_vid_idx on colors (vehicleid);
+
+CREATE TABLE "COMPANIES"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   COMPANYID varchar(10) primary key,
+   FULLNAME varchar(40),
+   CLASSIFICATION varchar(15)
+);
+CREATE TABLE "LOCATIONS"
+(
+   LOCATIONID varchar(10),
+   NAME varchar(42),
+   COMPANYID varchar(10)
+);
+CREATE TABLE "REL_COMP_ACC"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   NATURE varchar(15),
+   SUBJECTTYPE varchar(40),
+   TARGETTYPE varchar(40),
+   COMPANYID varchar(10) NOT NULL,
+   ACCESSORYID varchar(10) NOT NULL,
+   QUANTITYAUTH int,
+   QUANTITYAVAIL int
+);
+CREATE TABLE "REL_COMP_SHARE"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   NATURE varchar(15),
+   SUBJECTTYPE varchar(40),
+   TARGETTYPE varchar(40),
+   PRIMARYID varchar(10),
+   SECONDARYID varchar(10),
+   SINCE numeric(10,0)
+);
+CREATE TABLE "REL_COMP_SUBSID"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   NATURE varchar(15),
+   SUBJECTTYPE varchar(40),
+   TARGETTYPE varchar(40),
+   COMPANYID varchar(10),
+   SUBSIDIARYID varchar(10),
+   PERCENTOWNS numeric(10,0)
+);
+CREATE TABLE "REL_COMP_VEH"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   NATURE varchar(15),
+   SUBJECTTYPE varchar(40),
+   TARGETTYPE varchar(40),
+   COMPANYID varchar(10) NOT NULL,
+   VEHICLEID varchar(10) NOT NULL,
+   QUANTITYAUTH int,
+   QUANTITYAVAIL int
+);
+CREATE TABLE "REL_VEH_ACC"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   NATURE varchar(15),
+   SUBJECTTYPE varchar(40),
+   TARGETTYPE varchar(40),
+   VEHICLEID varchar(10) NOT NULL,
+   ACCESSORYID varchar(10) NOT NULL,
+   QUANTITYAUTH int,
+   QUANTITYAVAIL int
+);
+CREATE TABLE "RENTAL_PRODUCTS"
+(
+   PRODUCTID varchar(10) NOT NULL,
+   DURATION varchar(42),
+   VEHICLEID varchar(10),
+   COMPANYID varchar(10)
+);
+CREATE TABLE "VEHICLES"
+(
+   COMMONNAME varchar(40),
+   UUID varchar(36),
+   QUUID varchar(36),
+   VEHICLEID varchar(10) primary key,
+   STYLE varchar(40),
+   MAKE varchar(15),
+   MODEL varchar(15),
+   MODELYEAR int
+);
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Emerson NV-5000','AUUID2','AQUUID2','AID2','GPS','Emerson','NV-5000');
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Garmin Street Pilot','AUUID1','AQUUID1','AID1','GPS','Garmin','Street Pilot');
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Gvox A0102','AUUID5','AQUUID5','AID5','DVD','Gvox','A0102');
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Gvox A0201','AUUID4','AQUUID4','AID4','DVD','Gvox','A0201');
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Pioneer AVIC-N2','AUUID6','AQUUID6','AID6','Navigation','Pioneer','AVIC-N2');
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Pioneer CD-VC60','AUUID8','AQUUID8','AID8','Voice Guidance','Pioneer','CD-VC60');
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Pyle PLDVD65IN','AUUID3','AQUUID3','AID3','DVD','Pyle','PLDVD65IN');
+
+INSERT INTO "ACCESSORIES" (COMMONNAME,UUID,QUUID,ACCID,TYPE,MODEL,VERSION) VALUES ('Sanyo NV-E700','AUUID7','AQUUID7','AID7','Navigation','Sanyo','NV-E700');
+
+
+
+INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C1','Red','VID1');
+
+INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C2','Black','VID1');
+
+INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C3','Puce','VID2');
+
+INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C4','Red','VID3');
+
+INSERT INTO "COLORS" (COLORID,NAME,VEHICLEID) VALUES ('C5','Black','VID4');
+
+
+
+INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Avian','CUUID1','CQUUID1','CID1','Avian Rentals, Inc.','Consumer');
+
+INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Budge','CUUID3','CQUUID3','CID3','Budge, Inc.','Wholesale');
+
+INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Entertwine','CUUID2','CQUUID2','CID2','Entertwine Rent A Car, Inc.','Consumer');
+
+INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Gigahertz','CUUID4','CQUUID4','CID4','Gigahertz, Inc.','Consumer');
+
+INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Peso','CUUID5','CQUUID5','CID5','Peso, Inc.','Consumer');
+
+INSERT INTO "COMPANIES" (COMMONNAME,UUID,QUUID,COMPANYID,FULLNAME,CLASSIFICATION) VALUES ('Wholefleet','CUUID6','CQUUID6','CID6','Wholefleet, Inc.','Wholesale');
+
+
+
+INSERT INTO "LOCATIONS" (LOCATIONID,NAME,COMPANYID) VALUES ('LOC1','Pittsburgh','CID1');
+
+INSERT INTO "LOCATIONS" (LOCATIONID,NAME,COMPANYID) VALUES ('LOC2','Moosejaw','CID2');
+
+INSERT INTO "LOCATIONS" (LOCATIONID,NAME,COMPANYID) VALUES ('LOC3','Keokuk','CID1');
+
+
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA11','CAUUID11','CAQUUID11','offers','Company','Accessory','CID1','AID1',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA12','CAUUID12','CAQUUID12','offers','Company','Accessory','CID1','AID2',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA13','CAUUID13','CAQUUID13','offers','Company','Accessory','CID1','AID3',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA14','CAUUID14','CAQUUID14','offers','Company','Accessory','CID1','AID4',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA15','CAUUID15','CAQUUID15','offers','Company','Accessory','CID1','AID5',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA16','CAUUID16','CAQUUID16','offers','Company','Accessory','CID1','AID6',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA21','CAUUID21','CAQUUID21','offers','Company','Accessory','CID2','AID1',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA22','CAUUID22','CAQUUID22','offers','Company','Accessory','CID2','AID2',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA23','CAUUID23','CAQUUID23','offers','Company','Accessory','CID2','AID3',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA33','CAUUID33','CAQUUID33','offers','Company','Accessory','CID3','AID3',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA61','CAUUID61','CAQUUID61','offers','Company','Accessory','CID6','AID1',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA62','CAUUID62','CAQUUID62','offers','Company','Accessory','CID6','AID2',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA63','CAUUID63','CAQUUID63','offers','Company','Accessory','CID6','AID3',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA64','CAUUID64','CAQUUID64','offers','Company','Accessory','CID6','AID4',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA65','CAUUID65','CAQUUID65','offers','Company','Accessory','CID6','AID5',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA66','CAUUID66','CAQUUID66','offers','Company','Accessory','CID6','AID6',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA67','CAUUID67','CAQUUID67','offers','Company','Accessory','CID6','AID7',1,1);
+
+INSERT INTO "REL_COMP_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCA68','CAUUID68','CAQUUID68','offers','Company','Accessory','CID6','AID8',1,1);
+
+
+
+INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC12','CCUUID12','CCQUUID12','sharesWith','Company','Company','CID1','CID2',1985);
+
+INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC13','CCUUID13','CCQUUID13','sharesWith','Company','Company','CID1','CID3',1995);
+
+INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC14','CCUUID14','CCQUUID14','sharesWith','Company','Company','CID1','CID4',2005);
+
+INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC34','CCUUID34','CCQUUID34','sharesWith','Company','Company','CID3','CID4',2001);
+
+INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC54','CCUUID54','CCQUUID54','sharesWith','Company','Company','CID5','CID4',1999);
+
+INSERT INTO "REL_COMP_SHARE" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,PRIMARYID,SECONDARYID,SINCE) VALUES ('RCC64','CCUUID64','CCQUUID64','sharesWith','Company','Company','CID6','CID4',1995);
+
+
+
+INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS12','CSUUID12','CSQUUID12','owns','Company','Subsidiary','CID1','CID2',10);
+
+INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS13','CSUUID13','CSQUUID13','owns','Company','Subsidiary','CID1','CID3',50);
+
+INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS43','CSUUID43','CSQUUID43','owns','Company','Subsidiary','CID4','CID3',10);
+
+INSERT INTO "REL_COMP_SUBSID" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,SUBSIDIARYID,PERCENTOWNS) VALUES ('RCS56','CSUUID56','CSQUUID56','owns','Company','Subsidiary','CID5','CID6',100);
+
+
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV11','CVUUID11','CVQUUID11','rents','Company','Vehicle','CID1','VID1',10,2);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV12','CVUUID12','CVQUUID12','rents','Company','Vehicle','CID1','VID2',2,2);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV13','CVUUID13','CVQUUID13','rents','Company','Vehicle','CID1','VID3',2,0);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV14','CVUUID14','CVQUUID14','rents','Company','Vehicle','CID1','VID4',2,1);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV21','CVUUID21','CVQUUID21','rents','Company','Vehicle','CID2','VID1',5,3);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV22','CVUUID22','CVQUUID22','rents','Company','Vehicle','CID2','VID2',2,1);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV32','CVUUID32','CVQUUID32','rents','Company','Vehicle','CID3','VID2',1,1);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV47','CVUUID47','CVQUUID47','rents','Company','Vehicle','CID4','VID7',1,1);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV61','CVUUID61','CVQUUID61','rents','Company','Vehicle','CID6','VID1',1,1);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV62','CVUUID62','CVQUUID62','rents','Company','Vehicle','CID6','VID2',2,2);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV63','CVUUID63','CVQUUID63','rents','Company','Vehicle','CID6','VID3',3,3);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV64','CVUUID64','CVQUUID64','rents','Company','Vehicle','CID6','VID4',4,4);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV65','CVUUID65','CVQUUID65','rents','Company','Vehicle','CID6','VID5',5,5);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV66','CVUUID66','CVQUUID66','rents','Company','Vehicle','CID6','VID6',6,6);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV67','CVUUID67','CVQUUID67','rents','Company','Vehicle','CID6','VID7',7,7);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV68','CVUUID68','CVQUUID68','rents','Company','Vehicle','CID6','VID8',8,8);
+
+INSERT INTO "REL_COMP_VEH" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,COMPANYID,VEHICLEID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RCV69','CVUUID69','CVQUUID69','rents','Company','Vehicle','CID6','VID9',9,9);
+
+
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA11','VAUUID11','VAQUUID11','has','Vehicle','Accessory','VID1','AID1',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA12','VAUUID12','VAQUUID12','has','Vehicle','Accessory','VID1','AID2',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA13','VAUUID13','VAQUUID13','has','Vehicle','Accessory','VID1','AID3',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA23','VAUUID23','VAQUUID23','has','Vehicle','Accessory','VID2','AID3',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA34','VAUUID34','VAQUUID34','has','Vehicle','Accessory','VID3','AID4',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA35','VAUUID35','VAQUUID35','has','Vehicle','Accessory','VID3','AID5',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA41','VAUUID41','VAQUUID41','has','Vehicle','Accessory','VID4','AID1',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA45','VAUUID45','VAQUUID45','has','Vehicle','Accessory','VID4','AID5',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA46','VAUUID46','VAQUUID46','has','Vehicle','Accessory','VID4','AID6',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA51','VAUUID51','VAQUUID51','has','Vehicle','Accessory','VID5','AID1',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA53','VAUUID53','VAQUUID53','has','Vehicle','Accessory','VID5','AID3',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA55','VAUUID55','VAQUUID55','has','Vehicle','Accessory','VID5','AID5',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA57','VAUUID57','VAQUUID57','has','Vehicle','Accessory','VID5','AID7',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA62','VAUUID62','VAQUUID62','has','Vehicle','Accessory','VID6','AID2',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA64','VAUUID64','VAQUUID64','has','Vehicle','Accessory','VID6','AID4',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA66','VAUUID66','VAQUUID66','has','Vehicle','Accessory','VID6','AID6',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA68','VAUUID68','VAQUUID68','has','Vehicle','Accessory','VID6','AID8',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA88','VAUUID88','VAQUUID88','has','Vehicle','Accessory','VID8','AID8',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA91','VAUUID91','VAQUUID91','has','Vehicle','Accessory','VID9','AID1',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA92','VAUUID92','VAQUUID92','has','Vehicle','Accessory','VID9','AID2',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA93','VAUUID93','VAQUUID93','has','Vehicle','Accessory','VID9','AID3',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA94','VAUUID94','VAQUUID94','has','Vehicle','Accessory','VID9','AID4',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA95','VAUUID95','VAQUUID95','has','Vehicle','Accessory','VID9','AID5',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA96','VAUUID96','VAQUUID96','has','Vehicle','Accessory','VID9','AID6',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA97','VAUUID97','VAQUUID97','has','Vehicle','Accessory','VID9','AID7',1,1);
+
+INSERT INTO "REL_VEH_ACC" (COMMONNAME,UUID,QUUID,NATURE,SUBJECTTYPE,TARGETTYPE,VEHICLEID,ACCESSORYID,QUANTITYAUTH,QUANTITYAVAIL) VALUES ('RVA98','VAUUID98','VAQUUID98','has','Vehicle','Accessory','VID9','AID8',1,1);
+
+
+
+INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P1','Hourly','VID1','CID1');
+
+INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P2','Daily','VID1','CID1');
+
+INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P3','Weekly','VID1','CID1');
+
+INSERT INTO "RENTAL_PRODUCTS" (PRODUCTID,DURATION,VEHICLEID,COMPANYID) VALUES ('P4','Weekly','VID2','CID1');
+
+
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Chevy Tahoe 2005','VUUID3','VQUUID3','VID3','Utility','Chevrolet','Tahoe',2005);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford F150 2004','VUUID2','VQUUID2','VID2','Utility','Ford','F150',2004);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford F150 2005','VUUID1','VQUUID1','VID1','Utility','Ford','F150',2005);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford Windstar 2004','VUUID5','VQUUID5','VID5','Minivan','Ford','Windstar',2004);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Ford Windstar 2005','VUUID4','VQUUID4','VID4','Minivan','Ford','Windstar',2005);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Honda Pilot 2005','VUUID9','VQUUID9','VID9','SUV','Honda','Pilot',2005);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Nissan Quest 2004','VUUID7','VQUUID7','VID7','Minivan','Nissan','Quest',2004);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Nissan Quest 2005','VUUID6','VQUUID6','VID6','Minivan','Nissan','Quest',2005);
+
+INSERT INTO "VEHICLES" (COMMONNAME,UUID,QUUID,VEHICLEID,STYLE,MAKE,MODEL,MODELYEAR) VALUES ('Toyota Sienna 2004','VUUID8','VQUUID8','VID8','Minivan','Toyota','Sienna',2004);
+

Deleted: branches/as7/test-integration/common/src/test/resources/relate/test.zip
===================================================================
(Binary files differ)

Copied: branches/as7/test-integration/common/src/test/resources/relate/test.zip (from rev 3382, trunk/test-integration/common/src/test/resources/relate/test.zip)
===================================================================
(Binary files differ)

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testCase3365.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testCase3365.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="C!
 ID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV32" uuid="CVUUID32" queryUUID="CVQUUID32" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID3" vehicleID="VID2"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV47" uuid="CVUUID47" queryUUID="CVQUUID47" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID4" vehicleID="VID7"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuth!
 orized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" query!
 UUID="CV
QUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" queryUUID="CVQUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" queryUUID="CVQUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6"!
  vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testCase3365.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testCase3365.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testCase3365.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="C!
 ID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV32" uuid="CVUUID32" queryUUID="CVQUUID32" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID3" vehicleID="VID2"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV47" uuid="CVUUID47" queryUUID="CVQUUID47" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID4" vehicleID="VID7"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuth!
 orized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" query!
 UUID="CV
QUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" queryUUID="CVQUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" queryUUID="CVQUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6"!
  vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="!
 CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV32" uuid="CVUUID32" queryUUID="CVQUUID32" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID3" vehicleID="VID2"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuth!
 orized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" queryUUID="CVQUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" query!
 UUID="CV
QUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" queryUUID="CVQUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6"!
  vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_compoundCritNestedTgt.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="!
 CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV32" uuid="CVUUID32" queryUUID="CVQUUID32" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID3" vehicleID="VID2"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuth!
 orized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" queryUUID="CVQUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" query!
 UUID="CV
QUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" queryUUID="CVQUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6"!
  vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_crit.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testCase3365_crit.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_crit.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_crit.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testCase3365_crit.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testCase3365_crit.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_crit.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrc.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location></rental:locations></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcCombinationContext.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location></rental:locations></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company common!
 Name="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV32" uuid="CVUUID32" queryUUID="CVQUUID32" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID3" vehicleID="VID2"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV47" uuid="CVUUID47" queryUUID="CVQUUID47" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID4" vehicleID="VID7"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuth!
 orized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" query!
 UUID="CV
QUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" queryUUID="CVQUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" queryUUID="CVQUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6"!
  vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedSrcContext.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company common!
 Name="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV32" uuid="CVUUID32" queryUUID="CVQUUID32" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID3" vehicleID="VID2"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV47" uuid="CVUUID47" queryUUID="CVQUUID47" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID4" vehicleID="VID7"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuth!
 orized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" query!
 UUID="CV
QUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" queryUUID="CVQUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" queryUUID="CVQUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6"!
  vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuth!
 orized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" queryUUID="CVQUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" queryUUID="CVQUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" query!
 UUID="CV
QUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testCase3365_critNestedTgt.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:rentsVehicle commonName="RCV11" uuid="CVUUID11" queryUUID="CVQUUID11" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID1"><rental:quantityAuthorized>10</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Hourly</rental:duration><rental:duration>Daily</rental:duration><rental:duration>Weekly</rental:duration></rental:rentalProducts></rental:rentsVehicle><rental:rentsVehicle commonName="RCV12" uuid="CVUUID12" queryUUID="CVQUUID12" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable><rental:rentalProducts><rental:duration>Weekly</rental:duration></rental:rentalProducts></rent!
 al:rentsVehicle><rental:rentsVehicle commonName="RCV13" uuid="CVUUID13" queryUUID="CVQUUID13" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID3"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>0</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV14" uuid="CVUUID14" queryUUID="CVQUUID14" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID1" vehicleID="VID4"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV21" uuid="CVUUID21" queryUUID="CVQUUID21" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID2" vehicleID="VID1"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV22" uuid="CVUUID22" queryUUID=!
 "CVQUUID22" nature="rents" subjectType="Company" targetType="V!
 ehicle" 
companyID="CID2" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV61" uuid="CVUUID61" queryUUID="CVQUUID61" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID1"><rental:quantityAuthorized>1</rental:quantityAuthorized><rental:quantityAvailable>1</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV62" uuid="CVUUID62" queryUUID="CVQUUID62" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID2"><rental:quantityAuthorized>2</rental:quantityAuthorized><rental:quantityAvailable>2</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV63" uuid="CVUUID63" queryUUID="CVQUUID63" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID3"><rental:quantityAuthorized>3</rental:quantityAuth!
 orized><rental:quantityAvailable>3</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV64" uuid="CVUUID64" queryUUID="CVQUUID64" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID4"><rental:quantityAuthorized>4</rental:quantityAuthorized><rental:quantityAvailable>4</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV65" uuid="CVUUID65" queryUUID="CVQUUID65" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID5"><rental:quantityAuthorized>5</rental:quantityAuthorized><rental:quantityAvailable>5</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV66" uuid="CVUUID66" queryUUID="CVQUUID66" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID6"><rental:quantityAuthorized>6</rental:quantityAuthorized><rental:quantityAvailable>6</rental:quantityAvailable></rental:rentsVehicle!
 ><rental:rentsVehicle commonName="RCV67" uuid="CVUUID67" query!
 UUID="CV
QUUID67" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID7"><rental:quantityAuthorized>7</rental:quantityAuthorized><rental:quantityAvailable>7</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV68" uuid="CVUUID68" queryUUID="CVQUUID68" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID8"><rental:quantityAuthorized>8</rental:quantityAuthorized><rental:quantityAvailable>8</rental:quantityAvailable></rental:rentsVehicle><rental:rentsVehicle commonName="RCV69" uuid="CVUUID69" queryUUID="CVQUUID69" nature="rents" subjectType="Company" targetType="Vehicle" companyID="CID6" vehicleID="VID9"><rental:quantityAuthorized>9</rental:quantityAuthorized><rental:quantityAvailable>9</rental:quantityAvailable></rental:rentsVehicle></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:vehicle commonName="Ford F150 2005" uuid="VUUID1" queryUUID="VQUUID1" vehicleID="VID1"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford F150 2004" uuid="VUUID2" queryUUID="VQUUID2" vehicleID="VID2"><rental:style>Utility</rental:style><rental:make>Ford</rental:make><rental:model>F150</rental:model><rental:year>2004</rental:year><rental:availablecolors><rental:color>Puce</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Chevy Tahoe 2005" uuid="VUUID3" queryUUID="VQUUID3" vehicleID="VID3"><rental:style>Utility</rental:style><rental:make>Chevrolet</rental!
 :make><rental:model>Tahoe</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Red</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2005" uuid="VUUID4" queryUUID="VQUUID4" vehicleID="VID4"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2005</rental:year><rental:availablecolors><rental:color>Black</rental:color></rental:availablecolors></rental:vehicle><rental:vehicle commonName="Ford Windstar 2004" uuid="VUUID5" queryUUID="VQUUID5" vehicleID="VID5"><rental:style>Minivan</rental:style><rental:make>Ford</rental:make><rental:model>Windstar</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Nissan Quest 2005" uuid="VUUID6" queryUUID="VQUUID6" vehicleID="VID6"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2005</rental:year></!
 rental:vehicle><rental:vehicle commonName="Nissan Quest 2004" !
 uuid="VU
UID7" queryUUID="VQUUID7" vehicleID="VID7"><rental:style>Minivan</rental:style><rental:make>Nissan</rental:make><rental:model>Quest</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Toyota Sienna 2004" uuid="VUUID8" queryUUID="VQUUID8" vehicleID="VID8"><rental:style>Minivan</rental:style><rental:make>Toyota</rental:make><rental:model>Sienna</rental:model><rental:year>2004</rental:year></rental:vehicle><rental:vehicle commonName="Honda Pilot 2005" uuid="VUUID9" queryUUID="VQUUID9" vehicleID="VID9"><rental:style>SUV</rental:style><rental:make>Honda</rental:make><rental:model>Pilot</rental:model><rental:year>2005</rental:year></rental:vehicle></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testSharesDoc.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testSharesDoc.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDoc.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Peso" uuid="CUUID5" queryUUID="CQUUID5" companyID="CID5"><rental:name>Peso, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><!
 /rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC12" uuid="CCUUID12" queryUUID="CCQUUID12" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID2" since="1985"/><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/><rental:hasSharingAgreement commonName="RCC14" uuid="CCUUID14" queryUUID="CCQUUID14" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID4" since="2005"/><rental:hasSharingAgreement commonName="RCC34" uuid="CCUUID34" queryUUID="CCQUUID34" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID3" secondaryPartyID="CID4" since="2001"/><rental:hasSha!
 ringAgreement commonName="RCC54" uuid="CCUUID54" queryUUID="CCQUUID54" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID5" secondaryPartyID="CID4" since="1999"/><rental:hasSharingAgreement commonName="RCC64" uuid="CCUUID64" queryUUID="CCQUUID64" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID6" secondaryPartyID="CID4" since="1995"/></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testSharesDoc.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testSharesDoc.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testSharesDoc.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDoc.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Peso" uuid="CUUID5" queryUUID="CQUUID5" companyID="CID5"><rental:name>Peso, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company><rental:company commonName="Wholefleet" uuid="CUUID6" queryUUID="CQUUID6" companyID="CID6"><rental:name>Wholefleet, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><!
 /rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC12" uuid="CCUUID12" queryUUID="CCQUUID12" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID2" since="1985"/><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/><rental:hasSharingAgreement commonName="RCC14" uuid="CCUUID14" queryUUID="CCQUUID14" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID4" since="2005"/><rental:hasSharingAgreement commonName="RCC34" uuid="CCUUID34" queryUUID="CCQUUID34" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID3" secondaryPartyID="CID4" since="2001"/><rental:hasSha!
 ringAgreement commonName="RCC54" uuid="CCUUID54" queryUUID="CCQUUID54" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID5" secondaryPartyID="CID4" since="1999"/><rental:hasSharingAgreement commonName="RCC64" uuid="CCUUID64" queryUUID="CCQUUID64" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID6" secondaryPartyID="CID4" since="1995"/></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC12" uuid="CCUUID12" queryUUID="CCQUUID12" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID2" since="1985"/><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/><rental:hasSharingAgreement commonName="RCC14" uuid="CCUUID14" queryUUID="CCQUUID14" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID4" since="2005"/></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDocEspaceQuestion3.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC12" uuid="CCUUID12" queryUUID="CCQUUID12" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID2" since="1985"/><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/><rental:hasSharingAgreement commonName="RCC14" uuid="CCUUID14" queryUUID="CCQUUID14" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID4" since="2005"/></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC12" uuid="CCUUID12" queryUUID="CCQUUID12" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID2" since="1985"/><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/><rental:hasSharingAgreement commonName="RCC14" uuid="CCUUID14" queryUUID="CCQUUID14" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID4" since="2005"/></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgt.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC12" uuid="CCUUID12" queryUUID="CCQUUID12" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID2" since="1985"/><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/><rental:hasSharingAgreement commonName="RCC14" uuid="CCUUID14" queryUUID="CCQUUID14" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID4" since="2005"/></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company><rental:company commonName="Entertwine" uuid="CUUID2" queryUUID="CQUUID2" companyID="CID2"><rental:name>Entertwine Rent A Car, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Moosejaw</rental:location></rental:locations></rental:company><rental:company commonName="Gigahertz" uuid="CUUID4" queryUUID="CQUUID4" companyID="CID4"><rental:name>Gigahertz, Inc.</rental:name><rental:type>Consumer</rental:type></rental:company></rental:rentals>

Deleted: branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected
===================================================================
--- trunk/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected	2011-08-15 18:31:49 UTC (rev 3382)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/></rental:rentals>
-<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>

Copied: branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected (from rev 3382, trunk/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected)
===================================================================
--- branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected	                        (rev 0)
+++ branches/as7/test-integration/common/src/test/resources/relate/testSharesDocWithCritTgtContext.expected	2011-08-18 16:17:24 UTC (rev 3394)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Avian" uuid="CUUID1" queryUUID="CQUUID1" companyID="CID1"><rental:name>Avian Rentals, Inc.</rental:name><rental:type>Consumer</rental:type><rental:locations><rental:location>Pittsburgh</rental:location><rental:location>Keokuk</rental:location></rental:locations></rental:company></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:hasSharingAgreement commonName="RCC13" uuid="CCUUID13" queryUUID="CCQUUID13" nature="sharesWith" subjectType="Company" targetType="Company" primaryPartyID="CID1" secondaryPartyID="CID3" since="1995"/></rental:rentals>
+<?xml version="1.0" encoding="UTF-8"?><rental:rentals xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:rental="urn:metamatrix:source:rental"><rental:company commonName="Budge" uuid="CUUID3" queryUUID="CQUUID3" companyID="CID3"><rental:name>Budge, Inc.</rental:name><rental:type>Wholesale</rental:type></rental:company></rental:rentals>

Modified: branches/as7/test-integration/db/pom.xml
===================================================================
--- branches/as7/test-integration/db/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/db/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -9,7 +9,7 @@
 	<parent>
 		<artifactId>teiid-test-integration</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 
 	<modelVersion>4.0.0</modelVersion>

Modified: branches/as7/test-integration/db/src/test/java/org/teiid/dynamicvdb/TestVDBLessExecution.java
===================================================================
--- branches/as7/test-integration/db/src/test/java/org/teiid/dynamicvdb/TestVDBLessExecution.java	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/db/src/test/java/org/teiid/dynamicvdb/TestVDBLessExecution.java	2011-08-18 16:17:24 UTC (rev 3394)
@@ -40,7 +40,7 @@
     private static final String DQP_PROP_FILE = UnitTestUtil.getTestDataPath() + "/vdbless/dqp.properties;user=test"; //$NON-NLS-1$
     private static final String VDB = "VDBLess"; //$NON-NLS-1$
 
-    @Test public void testExecution() {
+    @Test public void testExecution() throws Exception {
     	getConnection(VDB, DQP_PROP_FILE);
     	executeAndAssertResults("select * from Example", new String[] { //$NON-NLS-1$
     			"TRADEID[string]    NOTIONAL[integer]", //$NON-NLS-1$
@@ -51,7 +51,7 @@
     	closeConnection();
     }    
     
-    @Test public void testIntegrationExecution() {
+    @Test public void testIntegrationExecution() throws Exception {
     	getConnection(VDB, DQP_PROP_FILE);
     	executeAndAssertResults("select * from Example, Smalla where notional = intkey", new String[] { //$NON-NLS-1$
     			"TRADEID[string]    NOTIONAL[integer]    INTKEY[integer]    STRINGKEY[string]    INTNUM[integer]    STRINGNUM[string]    FLOATNUM[float]    LONGNUM[long]    DOUBLENUM[double]    BYTENUM[short]    DATEVALUE[date]    TIMEVALUE[time]    TIMESTAMPVALUE[timestamp]    BOOLEANVALUE[short]    CHARVALUE[string]    SHORTVALUE[short]    BIGINTEGERVALUE[long]    BIGDECIMALVALUE[bigdecimal]    OBJECTVALUE[string]", //$NON-NLS-1$
@@ -64,7 +64,7 @@
     /**
      * We have no results to assert here since derby does not provide procedure resultset columns in their metadata.
      */
-    @Test public void testProcedureExecution() {
+    @Test public void testProcedureExecution() throws Exception {
     	getConnection(VDB, DQP_PROP_FILE);
     	execute("exec Derby.SQLUDTS(null, null, null, null, null)"); //$NON-NLS-1$
     	closeConnection();

Modified: branches/as7/test-integration/pom.xml
===================================================================
--- branches/as7/test-integration/pom.xml	2011-08-17 20:56:07 UTC (rev 3393)
+++ branches/as7/test-integration/pom.xml	2011-08-18 16:17:24 UTC (rev 3394)
@@ -3,7 +3,7 @@
 	<parent>
 		<artifactId>teiid-parent</artifactId>
 		<groupId>org.jboss.teiid</groupId>
-		<version>7.5.0.Alpha1-SNAPSHOT</version>
+		<version>7.6.0.Alpha1-SNAPSHOT</version>
 	</parent>
 	<modelVersion>4.0.0</modelVersion>
 	<artifactId>teiid-test-integration</artifactId>
@@ -14,7 +14,7 @@
 	<properties>
 		<derby.version>10.2.1.6</derby.version>
 		<mysql.connector.version>5.1.5</mysql.connector.version>
-		<postgresql.version>8.3-603.jdbc3</postgresql.version>
+		<postgresql.version>8.4-702.jdbc4</postgresql.version>
 
 		<apache.ant.version>1.7.0</apache.ant.version>
 	</properties>
@@ -98,6 +98,22 @@
             <scope>provided</scope>
         </dependency>   		
          -->
+         
+    <dependency>
+        <groupId>org.jboss</groupId>
+        <artifactId>jboss-vfs</artifactId>
+        <scope>test</scope>
+    </dependency> 
+    <dependency>
+        <groupId>org.jboss.logging</groupId>
+        <artifactId>jboss-logging</artifactId>
+        <scope>test</scope>        
+    </dependency> 
+    <dependency>
+        <groupId>org.jboss.as</groupId>
+        <artifactId>jboss-as-security</artifactId>
+        <scope>provided</scope>
+    </dependency>              
 	</dependencies>
 
   <modules>



More information about the teiid-commits mailing list